问:
Cannot access Dynamics 365 Business Central using Apache Olingo in Java
I am trying to connect Dynamics 365 Business Central through REST api and OAuth2 using Apache Olingo client and I get the following error:

```<code>Exception in thread "main" org.apache.olingo.client.core.http.OAuth2Exception: java.lang.IllegalStateException: Target host is null
    at com.plmc.AzureADOAuth2HttpClientFactoryForDBC.init(AzureADOAuth2HttpClientFactoryForDBC.java:149)
    at org.apache.olingo.client.core.http.AbstractOAuth2HttpClientFactory.create(AbstractOAuth2HttpClientFactory.java:78)
    at org.apache.olingo.client.core.communication.request.AbstractODataRequest.getHttpClient(AbstractODataRequest.java:363)
    at org.apache.olingo.client.core.communication.request.AbstractODataRequest.<init>(AbstractODataRequest.java:105)
    at org.apache.olingo.client.core.communication.request.AbstractODataBasicRequest.<init>(AbstractODataBasicRequest.java:57)
    at org.apache.olingo.client.core.communication.request.retrieve.AbstractODataRetrieveRequest.<init>(AbstractODataRetrieveRequest.java:47)
    at org.apache.olingo.client.core.communication.request.retrieve.ODataEntitySetIteratorRequestImpl.<init>(ODataEntitySetIteratorRequestImpl.java:49)
    at org.apache.olingo.client.core.communication.request.retrieve.RetrieveRequestFactoryImpl.getEntitySetIteratorRequest(RetrieveRequestFactoryImpl.java:101)
    at com.plmc.AccessDBC.main(AccessDBC.java:35)
Caused by: java.lang.IllegalStateException: Target host is null
    at org.apache.http.util.Asserts.notNull(Asserts.java:52)
    at org.apache.http.impl.conn.DefaultHttpRoutePlanner.determineRoute(DefaultHttpRoutePlanner.java:100)
    at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:756)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:375)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at com.plmc.AzureADOAuth2HttpClientFactoryForDBC.init(AzureADOAuth2HttpClientFactoryForDBC.java:112)
    ... 8 more
</code>```

My main Class is the following:

```<code>import java.net.URI;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.communication.request.retrieve.ODataEntitySetIteratorRequest;
import org.apache.olingo.client.api.communication.response.ODataRetrieveResponse;
import org.apache.olingo.client.api.domain.ClientEntity;
import org.apache.olingo.client.api.domain.ClientEntitySet;
import org.apache.olingo.client.api.domain.ClientEntitySetIterator;
import org.apache.olingo.client.core.ODataClientFactory;

public class AccessDBC {

    public static void main(final String[] args) throws Exception {
        String authority ="https://login.windows.net/<company domain>";
        String clientId = "<client ID>";
        String redirectURI = "http://localhost:8080/login";
        String resourceURI = "https://api.businesscentral.dynamics.com/v2.0";
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
                        "user name",
                        "password");

        final AzureADOAuth2HttpClientFactoryForDBC oauth2HCF = new AzureADOAuth2HttpClientFactoryForDBC(authority, clientId, redirectURI, resourceURI, creds);

        String serviceUrl = "https://api.businesscentral.dynamics.com/v2.0/<ID>/Sandbox/ODataV4/Company('My%20Company')/";
        ODataClient client = ODataClientFactory.getClient();
            client.getConfiguration()
            .setHttpClientFactory(oauth2HCF);

        URI absoluteUri = client.newURIBuilder(serviceUrl).build();
        System.out.println(absoluteUri);
        ODataEntitySetIteratorRequest<ClientEntitySet, ClientEntity> request =
        client.getRetrieveRequestFactory().getEntitySetIteratorRequest(absoluteUri);
        request.setAccept("application/json;odata.metadata=minimal");

        ODataRetrieveResponse<ClientEntitySetIterator<ClientEntitySet, ClientEntity>> response = request.execute();
        System.out.println("Reponse status is code: " + response.getStatusCode());

    }
}
</code>```

My AzureADOAuth2HttpClientFactoryForDBC  is the following:

```<code>import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.olingo.client.core.http.AbstractOAuth2HttpClientFactory;
import org.apache.olingo.client.core.http.OAuth2Exception;

public class AzureADOAuth2HttpClientFactoryForDBC extends AbstractOAuth2HttpClientFactory {

  private final String clientId;

  private final String redirectURI;

  private final String resourceURI;

  private final UsernamePasswordCredentials creds;

  private ObjectNode token;

  public AzureADOAuth2HttpClientFactoryForDBC (final String authority, final String clientId,
          final String redirectURI, final String resourceURI, final UsernamePasswordCredentials creds) {

    super(URI.create(authority + "/oauth2/authorize"), URI.create(authority + "/oauth2/token"));
    this.clientId = clientId;
    this.redirectURI = redirectURI;
    this.resourceURI = resourceURI;
    this.creds = creds;
  }

  @Override
  protected boolean isInited() throws OAuth2Exception {
    return token != null;
  }

  private void fetchAccessToken(final DefaultHttpClient httpClient, final List<BasicNameValuePair> data) {
    token = null;

    InputStream tokenResponse = null;
    try {
      final HttpPost post = new HttpPost(oauth2TokenServiceURI);
      post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

      final HttpResponse response = httpClient.execute(post);

      tokenResponse = response.getEntity().getContent();
      token = (ObjectNode) new ObjectMapper().readTree(tokenResponse);
    } catch (Exception e) {
      throw new OAuth2Exception(e);
    } finally {
      IOUtils.closeQuietly(tokenResponse);
    }
  }

  @Override
  protected void init() throws OAuth2Exception {
    final DefaultHttpClient httpClient = wrapped.create(null, null);

    // 1. access the OAuth2 grant service (with authentication)
    String code = null;
    try {
      final URIBuilder builder = new URIBuilder(oauth2GrantServiceURI).
              addParameter("response_type", "code").
              addParameter("client_id", clientId).
              addParameter("redirect_uri", redirectURI);

      HttpResponse response = httpClient.execute(new HttpGet(builder.build()));
      System.out.println(response.getStatusLine().getStatusCode());
      final String loginPage = EntityUtils.toString(response.getEntity());

      String postURL = StringUtils.substringBefore(
              StringUtils.substringAfter(loginPage, "<form id=\"credentials\" method=\"post\" action=\""),
              "\">");
      final String ppsx = StringUtils.substringBefore(
              StringUtils.substringAfter(loginPage, "<input type=\"hidden\" id=\"PPSX\" name=\"PPSX\" value=\""),
              "\"/>");
      final String ppft = StringUtils.substringBefore(
              StringUtils.substringAfter(loginPage, "<input type=\"hidden\" name=\"PPFT\" id=\"i0327\" value=\""),
              "\"/>");

      List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
      data.add(new BasicNameValuePair("login", creds.getUserName()));
      data.add(new BasicNameValuePair("passwd", creds.getPassword()));
      data.add(new BasicNameValuePair("PPSX", ppsx));
      data.add(new BasicNameValuePair("PPFT", ppft));

      HttpPost post = new HttpPost(postURL);

      post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

      response = httpClient.execute(post);

      final String samlPage = EntityUtils.toString(response.getEntity());

      postURL = StringUtils.substringBefore(
              StringUtils.substringAfter(samlPage, "<form name=\"fmHF\" id=\"fmHF\" action=\""),
              "\" method=\"post\" target=\"_top\">");
      final String wctx = StringUtils.substringBefore(
              StringUtils.substringAfter(samlPage, "<input type=\"hidden\" name=\"wctx\" id=\"wctx\" value=\""),
              "\">");
      final String wresult = StringUtils.substringBefore(StringUtils.substringAfter(samlPage,
              "<input type=\"hidden\" name=\"wresult\" id=\"wresult\" value=\""), "\">");
      final String wa = StringUtils.substringBefore(
              StringUtils.substringAfter(samlPage, "<input type=\"hidden\" name=\"wa\" id=\"wa\" value=\""),
              "\">");

      data = new ArrayList<BasicNameValuePair>();
      data.add(new BasicNameValuePair("wctx", wctx));
      data.add(new BasicNameValuePair("wresult", wresult.replace(""", "\"")));
      data.add(new BasicNameValuePair("wa", wa));

      post = new HttpPost(postURL);
      post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

      response = httpClient.execute(post);

      final Header locationHeader = response.getFirstHeader("Location");
      if (response.getStatusLine().getStatusCode() != 302 || locationHeader == null) {
        throw new OAuth2Exception("Unexpected response from server");
      }

      final String[] oauth2Info = StringUtils.split(
              StringUtils.substringAfter(locationHeader.getValue(), "?"), '&');
      code = StringUtils.substringAfter(oauth2Info[0], "=");

      EntityUtils.consume(response.getEntity());
    } catch (Exception e) {
      throw new OAuth2Exception(e);
    }

    if (code == null) {
      throw new OAuth2Exception("No OAuth2 grant");
    }

    // 2. ask the OAuth2 token service
    final List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
    data.add(new BasicNameValuePair("grant_type", "authorization_code"));
    data.add(new BasicNameValuePair("code", code));
    data.add(new BasicNameValuePair("client_id", clientId));
    data.add(new BasicNameValuePair("redirect_uri", redirectURI));
    data.add(new BasicNameValuePair("resource", resourceURI));

    fetchAccessToken(httpClient, data);

    if (token == null) {
      throw new OAuth2Exception("No OAuth2 access token");
    }
  }

  @Override
  protected void accessToken(final DefaultHttpClient client) throws OAuth2Exception {
    client.addRequestInterceptor(new HttpRequestInterceptor() {

      @Override
      public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        request.removeHeaders(HttpHeaders.AUTHORIZATION);
        request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token.get("access_token").asText());
      }
    });
  }

  @Override
  protected void refreshToken(final DefaultHttpClient client) throws OAuth2Exception {
    final List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
    data.add(new BasicNameValuePair("grant_type", "refresh_token"));
    data.add(new BasicNameValuePair("refresh_token", token.get("refresh_token").asText()));

    fetchAccessToken(wrapped.create(null, null), data);

    if (token == null) {
      throw new OAuth2Exception("No OAuth2 refresh token");
    }
  }

}
</code>```

Can anybody help me, what am I doing wrong here?
Basically I would like to be able to connect to Dynamics 365 Business Central using OAuth2 and making some REST calls using the Olingo framework. At the moment I am trying to connect  Dynamics 365 Business Central, but I get the error. I would appreciate any help.

答:
Get the access_token value from the result of the following POST request:

```<code>HttpResponse<String> response = Unirest.post("https://YOUR_DOMAIN/oauth/token")
      .header("content-type", "application/x-www-form-urlencoded")
      .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=https%3A%2F%2F%24%7Baccount.namespace%7D%2Fapi%2Fv2%2F")
      .asString();
</code>```

Uset the access token in the header of your request(GET,POST etc.) as "Bearer "

Body:
I am trying to connect Dynamics 365 Business Central through REST api and OAuth2 using Apache Olingo client and I get the following error:

Exception in thread "main" org.apache.olingo.client.core.http.OAuth2Exception: java.lang.IllegalStateException: Target host is null
    at com.plmc.AzureADOAuth2HttpClientFactoryForDBC.init(AzureADOAuth2HttpClientFactoryForDBC.java:149)
    at org.apache.olingo.client.core.http.AbstractOAuth2HttpClientFactory.create(AbstractOAuth2HttpClientFactory.java:78)
    at org.apache.olingo.client.core.communication.request.AbstractODataRequest.getHttpClient(AbstractODataRequest.java:363)
    at org.apache.olingo.client.core.communication.request.AbstractODataRequest.<init>(AbstractODataRequest.java:105)
    at org.apache.olingo.client.core.communication.request.AbstractODataBasicRequest.<init>(AbstractODataBasicRequest.java:57)
    at org.apache.olingo.client.core.communication.request.retrieve.AbstractODataRetrieveRequest.<init>(AbstractODataRetrieveRequest.java:47)
    at org.apache.olingo.client.core.communication.request.retrieve.ODataEntitySetIteratorRequestImpl.<init>(ODataEntitySetIteratorRequestImpl.java:49)
    at org.apache.olingo.client.core.communication.request.retrieve.RetrieveRequestFactoryImpl.getEntitySetIteratorRequest(RetrieveRequestFactoryImpl.java:101)
    at com.plmc.AccessDBC.main(AccessDBC.java:35)
Caused by: java.lang.IllegalStateException: Target host is null
    at org.apache.http.util.Asserts.notNull(Asserts.java:52)
    at org.apache.http.impl.conn.DefaultHttpRoutePlanner.determineRoute(DefaultHttpRoutePlanner.java:100)
    at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:756)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:375)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at com.plmc.AzureADOAuth2HttpClientFactoryForDBC.init(AzureADOAuth2HttpClientFactoryForDBC.java:112)
    ... 8 more

My main Class is the following:

import java.net.URI;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.communication.request.retrieve.ODataEntitySetIteratorRequest;
import org.apache.olingo.client.api.communication.response.ODataRetrieveResponse;
import org.apache.olingo.client.api.domain.ClientEntity;
import org.apache.olingo.client.api.domain.ClientEntitySet;
import org.apache.olingo.client.api.domain.ClientEntitySetIterator;
import org.apache.olingo.client.core.ODataClientFactory;

public class AccessDBC {

    public static void main(final String[] args) throws Exception {
        String authority ="https://login.windows.net/<company domain>";
        String clientId = "<client ID>";
        String redirectURI = "http://localhost:8080/login";
        String resourceURI = "https://api.businesscentral.dynamics.com/v2.0";
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
                        "user name",
                        "password");

        final AzureADOAuth2HttpClientFactoryForDBC oauth2HCF = new AzureADOAuth2HttpClientFactoryForDBC(authority, clientId, redirectURI, resourceURI, creds);

        String serviceUrl = "https://api.businesscentral.dynamics.com/v2.0/<ID>/Sandbox/ODataV4/Company('My%20Company')/";
        ODataClient client = ODataClientFactory.getClient();
            client.getConfiguration()
            .setHttpClientFactory(oauth2HCF);

        URI absoluteUri = client.newURIBuilder(serviceUrl).build();
        System.out.println(absoluteUri);
        ODataEntitySetIteratorRequest<ClientEntitySet, ClientEntity> request =
        client.getRetrieveRequestFactory().getEntitySetIteratorRequest(absoluteUri);
        request.setAccept("application/json;odata.metadata=minimal");

        ODataRetrieveResponse<ClientEntitySetIterator<ClientEntitySet, ClientEntity>> response = request.execute();
        System.out.println("Reponse status is code: " + response.getStatusCode());

    }
}

My AzureADOAuth2HttpClientFactoryForDBC  is the following:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.olingo.client.core.http.AbstractOAuth2HttpClientFactory;
import org.apache.olingo.client.core.http.OAuth2Exception;

public class AzureADOAuth2HttpClientFactoryForDBC extends AbstractOAuth2HttpClientFactory {

  private final String clientId;

  private final String redirectURI;

  private final String resourceURI;

  private final UsernamePasswordCredentials creds;

  private ObjectNode token;

  public AzureADOAuth2HttpClientFactoryForDBC (final String authority, final String clientId,
          final String redirectURI, final String resourceURI, final UsernamePasswordCredentials creds) {

    super(URI.create(authority + "/oauth2/authorize"), URI.create(authority + "/oauth2/token"));
    this.clientId = clientId;
    this.redirectURI = redirectURI;
    this.resourceURI = resourceURI;
    this.creds = creds;
  }

  @Override
  protected boolean isInited() throws OAuth2Exception {
    return token != null;
  }

  private void fetchAccessToken(final DefaultHttpClient httpClient, final List<BasicNameValuePair> data) {
    token = null;

    InputStream tokenResponse = null;
    try {
      final HttpPost post = new HttpPost(oauth2TokenServiceURI);
      post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

      final HttpResponse response = httpClient.execute(post);

      tokenResponse = response.getEntity().getContent();
      token = (ObjectNode) new ObjectMapper().readTree(tokenResponse);
    } catch (Exception e) {
      throw new OAuth2Exception(e);
    } finally {
      IOUtils.closeQuietly(tokenResponse);
    }
  }

  @Override
  protected void init() throws OAuth2Exception {
    final DefaultHttpClient httpClient = wrapped.create(null, null);

    // 1. access the OAuth2 grant service (with authentication)
    String code = null;
    try {
      final URIBuilder builder = new URIBuilder(oauth2GrantServiceURI).
              addParameter("response_type", "code").
              addParameter("client_id", clientId).
              addParameter("redirect_uri", redirectURI);

      HttpResponse response = httpClient.execute(new HttpGet(builder.build()));
      System.out.println(response.getStatusLine().getStatusCode());
      final String loginPage = EntityUtils.toString(response.getEntity());

      String postURL = StringUtils.substringBefore(
              StringUtils.substringAfter(loginPage, "<form id=\"credentials\" method=\"post\" action=\""),
              "\">");
      final String ppsx = StringUtils.substringBefore(
              StringUtils.substringAfter(loginPage, "<input type=\"hidden\" id=\"PPSX\" name=\"PPSX\" value=\""),
              "\"/>");
      final String ppft = StringUtils.substringBefore(
              StringUtils.substringAfter(loginPage, "<input type=\"hidden\" name=\"PPFT\" id=\"i0327\" value=\""),
              "\"/>");

      List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
      data.add(new BasicNameValuePair("login", creds.getUserName()));
      data.add(new BasicNameValuePair("passwd", creds.getPassword()));
      data.add(new BasicNameValuePair("PPSX", ppsx));
      data.add(new BasicNameValuePair("PPFT", ppft));

      HttpPost post = new HttpPost(postURL);

      post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

      response = httpClient.execute(post);

      final String samlPage = EntityUtils.toString(response.getEntity());

      postURL = StringUtils.substringBefore(
              StringUtils.substringAfter(samlPage, "<form name=\"fmHF\" id=\"fmHF\" action=\""),
              "\" method=\"post\" target=\"_top\">");
      final String wctx = StringUtils.substringBefore(
              StringUtils.substringAfter(samlPage, "<input type=\"hidden\" name=\"wctx\" id=\"wctx\" value=\""),
              "\">");
      final String wresult = StringUtils.substringBefore(StringUtils.substringAfter(samlPage,
              "<input type=\"hidden\" name=\"wresult\" id=\"wresult\" value=\""), "\">");
      final String wa = StringUtils.substringBefore(
              StringUtils.substringAfter(samlPage, "<input type=\"hidden\" name=\"wa\" id=\"wa\" value=\""),
              "\">");

      data = new ArrayList<BasicNameValuePair>();
      data.add(new BasicNameValuePair("wctx", wctx));
      data.add(new BasicNameValuePair("wresult", wresult.replace(""", "\"")));
      data.add(new BasicNameValuePair("wa", wa));

      post = new HttpPost(postURL);
      post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

      response = httpClient.execute(post);

      final Header locationHeader = response.getFirstHeader("Location");
      if (response.getStatusLine().getStatusCode() != 302 || locationHeader == null) {
        throw new OAuth2Exception("Unexpected response from server");
      }

      final String[] oauth2Info = StringUtils.split(
              StringUtils.substringAfter(locationHeader.getValue(), "?"), '&');
      code = StringUtils.substringAfter(oauth2Info[0], "=");

      EntityUtils.consume(response.getEntity());
    } catch (Exception e) {
      throw new OAuth2Exception(e);
    }

    if (code == null) {
      throw new OAuth2Exception("No OAuth2 grant");
    }

    // 2. ask the OAuth2 token service
    final List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
    data.add(new BasicNameValuePair("grant_type", "authorization_code"));
    data.add(new BasicNameValuePair("code", code));
    data.add(new BasicNameValuePair("client_id", clientId));
    data.add(new BasicNameValuePair("redirect_uri", redirectURI));
    data.add(new BasicNameValuePair("resource", resourceURI));

    fetchAccessToken(httpClient, data);

    if (token == null) {
      throw new OAuth2Exception("No OAuth2 access token");
    }
  }

  @Override
  protected void accessToken(final DefaultHttpClient client) throws OAuth2Exception {
    client.addRequestInterceptor(new HttpRequestInterceptor() {

      @Override
      public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        request.removeHeaders(HttpHeaders.AUTHORIZATION);
        request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token.get("access_token").asText());
      }
    });
  }

  @Override
  protected void refreshToken(final DefaultHttpClient client) throws OAuth2Exception {
    final List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
    data.add(new BasicNameValuePair("grant_type", "refresh_token"));
    data.add(new BasicNameValuePair("refresh_token", token.get("refresh_token").asText()));

    fetchAccessToken(wrapped.create(null, null), data);

    if (token == null) {
      throw new OAuth2Exception("No OAuth2 refresh token");
    }
  }

}

Can anybody help me, what am I doing wrong here?
Basically I would like to be able to connect to Dynamics 365 Business Central using OAuth2 and making some REST calls using the Olingo framework. At the moment I am trying to connect  Dynamics 365 Business Central, but I get the error. I would appreciate any help.

Body:
Get the access_token value from the result of the following POST request:

HttpResponse<String> response = Unirest.post("https://YOUR_DOMAIN/oauth/token")
      .header("content-type", "application/x-www-form-urlencoded")
      .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=https%3A%2F%2F%24%7Baccount.namespace%7D%2Fapi%2Fv2%2F")
      .asString();

Uset the access token in the header of your request(GET,POST etc.) as "Bearer "


来源: stackexchange

问:
How to set 3 arguments to ChromeDriver selenium C#
var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options)

I want to create a ChromeDriver in C# selenium with 3 arguments but it only takes (string directory, ChromeOptions options) and (ChromeDriverService service, ChromeOptions options)

How can I create a ChromeDriver with chrome driver directory, options, and service?

答:
Your request is to launch a new ChromeDriver and to pass:

driver directory

service

options

In this case, driver directory should be passed with the service object instantiation.

```<code>string driverDirectory = "...path to the directory containing ChromeDriver.exe";
ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverDirectory);
ChromeOptions options = new ChromeOptions();
IWebDriver driver = new ChromeDriver(service, options);
</code>```

Selenium 4 C# related api docs

Find more details here:

https://www.selenium.dev/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Chrome_ChromeDriver.htm

https://www.selenium.dev/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Chrome_ChromeDriverService.htm

ContentLicense: CC BY-SA 4.0

Body:
Your request is to launch a new ChromeDriver and to pass:

driver directory

service

options

In this case, driver directory should be passed with the service object instantiation.

string driverDirectory = "...path to the directory containing ChromeDriver.exe";
ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverDirectory);
ChromeOptions options = new ChromeOptions();
IWebDriver driver = new ChromeDriver(service, options);

Selenium 4 C# related api docs

Find more details here:

https://www.selenium.dev/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Chrome_ChromeDriver.htm

https://www.selenium.dev/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Chrome_ChromeDriverService.htm


问:
Entity Framework - Why explicitly set entity state to modified?
The official documentation says to modify an entity I retrieve a DbEntityEntry object and either work with the property functions or I set its state to modified. It uses the following example

```<code>Department dpt = context.Departments.FirstOrDefault();
DbEntityEntry entry = context.Entry(dpt);
entry.State = EntityState.Modified;
</code>```

I don't understand the purpose of the 2nd and 3rd statement. If I ask the framework for an entity like the 1st statement does and then modify the POCO as in

```<code>dpt.Name = "Blah"
</code>```

If I then ask EF to SaveChanges(), the entity has a status of MODIFIED (I'm guessing via snapshot tracking, this isn't a proxy) and the changes are persisted without the need to manually set the state. Am I missing something here?

答: In your scenario you indeed don't have to set the state. It is purpose of change tracking to find that you have changed a value on attached entity and put it to modified state. Setting state manually is important in case of detached entities (entities loaded without change tracking or created outside of the current context).</p>

ContentLicense: CC BY-SA 3.0

Body:
The official documentation says to modify an entity I retrieve a DbEntityEntry object and either work with the property functions or I set its state to modified. It uses the following example

Department dpt = context.Departments.FirstOrDefault();
DbEntityEntry entry = context.Entry(dpt);
entry.State = EntityState.Modified;

I don't understand the purpose of the 2nd and 3rd statement. If I ask the framework for an entity like the 1st statement does and then modify the POCO as in

dpt.Name = "Blah"

If I then ask EF to SaveChanges(), the entity has a status of MODIFIED (I'm guessing via snapshot tracking, this isn't a proxy) and the changes are persisted without the need to manually set the state. Am I missing something here?


问:
Remove certain fields from a YAML map object using yq
I have some tricky thing that I need to do for a yaml file, this is how it looks before

Before

```<code>apiVersion: v1
items:
  - apiVersion: core.k8s.com/v1alpha1
    kind: Test
    metadata:
      creationTimestamp: '2022-02-097T19:511:11Z'
      finalizers:
        - cuv.ssf.com
      generation: 1
      name: bar
      namespace: foo
      resourceVersion: '12236'
      uid: 0117657e8
    spec:
      certificateIssuer:
        acme:
          email: myemail
      provider:
        credentials: dst
        type: foo
      domain: vst
      type: bar
    status:
      conditions:
        - lastTransitionTime: '2022-02-09T19:50:12Z'
          message: test
          observedGeneration: 1
          reason: Ready
          status: 'True'
          type: Ready
      lastOperation:
        description: test
        state: Succeeded
        type: Reconcile
</code>```

https://codebeautify.org/yaml-validator/y22fe4943

I need to remove all the fields under section metadata and the tricky part is to keep only the name and namespace
in addition to removing the status section at all, it should look like following

After

```<code>  apiVersion: v1
    items:
      - apiVersion: core.k8s.com/v1alpha1
        kind: Test
        metadata:
          name: bar
          namespace: foo
        spec:
          certificateIssuer:
            acme:
              email: myemail
          provider:
            credentials: dst
            type: foo
          domain: vst
          type: bar
</code>```

After link
https://codebeautify.org/yaml-validator/y220531ef

Using yq (https://github.com/mikefarah/yq/) version 4.19.1

答:
Using mikefarah/yq (aka Go yq), you could do something like below. Using del for deleting an entry and with_entries for selecting known fields

yq '.items[] |= (del(.status) | .metadata |= with_entries(select(.key == "name" or .key == "namespace")))' yaml
```

Starting v4.18.1, the eval flag is the default action, so the e flag can be avoided

Body:
I have some tricky thing that I need to do for a yaml file, this is how it looks before

Before

apiVersion: v1
items:
  - apiVersion: core.k8s.com/v1alpha1
    kind: Test
    metadata:
      creationTimestamp: '2022-02-097T19:511:11Z'
      finalizers:
        - cuv.ssf.com
      generation: 1
      name: bar
      namespace: foo
      resourceVersion: '12236'
      uid: 0117657e8
    spec:
      certificateIssuer:
        acme:
          email: myemail
      provider:
        credentials: dst
        type: foo
      domain: vst
      type: bar
    status:
      conditions:
        - lastTransitionTime: '2022-02-09T19:50:12Z'
          message: test
          observedGeneration: 1
          reason: Ready
          status: 'True'
          type: Ready
      lastOperation:
        description: test
        state: Succeeded
        type: Reconcile

https://codebeautify.org/yaml-validator/y22fe4943

I need to remove all the fields under section metadata and the tricky part is to keep only the name and namespace
in addition to removing the status section at all, it should look like following

After

  apiVersion: v1
    items:
      - apiVersion: core.k8s.com/v1alpha1
        kind: Test
        metadata:
          name: bar
          namespace: foo
        spec:
          certificateIssuer:
            acme:
              email: myemail
          provider:
            credentials: dst
            type: foo
          domain: vst
          type: bar

After link
https://codebeautify.org/yaml-validator/y220531ef

Using yq (https://github.com/mikefarah/yq/) version 4.19.1

Body:
Using mikefarah/yq (aka Go yq), you could do something like below. Using del for deleting an entry and with_entries for selecting known fields

yq '.items[] |= (del(.status) | .metadata |= with_entries(select(.key == "name" or .key == "namespace")))' yaml

Starting v4.18.1, the eval flag is the default action, so the e flag can be avoided


问:
Run-time Error 424 Object Required UserForm doesnt exist
I'm attempting to do the things written on this site www.excel-easy.com but when I click the commandbutton (from ActiveX controls) in the worksheet just like what the website instructed, nothing happens. I tried to use a button from form controls, but it says that the error is in this
---> DinnerPlannerUserForm.Show

My Code:

```<code>Sub Button2_Click()
    DinnerPlannerUserForm.Show
End Sub
</code>```

When I used F8, it said the error is here --> Private Sub UserForm_Initialize()

```<code>Private Sub UserForm_Initialize()

    'Empty NameTextBox
    NameTextBox.Value = ""

    'Empty PhoneTextBox
    PhoneTextBox.Value = ""

    'Empty CityListBox
    CityListBox.Clear

    'Fill CityListBox
    With CityListBox
        .AddItem "San Francisco"
        .AddItem "Oakland"
        .AddItem "Richmond"
    End With

    'Empty DinnerComboBox
    DinnerComboBox.Clear

    'Fill DinnerComboBox
    With DinnerComboBox
        .AddItem "Italian"
        .AddItem "Chinese"
        .AddItem "Frites and Meat"
    End With

    'Uncheck DataCheckBoxes
    DateCheckBox1.Value = False
    DateCheckBox2.Value = False
    DateCheckBox3.Value = False

    'Set no car as default
    CarOptionButton2.Value = True

    'Empty MoneyTextBox
    MoneyTextBox.Value = ""

    'Set Focus on NameTextBox
    NameTextBox.SetFocus

End Sub
</code>```

答:
It was "typo" issues for me - I was using the same DinnerPlannerUserForm guide. Worked once I checked all the (Name) boxes were all exactly the same as the names referred to in the code.

The guide is good, except the element "Show the userform" step, and it could perhaps remind us to double check names are exact. I first used this guide about 6 years ago and it helped me build some incredibly useful forms over the years.

Body:
I'm attempting to do the things written on this site www.excel-easy.com but when I click the commandbutton (from ActiveX controls) in the worksheet just like what the website instructed, nothing happens. I tried to use a button from form controls, but it says that the error is in this
---> DinnerPlannerUserForm.Show

My Code:

Sub Button2_Click()
    DinnerPlannerUserForm.Show
End Sub

When I used F8, it said the error is here --> Private Sub UserForm_Initialize()

Private Sub UserForm_Initialize()

    'Empty NameTextBox
    NameTextBox.Value = ""

    'Empty PhoneTextBox
    PhoneTextBox.Value = ""

    'Empty CityListBox
    CityListBox.Clear

    'Fill CityListBox
    With CityListBox
        .AddItem "San Francisco"
        .AddItem "Oakland"
        .AddItem "Richmond"
    End With

    'Empty DinnerComboBox
    DinnerComboBox.Clear

    'Fill DinnerComboBox
    With DinnerComboBox
        .AddItem "Italian"
        .AddItem "Chinese"
        .AddItem "Frites and Meat"
    End With

    'Uncheck DataCheckBoxes
    DateCheckBox1.Value = False
    DateCheckBox2.Value = False
    DateCheckBox3.Value = False

    'Set no car as default
    CarOptionButton2.Value = True

    'Empty MoneyTextBox
    MoneyTextBox.Value = ""

    'Set Focus on NameTextBox
    NameTextBox.SetFocus

End Sub


问:
xcode build to iPhone device it has an invalid code signature
I wanted to build my project in my iPhone, I got this error message

```<code>The operation couldn’t be completed.
Unable to launch com.xxxx.test because it has an invalid code signature,
inadequate entitlements or its profile has not been explicitly trusted by the user.
</code>```

I tried to go to settings> general> VPN and device management but I have nothing inside it I only have the possibility to log in with a work or school account and nothing else. My app does not appear in the VPN and device management section therefore I cannot authorize anything.How can I fix it? Thanks.

Xcode 13.0
iPhone X iOS 15

答:
There are two solutions :

Solution 1: open System Preferences -> Users & Groups -> Add a user account (build with the new user is successfully

Solution 2: Open Keychain Access -> choose System, All Items -> delete certificate Apple Worldwide Developer Relations Certification Authority

Body:
I wanted to build my project in my iPhone, I got this error message

The operation couldn’t be completed.
Unable to launch com.xxxx.test because it has an invalid code signature,
inadequate entitlements or its profile has not been explicitly trusted by the user.

I tried to go to settings> general> VPN and device management but I have nothing inside it I only have the possibility to log in with a work or school account and nothing else. My app does not appear in the VPN and device management section therefore I cannot authorize anything.How can I fix it? Thanks.

Xcode 13.0
iPhone X iOS 15


问:
Design a system which consume data from different type of web services like SOAP and REST
If I want to design a system/application which takes data preferably through web services from different other application which have exposed the API in different type of web service like SOAP based and REST based. What should be the best approach to deal with such situation where I am getting slightly more or less fields apart from the mandatory fields which is required in my application to run my algorithm.</p>

答:
Option 1: SPRING BOOT

You can build a service to consume other services and process them using Spring boot.

Pros: You can choose an archetype when building the app, lots of documentations. Easy to get started using the  https://start.spring.io/

Cons: Very heavy, some configuration can be tricky.

Option 2: SPARK

If you want something more simple and basic I would recommend Spark (Don't confuse with Apache Spark) it is a very light web server framework. https://sparkjava.com/

Pros: Light and simple, easy to get started.

Cons: You need to implement all the external calls and database access if you need it too.

There are a lot of frameworks similar to these. Just by doing a google search "Web server frameworks for java" you can find very interesting articles.

If you want to know about different design patterns. You can find a good explanation of the main ones in the following video: https://www.youtube.com/watch?v=BrT3AO8bVQY


问:
401 instead of 403 with Spring Boot 2
With Spring Boot 1.5.6.RELEASE I was able to send HTTP Status code 401 instead of 403 as described in How let spring security response unauthorized(http 401 code) if requesting uri without authentication, by doing this:

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //...
        http.exceptionHandling()
                .authenticationEntryPoint(new Http401AuthenticationEntryPoint("myHeader"));
        //...
    }
}
</code>```

using the org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint class.

I just upgraded to Spring Boot 2.0.0.RELEASE and found there is not such class any more (at least in that package).

Questions:

Does this class (Http401AuthenticationEntryPoint) exist yet in Spring Boot?

If no, what could be a good alternative for keeping the same behavior in an existing project in order to keep consistency with other implementations which depend on this status code (401) instead of 403?

Please notice this is different from Spring Security anonymous 401 instead of 403 because it's referring specifically to SpringBoot 2 (there are solutions in that post not applicable anymore in SpringBoot version 2 or others are not needed at all)

答:
For reactive (WebFlux) stack you can override the returned status code by adding such @Bean to catch some specific exceptions:</p>
```<code>@Component
class MyErrorAttributes : DefaultErrorAttributes() {
override fun getErrorAttributes(
    request: ServerRequest,
    options: ErrorAttributeOptions
): MutableMap<String, Any> {
    val cause = super.getError(request)

    val errorAttributes = super.getErrorAttributes(request, options)

    when (cause) {
        is TokenExpiredException -> {
            errorAttributes["status"] = HttpStatus.UNAUTHORIZED.value()
            errorAttributes["error"] = HttpStatus.UNAUTHORIZED.reasonPhrase
        }
    }

    return errorAttributes
}
}
</code>```

Title: 401 instead of 403 with Spring Boot 2

Body:
With Spring Boot 1.5.6.RELEASE I was able to send HTTP Status code 401 instead of 403 as described in How let spring security response unauthorized(http 401 code) if requesting uri without authentication, by doing this:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //...
        http.exceptionHandling()
                .authenticationEntryPoint(new Http401AuthenticationEntryPoint("myHeader"));
        //...
    }
}

using the org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint class.

I just upgraded to Spring Boot 2.0.0.RELEASE and found there is not such class any more (at least in that package).

Questions:

Does this class (Http401AuthenticationEntryPoint) exist yet in Spring Boot?

If no, what could be a good alternative for keeping the same behavior in an existing project in order to keep consistency with other implementations which depend on this status code (401) instead of 403?

Please notice this is different from Spring Security anonymous 401 instead of 403 because it's referring specifically to SpringBoot 2 (there are solutions in that post not applicable anymore in SpringBoot version 2 or others are not needed at all)

Body:
For reactive (WebFlux) stack you can override the returned status code by adding such @Bean to catch some specific exceptions:

@Component
class MyErrorAttributes : DefaultErrorAttributes() {
override fun getErrorAttributes(
    request: ServerRequest,
    options: ErrorAttributeOptions
): MutableMap<String, Any> {
    val cause = super.getError(request)

    val errorAttributes = super.getErrorAttributes(request, options)

    when (cause) {
        is TokenExpiredException -> {
            errorAttributes["status"] = HttpStatus.UNAUTHORIZED.value()
            errorAttributes["error"] = HttpStatus.UNAUTHORIZED.reasonPhrase
        }
    }

    return errorAttributes
}
}


问:
Socket.io gives CORS error even if I allowed cors it on server
My node server and client are running on different ports(3001,5347 respectively).
On client I had used,

```<code>var socket = io('http://127.0.0.1:3001');
</code>```

On server I tried all of following one by one

```<code>    1) io.set('origins', '*:*');
    2) io.set('origins', 'http://127.0.0.1:5347');
    3) io.set('origins', '*');
    4) io.set('origins', '127.0.0.1:5347');
</code>```

But I'm getting following error:

XMLHttpRequest cannot load http://127.0.0.1:3001/socket.io/?EIO=3&transport=polling&t=1456799439856-4590. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access.

Note: I'm using express on server and I'm already using cors middleware in following way:

```<code>app.use(cors());
</code>```

Where app and cors are instances of express and cors respectively.

答: For me the symptom was CORS (No Access-Control-Allow-Origin header) and after spending hours trying everything here I realized that the remote webserver wasn't configured to handle https://serverurl/socket.io properly. After adding a nginx location handler for "/socket.io" the errors vanished.</p>

Body:
My node server and client are running on different ports(3001,5347 respectively).
On client I had used,

var socket = io('http://127.0.0.1:3001');

On server I tried all of following one by one

    1) io.set('origins', '*:*');
    2) io.set('origins', 'http://127.0.0.1:5347');
    3) io.set('origins', '*');
    4) io.set('origins', '127.0.0.1:5347');

But I'm getting following error:

XMLHttpRequest cannot load http://127.0.0.1:3001/socket.io/?EIO=3&transport=polling&t=1456799439856-4590. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access.

Note: I'm using express on server and I'm already using cors middleware in following way:

app.use(cors());

Where app and cors are instances of express and cors respectively.


问:
Program segfaulting in release version only
I have an executable that is segfaulting in release but not in debug. I assume it's a wrong call to a printf-family function.

When running i get this:

```<code>*** buffer overflow detected ***: ./mybin terminated
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777f5)[0x7f3a8914d7f5]
/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x5c)[0x7f3a891ef21c]
/lib/x86_64-linux-gnu/libc.so.6(+0x117220)[0x7f3a891ed220]
/lib/x86_64-linux-gnu/libc.so.6(+0x116789)[0x7f3a891ec789]
/lib/x86_64-linux-gnu/libc.so.6(_IO_default_xsputn+0x80)[0x7f3a891516c0]
/lib/x86_64-linux-gnu/libc.so.6(_IO_vfprintf+0xc90)[0x7f3a89123e10]
/lib/x86_64-linux-gnu/libc.so.6(__vsprintf_chk+0x84)[0x7f3a891ec814]
/lib/x86_64-linux-gnu/libc.so.6(__sprintf_chk+0x7d)[0x7f3a891ec76d]
./mybin[0x58b50e]
./mybin(main+0x2f3b)[0x41cfab]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f3a890f6840]
./mybin[0x421969]
======= Memory map: ========
...
7f3a8cd2e000-7f3a8cd34000 rw-p 00000000 00:00 0 Aborted (core dumped)
</code>```

Running it in gdb yields these last lines:

```<code>#8  0x00007ffff3aa7814 in ___vsprintf_chk (s=0x7fffffffaee0 "Some Text - \377\377\177", flags=1, slen=20, format=0x894098 "Some Text - %d",
    args=args@entry=0x7fffffffad68) at vsprintf_chk.c:82
#9  0x00007ffff3aa776d in ___sprintf_chk (s=<optimized out>, flags=<optimized out>, slen=<optimized out>, format=<optimized out>) at sprintf_chk.c:31
#10 0x000000000058b50e in ?? ()
#11 0x000000000041cfab in main ()
</code>```

The "Some Text - %d" comes from:

```<code>char aCharArr[20];
sprintf(aCharArr, "Some text - %d", anInt);
</code>```

While it could do with a memset and snprintf, i've never had issues with these lines before. The int is always one digit.

I was unable to find that 0x58b50e using nm -CD. How else can i more or less pinpoint this (besides going back the commit tree as i'm doing atm and filling the program with printfs)?

答:
Well, as it turns out, the original text (not "Some text") took 19 chars plus the %d, which is "always" one digit. Even so, that's 20 chars in a char aCharArr[20], producing a char array that is not \0-terminated.

Increasing the size of aCharArr (to the next multiple of 8 but that's just me) fixed it and using snprintf instead gave me peace of mind.

```<code>char aCharArr[24];
memset(aCharArr, '\0', sizeof(aCharArr));
sprintf(aCharArr, "Actual str orig len%d", anInt);
</code>```

Compiling in debug with -O2 as is used in release was also helpful, although the available information was enough.

Body:
I have an executable that is segfaulting in release but not in debug. I assume it's a wrong call to a printf-family function.

When running i get this:

*** buffer overflow detected ***: ./mybin terminated
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777f5)[0x7f3a8914d7f5]
/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x5c)[0x7f3a891ef21c]
/lib/x86_64-linux-gnu/libc.so.6(+0x117220)[0x7f3a891ed220]
/lib/x86_64-linux-gnu/libc.so.6(+0x116789)[0x7f3a891ec789]
/lib/x86_64-linux-gnu/libc.so.6(_IO_default_xsputn+0x80)[0x7f3a891516c0]
/lib/x86_64-linux-gnu/libc.so.6(_IO_vfprintf+0xc90)[0x7f3a89123e10]
/lib/x86_64-linux-gnu/libc.so.6(__vsprintf_chk+0x84)[0x7f3a891ec814]
/lib/x86_64-linux-gnu/libc.so.6(__sprintf_chk+0x7d)[0x7f3a891ec76d]
./mybin[0x58b50e]
./mybin(main+0x2f3b)[0x41cfab]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f3a890f6840]
./mybin[0x421969]
======= Memory map: ========
...
7f3a8cd2e000-7f3a8cd34000 rw-p 00000000 00:00 0 Aborted (core dumped)

Running it in gdb yields these last lines:

#8  0x00007ffff3aa7814 in ___vsprintf_chk (s=0x7fffffffaee0 "Some Text - \377\377\177", flags=1, slen=20, format=0x894098 "Some Text - %d",
    args=args@entry=0x7fffffffad68) at vsprintf_chk.c:82
#9  0x00007ffff3aa776d in ___sprintf_chk (s=<optimized out>, flags=<optimized out>, slen=<optimized out>, format=<optimized out>) at sprintf_chk.c:31
#10 0x000000000058b50e in ?? ()
#11 0x000000000041cfab in main ()

The "Some Text - %d" comes from:

char aCharArr[20];
sprintf(aCharArr, "Some text - %d", anInt);

While it could do with a memset and snprintf, i've never had issues with these lines before. The int is always one digit.

I was unable to find that 0x58b50e using nm -CD. How else can i more or less pinpoint this (besides going back the commit tree as i'm doing atm and filling the program with printfs)?

Body:
Well, as it turns out, the original text (not "Some text") took 19 chars plus the %d, which is "always" one digit. Even so, that's 20 chars in a char aCharArr[20], producing a char array that is not \0-terminated.

Increasing the size of aCharArr (to the next multiple of 8 but that's just me) fixed it and using snprintf instead gave me peace of mind.

char aCharArr[24];
memset(aCharArr, '\0', sizeof(aCharArr));
sprintf(aCharArr, "Actual str orig len%d", anInt);

Compiling in debug with -O2 as is used in release was also helpful, although the available information was enough.


问:
How to get the list of all database users
I am going to get the list of all users, including Windows users and 'sa', who have access to a particular database in MS SQL Server.
Basically, I would like the list to look like as what is shown in SQL Server Management Studio (i.e. the list that is shown when you expand [databse] -> Security -> Users) with one important exception: I do not want to see the 'dbo' in the list. Rather, I would like to see the actual user who owns the database. So, for example, if 'sa' is the 'dbo', 'sa' must be included in the list instead of 'dbo'. Another note not to be missed is, the list in the SQL Server Management Studio normally shows Windows users in addition to SQL users, And I would like those users to be included as well.

So far, I have been able to come up with the following query:

```<code>SELECT * FROM sys.database_principals where (type='S' or type = 'U')
</code>```

This query is almost right but the problem is it doesn't satisfy the 'dbo' condition.

How can I change this query or should I use another one?

答:
To run a query returning users of individual databases, try this:

EXEC sp_MSforeachdb 'USE ? <QUERY HERE>'
```
<p>This will run a query (and return a result) for each database. So to get all users (probably with a lot of internal users and roles you are not interested in, try:</p>
<pre class="lang-sql prettyprint-override"><code>EXEC sp_MSforeachdb 'USE ?; SELECT DB_NAME(), * FROM sys.database_principals;'
</code>```

Just apply filters mentioned in other replys to get exactly the subset you are looking for.

Body:
I am going to get the list of all users, including Windows users and 'sa', who have access to a particular database in MS SQL Server.
Basically, I would like the list to look like as what is shown in SQL Server Management Studio (i.e. the list that is shown when you expand [databse] -> Security -> Users) with one important exception: I do not want to see the 'dbo' in the list. Rather, I would like to see the actual user who owns the database. So, for example, if 'sa' is the 'dbo', 'sa' must be included in the list instead of 'dbo'. Another note not to be missed is, the list in the SQL Server Management Studio normally shows Windows users in addition to SQL users, And I would like those users to be included as well.

So far, I have been able to come up with the following query:

SELECT * FROM sys.database_principals where (type='S' or type = 'U')

This query is almost right but the problem is it doesn't satisfy the 'dbo' condition.

How can I change this query or should I use another one?

Body:
To run a query returning users of individual databases, try this:

EXEC sp_MSforeachdb 'USE ? <QUERY HERE>'

This will run a query (and return a result) for each database. So to get all users (probably with a lot of internal users and roles you are not interested in, try:

EXEC sp_MSforeachdb 'USE ?; SELECT DB_NAME(), * FROM sys.database_principals;'

Just apply filters mentioned in other replys to get exactly the subset you are looking for.


问:
Populate Multiple Mongoose Model Fields using Mongoose-paginate plugin
I have a Mongoose Schema (Appointment) with two ref fields (sender and receiver). Both referencing the same Schema (User). I am trying to populate these two fields using mongoose-paginate plugin.

The Appointment Schema snippet.

var paginate = require('mongoose-paginate');

var AppointmentSchema = new Schema({
  dateCreated: {type: Date, default: Date.now},
  sender: {type: ObjectId, ref: 'User'},
  receiver: {type: ObjectId, ref: 'User'},
  message: String,

  .........................

AppointmentSchema.plugin(paginate);

var Appointment = mongoose.model('Appointment', AppointmentSchema);
module.exports = Appointment;```
</div>
</div>
</p>

<p>The User Schema snippet.</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var UserSchema = new Schema({
  username: String,
  name: {
    first: String,
    middle: String,
    last: String
  },

  ..................

var User = mongoose.model('User', UserSchema);

module.exports = User;</code>```

The mongoose paginate query.

Appointment.paginate({}, request.query.page, request.query.limit,
    function(error, pageCount, appointments, itemCount) {
      if (error) {
         return console.log('ERRRRRRRRRR'.red);
      } else {
        console.log(appointments);
        return response.render('message/inbox',
        {
          pageTitle: "Trash",
          messages: appointments,
          pageCount: pageCount,
          itemCount: itemCount,
          currentPage: currentPage
        });
      }
    }, {columns: {}, populate: 'receiver', populate: 'sender', sortBy: {title: -1}});```

This works fine but i want to populate both the sender and receiver fields. Please how do i go about that. I tried passing the fields in JSON but didn't work.

答:
For developers using mongoose-paginate-v2, you can pass an array object to in the pagination options to populate multiple references.</p>
```<code>Collection.paginate(query,{
   page : 1,
   limit : 10,
   populate : [
     {
       path : 'refName1',
       select : {field : 1}
     },
     {
       path : 'refName2',
       select : {field : 1}
     }
   ]
})
</code>```

Body:
I have a Mongoose Schema (Appointment) with two ref fields (sender and receiver). Both referencing the same Schema (User). I am trying to populate these two fields using mongoose-paginate plugin.

The Appointment Schema snippet.

var paginate = require('mongoose-paginate');

var AppointmentSchema = new Schema({
  dateCreated: {type: Date, default: Date.now},
  sender: {type: ObjectId, ref: 'User'},
  receiver: {type: ObjectId, ref: 'User'},
  message: String,

  .........................

AppointmentSchema.plugin(paginate);

var Appointment = mongoose.model('Appointment', AppointmentSchema);
module.exports = Appointment;

The User Schema snippet.

var UserSchema = new Schema({
  username: String,
  name: {
    first: String,
    middle: String,
    last: String
  },

  ..................

var User = mongoose.model('User', UserSchema);

module.exports = User;

The mongoose paginate query.

Appointment.paginate({}, request.query.page, request.query.limit,
    function(error, pageCount, appointments, itemCount) {
      if (error) {
         return console.log('ERRRRRRRRRR'.red);
      } else {
        console.log(appointments);
        return response.render('message/inbox',
        {
          pageTitle: "Trash",
          messages: appointments,
          pageCount: pageCount,
          itemCount: itemCount,
          currentPage: currentPage
        });
      }
    }, {columns: {}, populate: 'receiver', populate: 'sender', sortBy: {title: -1}});

This works fine but i want to populate both the sender and receiver fields. Please how do i go about that. I tried passing the fields in JSON but didn't work.

Body:
For developers using mongoose-paginate-v2, you can pass an array object to in the pagination options to populate multiple references.

Collection.paginate(query,{
   page : 1,
   limit : 10,
   populate : [
     {
       path : 'refName1',
       select : {field : 1}
     },
     {
       path : 'refName2',
       select : {field : 1}
     }
   ]
})


问:
convert string to char c
I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return "5". But I want to five to be a single char '5'.

I thought maybe I could cast to a char in the return. However, I just get rubbish.

I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.

```<code>char *digits_conversion[][2]=
{
    {"ap_zero", "0"},
    {"ap_one", "1"},
    {"ap_two", "2"},
    {"ap_three", "3"},
    {"ap_four", "4"},
    {"ap_five", "5"},
    {"ap_six", "6"},
    {"ap_seven", "7"},
    {"ap_eight", "8"},
    {"ap_nine", "9"},
    {"ap_star", "*"},
    {"ap_hash", "#"},
    {NULL, NULL}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
        if(strcmp(digits_conversion[i][0], digit) == 0)
        {
            return (char) digits_conversion[i][1];
        }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}
</code>```

答:
```<code>digits_conversion[i][1]
</code>```

is a C-style string. Use:

```<code>digits_conversion[ i ][ 1 ][ 0 ] // if you want the character

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
            if(strcmp(digits_conversion[i][0], digit) == 0)
            {
                    return digits_conversion[i][1][0];
            }
    }

    return '\0';
}
</code>```

OwnerDisplayName: robUK

Title: convert string to char c

Body:
I am working on a project where I can to convert a api digit to a char. I have used an array of string pointers to get the conversion. However, I want to return just a single ch, as my api that I am using will only accept a char. So ap_five will return "5". But I want to five to be a single char '5'.

I thought maybe I could cast to a char in the return. However, I just get rubbish.

I am sure there is other ways to solve this, how I am just wondering how can I solve with my present program.

char *digits_conversion[][2]=
{
    {"ap_zero", "0"},
    {"ap_one", "1"},
    {"ap_two", "2"},
    {"ap_three", "3"},
    {"ap_four", "4"},
    {"ap_five", "5"},
    {"ap_six", "6"},
    {"ap_seven", "7"},
    {"ap_eight", "8"},
    {"ap_nine", "9"},
    {"ap_star", "*"},
    {"ap_hash", "#"},
    {NULL, NULL}
};

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
        if(strcmp(digits_conversion[i][0], digit) == 0)
        {
            return (char) digits_conversion[i][1];
        }
    }

    return '\0';
}

int main(void)
{
    char ch;

    ch = convert_to_char("ap_five");

    printf("Converted digit: %c\n", ch);

    return 0;
}

LastEditorDisplayName: robUK

Body:
digits_conversion[i][1]

is a C-style string. Use:

digits_conversion[ i ][ 1 ][ 0 ] // if you want the character

char convert_to_char(const char *digit)
{
    int i = 0;
    for(i = 0; *digits_conversion[i][1]; i++)
    {
            if(strcmp(digits_conversion[i][0], digit) == 0)
            {
                    return digits_conversion[i][1][0];
            }
    }

    return '\0';
}

OwnerDisplayName: dirkgently

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dirkgently


问:
Returning cells as a Matrix VBA
I have a bunch of cells in a sheet that look like this:

Each rows has a gap of 3, and columns a gap of 5.

Id like to extract these values and copy it to some area:

How would I grab each cell and create a matrix like so. Im trying to use a VBA sub() for this, as the initial table size can vary but Im not sure how to do it. Any thoughts appreciated.

答:
The result go to Sheet2</p>
```<code>Sub TransferNotEmptyCells()
  Dim rngArea As Range
  Dim rngCell As Range
  Dim lngRow As Long, lngRowMax As Long, lngCol As Long, lngColMax As Long
  Dim lngRowTarget As Long, lngColTarget As Long

 'Clear Target worksheet
  Sheet2.UsedRange.Clear
  'set row/Col to Start-Position
  lngRowTarget = 1
  lngColTarget = 1

  With Sheet1
  'determine usedrange in Sheet1
   lngRowMax = .Cells(.Rows.Count, 1).End(xlUp).Row
   lngColMax = .Cells(1, .Columns.Count).End(xlToLeft).Column

   'Create two loops to read all filled cells
   For lngRow = 1 To lngRowMax

    For lngCol = 1 To lngColMax

      If .Cells(lngRow, lngCol).Value <> "" Then
        Sheet2.Cells(lngRowTarget, lngColTarget).Value = .Cells(lngRow, lngCol).Value
        lngColTarget = lngColTarget + 1
      End If

    Next lngCol

    lngColTarget = 1

    If .Cells(lngRow, 1).Value <> "" Then
     lngRowTarget = lngRowTarget + 1
    End If
   Next lngRow

  End With

End Sub
</code>```

Title: Returning cells as a Matrix VBA

Body:
The result go to Sheet2

Sub TransferNotEmptyCells()
  Dim rngArea As Range
  Dim rngCell As Range
  Dim lngRow As Long, lngRowMax As Long, lngCol As Long, lngColMax As Long
  Dim lngRowTarget As Long, lngColTarget As Long

 'Clear Target worksheet
  Sheet2.UsedRange.Clear
  'set row/Col to Start-Position
  lngRowTarget = 1
  lngColTarget = 1

  With Sheet1
  'determine usedrange in Sheet1
   lngRowMax = .Cells(.Rows.Count, 1).End(xlUp).Row
   lngColMax = .Cells(1, .Columns.Count).End(xlToLeft).Column

   'Create two loops to read all filled cells
   For lngRow = 1 To lngRowMax

    For lngCol = 1 To lngColMax

      If .Cells(lngRow, lngCol).Value <> "" Then
        Sheet2.Cells(lngRowTarget, lngColTarget).Value = .Cells(lngRow, lngCol).Value
        lngColTarget = lngColTarget + 1
      End If

    Next lngCol

    lngColTarget = 1

    If .Cells(lngRow, 1).Value <> "" Then
     lngRowTarget = lngRowTarget + 1
    End If
   Next lngRow

  End With

End Sub


问:
How do I get ruby to print a full backtrace that includes arguments passed to functions?
Sometimes backtrace is enough to diagnose problem. But sometimes reason of crash is not obvious without knowledge what was passed to function.

Getting information what was passed to function that caused crash would be quite useful, especially in cases where reproducing is not obvious because it was caused by for example exception in network connection, weird user input or because program is depends on randomisation or processes data from external sensor.

Lets say that there is following program

```<code>def handle_changed_input(changed_input)
    raise 'ops' if changed_input =~ /magic/
end

def do_something_with_user_input(input)
    input = "#{input.strip}c"
    handle_changed_input(input)
end

input = gets
do_something_with_user_input(input)
</code>```

where user typed "magic" as input. Normally one has

```<code>test.rb:2:in `handle_changed_input': ops (RuntimeError)
    from test.rb:7:in `do_something_with_user_input'
    from test.rb:11:in `<main>'
</code>```

as output.  What one may do to show also what was passed to function? Something like

```<code>test.rb:2:in `handle_changed_input("magic")': ops (RuntimeError)
    from test.rb:7:in `do_something_with_user_input("magi\n")'
    from test.rb:11:in `<main>'
</code>```

It would be useful in many situations (and not truly useful where parameters are not representable as strings of reasonable legth, there is a good reason why it is not enabled by default).

How one may add this functionality? It is necessary that program works as usually during normal operation and preferably there is no additional output before crash.

I tried for example

```<code>def do_something_with_user_input(input)
    method(__method__).parameters.map do |_, name|
        puts "#{name}=#{binding.local_variable_get(name)}"
    end
    raise 'ops' if input =~ /magic/
end

input = gets
</code>```

found in Is there a way to access method arguments in Ruby? but it would print on every single entrance to function what both would flood output and make program significantly slower.

答:
```<code>MAX_STACK_SIZE = 200
tracer = proc do |event|
  if event == 'call' && caller_locations.length > MAX_STACK_SIZE
    fail "Probable Stack Overflow"
  end
end
set_trace_func(tracer)
</code>```

Body:
Sometimes backtrace is enough to diagnose problem. But sometimes reason of crash is not obvious without knowledge what was passed to function.

Getting information what was passed to function that caused crash would be quite useful, especially in cases where reproducing is not obvious because it was caused by for example exception in network connection, weird user input or because program is depends on randomisation or processes data from external sensor.

Lets say that there is following program

def handle_changed_input(changed_input)
    raise 'ops' if changed_input =~ /magic/
end

def do_something_with_user_input(input)
    input = "#{input.strip}c"
    handle_changed_input(input)
end

input = gets
do_something_with_user_input(input)

where user typed "magic" as input. Normally one has

test.rb:2:in `handle_changed_input': ops (RuntimeError)
    from test.rb:7:in `do_something_with_user_input'
    from test.rb:11:in `'

as output.  What one may do to show also what was passed to function? Something like

test.rb:2:in `handle_changed_input("magic")': ops (RuntimeError)
    from test.rb:7:in `do_something_with_user_input("magi\n")'
    from test.rb:11:in `'

It would be useful in many situations (and not truly useful where parameters are not representable as strings of reasonable legth, there is a good reason why it is not enabled by default).

How one may add this functionality? It is necessary that program works as usually during normal operation and preferably there is no additional output before crash.

I tried for example

def do_something_with_user_input(input)
    method(__method__).parameters.map do |_, name|
        puts "#{name}=#{binding.local_variable_get(name)}"
    end
    raise 'ops' if input =~ /magic/
end

input = gets

found in Is there a way to access method arguments in Ruby? but it would print on every single entrance to function what both would flood output and make program significantly slower.


问:
Update SVG progress circle by clicking checkboxes
I have 5 checkboxes representing a To-Do list, for every checkbox I click, the circle's diameter should complete 1/5, 2/5 , 3/5, 4/5, 5/5 until it completes the 5 checkboxes, the order of how the checkboxes are created shouldn't matter. If I clicked "first ToDo" and "third ToDo" without selecting "second ToDo" the circle should still show 2/5 of itself.

So far I've been able to make the circle interact with the input of the checkboxes, but I'm struggling to make the visual progress happen, when I click one of the ToDos the progress circle it's marked but not in the right order and portions, also the idea is that the visual progress should move forward to the right until completing the circle.

Looking for information online, I see people uses <circle path>but it is really confusing for me because some configurations are made through CSS while other people do it in the JS, according to me it is best that I use JS to show the progress, because it should behave in base of the checkboxes.

function update() {

  var myBar = document.getElementById("myCircle");
  //Reference the Form.
  var toDo = document.getElementById("toDo");

  //Reference all the CheckBoxes in Table.
  boxes = toDo.querySelectorAll("input[type='checkbox']:checked");
  checked = boxes.length

  myBar.style.strokeDasharray = ((checked) * 100) + "%";
  if (checked === 0) {
    alert("Please select CheckBox(s).");
  }
  return true;
}

checks = document.querySelectorAll("input[type='checkbox']");
checks.forEach(function(box) {
  box.addEventListener("change", function() {
    update()
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myCircle {
  width: 0;
  height: 30px;
  stroke: #A3BBAD;
  stroke-width: 3px;
}

#myProgress {
  margin: auto;
  width: 50%;
  stroke: #357266;
  stroke-width: 3px;
}</code>```

<svg height="100" width="100">
  <circle id="myProgress" cx="50" cy="50" r="40" fill="transparent"/>
  <circle id="myCircle" cx="50" cy="50" r="40" fill="transparent"/>
</svg>

<form id="toDo">
  <input id="FirstToDo" type="checkbox" value="1" />First
  <input id="SecondToDo" type="checkbox" value="2" />Second
  <input id="ThirdToDo" type="checkbox" value="3" />Third
  <input id="FourthToDo" type="checkbox" value="4" />Fourth
  <input id="FifthToDo" type="checkbox" value="5" />Fifth
</form>
```

答:
First, you need to understand that percent unit isn't a fraction of the circle's path. In this context :

If a percentage is used, the value represents a percentage of the current viewport.

[ source w3.org emphasis mine ]

To set a total length to the circle's path, you can use pathLength="100" (see MDN for more information on the pathLength).

Then, you can adjust your JS to set the strokeDasharray value on a base 100 for the circle's path lentgh.

Here is a possible approach :

function update() {

  var myBar = document.getElementById("myCircle");
  //Reference the Form.
  var toDo = document.getElementById("toDo");

  //Reference all the CheckBoxes in Table.
  boxes = toDo.querySelectorAll("input[type='checkbox']:checked");
  checked = boxes.length

  myBar.style.strokeDasharray = (100 - (checked) * 20) + ', 100';
  if (checked === 0) {
    alert("Please select CheckBox(s).");
  }
  return true;
}

checks = document.querySelectorAll("input[type='checkbox']");
checks.forEach(function(box) {
  box.addEventListener("change", function() {
    update()
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
  transform: rotate(-90deg);
}
#myCircle {
  width: 0;
  height: 30px;
  stroke: #A3BBAD;
  stroke-width: 3px;
}

#myProgress {
  margin: auto;
  width: 50%;
  stroke: #357266;
  stroke-width: 3px;
}</code>```

<svg height="100" width="100">
  <circle id="myProgress" cx="50" cy="50" r="40" fill="transparent"/>
  <circle id="myCircle" cx="50" cy="50" r="40" fill="transparent" pathLength="100"/>
</svg>

<form id="toDo">
  <input id="FirstToDo" type="checkbox" value="1" />First
  <input id="SecondToDo" type="checkbox" value="2" />Second
  <input id="ThirdToDo" type="checkbox" value="3" />Third
  <input id="FourthToDo" type="checkbox" value="4" />Fourth
  <input id="FifthToDo" type="checkbox" value="5" />Fifth
</form>```

On a side note, as the circle stroke starts on the right of the cricle by default, I added a rotation (-90deg) to the svg to make the progress bar start at the top of the circle.

Body:
I have 5 checkboxes representing a To-Do list, for every checkbox I click, the circle's diameter should complete 1/5, 2/5 , 3/5, 4/5, 5/5 until it completes the 5 checkboxes, the order of how the checkboxes are created shouldn't matter. If I clicked "first ToDo" and "third ToDo" without selecting "second ToDo" the circle should still show 2/5 of itself.

So far I've been able to make the circle interact with the input of the checkboxes, but I'm struggling to make the visual progress happen, when I click one of the ToDos the progress circle it's marked but not in the right order and portions, also the idea is that the visual progress should move forward to the right until completing the circle.

Looking for information online, I see people uses <circle path>but it is really confusing for me because some configurations are made through CSS while other people do it in the JS, according to me it is best that I use JS to show the progress, because it should behave in base of the checkboxes.

function update() {

  var myBar = document.getElementById("myCircle");
  //Reference the Form.
  var toDo = document.getElementById("toDo");

  //Reference all the CheckBoxes in Table.
  boxes = toDo.querySelectorAll("input[type='checkbox']:checked");
  checked = boxes.length

  myBar.style.strokeDasharray = ((checked) * 100) + "%";
  if (checked === 0) {
    alert("Please select CheckBox(s).");
  }
  return true;
}

checks = document.querySelectorAll("input[type='checkbox']");
checks.forEach(function(box) {
  box.addEventListener("change", function() {
    update()
  });
});

#myCircle {
  width: 0;
  height: 30px;
  stroke: #A3BBAD;
  stroke-width: 3px;
}

#myProgress {
  margin: auto;
  width: 50%;
  stroke: #357266;
  stroke-width: 3px;
}

<svg height="100" width="100">
  <circle id="myProgress" cx="50" cy="50" r="40" fill="transparent"/>
  <circle id="myCircle" cx="50" cy="50" r="40" fill="transparent"/>
</svg>

<form id="toDo">
  <input id="FirstToDo" type="checkbox" value="1" />First
  <input id="SecondToDo" type="checkbox" value="2" />Second
  <input id="ThirdToDo" type="checkbox" value="3" />Third
  <input id="FourthToDo" type="checkbox" value="4" />Fourth
  <input id="FifthToDo" type="checkbox" value="5" />Fifth
</form>

Body:
First, you need to understand that percent unit isn't a fraction of the circle's path. In this context :

If a percentage is used, the value represents a percentage of the current viewport.

[ source w3.org emphasis mine ]

To set a total length to the circle's path, you can use pathLength="100" (see MDN for more information on the pathLength).

Then, you can adjust your JS to set the strokeDasharray value on a base 100 for the circle's path lentgh.

Here is a possible approach :

function update() {

  var myBar = document.getElementById("myCircle");
  //Reference the Form.
  var toDo = document.getElementById("toDo");

  //Reference all the CheckBoxes in Table.
  boxes = toDo.querySelectorAll("input[type='checkbox']:checked");
  checked = boxes.length

  myBar.style.strokeDasharray = (100 - (checked) * 20) + ', 100';
  if (checked === 0) {
    alert("Please select CheckBox(s).");
  }
  return true;
}

checks = document.querySelectorAll("input[type='checkbox']");
checks.forEach(function(box) {
  box.addEventListener("change", function() {
    update()
  });
});

svg {
  transform: rotate(-90deg);
}
#myCircle {
  width: 0;
  height: 30px;
  stroke: #A3BBAD;
  stroke-width: 3px;
}

#myProgress {
  margin: auto;
  width: 50%;
  stroke: #357266;
  stroke-width: 3px;
}

<svg height="100" width="100">
  <circle id="myProgress" cx="50" cy="50" r="40" fill="transparent"/>
  <circle id="myCircle" cx="50" cy="50" r="40" fill="transparent" pathLength="100"/>
</svg>
<br>

<form id="toDo">
  <input id="FirstToDo" type="checkbox" value="1" /><label for="FirstToDo">First</label>
  <input id="SecondToDo" type="checkbox" value="2" /><label for="SecondToDo">Second</label>
  <input id="ThirdToDo" type="checkbox" value="3" /><label for="ThirdToDo">Third</label>
  <input id="FourthToDo" type="checkbox" value="4" /><label for="FourthToDo">Fourth</label>
  <input id="FifthToDo" type="checkbox" value="5" /><label for="FifthToDo">Fifth</label>
</form>

On a side note, as the circle stroke starts on the right of the cricle by default, I added a rotation (-90deg) to the svg to make the progress bar start at the top of the circle.


问:
Syntax error: 'await' outside async function, but it works as a global variable?
I am pulling data using the Binance API, and want to store it (bitcoin price and time) in two separate arrays, then plot the data onto Matplotlib.

I have the following code:

However, when I run it, I get a syntax error:

From suggested answers below, I tried amending the code to include the async function as followings:

But when I run this, I now get:

```<code>RuntimeError: asyncio.run() cannot be called from a running event loop
</code>```

答:
await can only be called in an async function, so your animate function must be async :

```<code>async def animate(i):
await socket.__aenter__()
msg = await socket.recv()
x_axis.append(msg['T'])
y_axis.append(msg['p'])

plt.cla()
plt.plot(x_axis,y_axis)
</code>```

Body:
I am pulling data using the Binance API, and want to store it (bitcoin price and time) in two separate arrays, then plot the data onto Matplotlib.

I have the following code:

However, when I run it, I get a syntax error:

From suggested answers below, I tried amending the code to include the async function as followings:

But when I run this, I now get:

RuntimeError: asyncio.run() cannot be called from a running event loop

Body:
await can only be called in an async function, so your animate function must be async :

async def animate(i):
await socket.__aenter__()
msg = await socket.recv()
x_axis.append(msg['T'])
y_axis.append(msg['p'])

plt.cla()
plt.plot(x_axis,y_axis)


问:
Subtraction of numbers double and long
In my JAVA program there is code like this:

```<code>int f_part = (int) ((f_num - num) * 100);
</code>```

f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it's value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don't know why this happening. Please can someone explain why this happens and way to correct it.

答:
Floating point arithmetic is not as simple as it may seem and there can be precision issues.
See Why can't decimal numbers be represented exactly in binary?, What Every Computer Scientist Should Know About Floating-Point Arithmetic for details.

If you need absolutely sure precision, you might want to use BigDecimal.

Title: Subtraction of numbers double and long

Body:
In my JAVA program there is code like this:

int f_part = (int) ((f_num - num) * 100);

f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it's value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don't know why this happening. Please can someone explain why this happens and way to correct it.


问:
Tiptap editor, how to paste multiple empty lines?
Using the basic version fo Tiptap editor:

```<code><template>
  <div v-if="editor">
    <editor-content :editor="editor" />
  </div>
</template>

<script>
import { Editor, EditorContent } from '@tiptap/vue-3'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'

export default {
  components: {
    EditorContent,
  },

  data() {
    return {
      editor: null,
    }
  },

  mounted() {
    this.editor = new Editor({
      extensions: [
        Document,
        Paragraph,
        Text,
      ],
      content: `
        <p>The Paragraph extension is not required, but it’s very likely you want to use it. It’s needed to write paragraphs of text. </p>
      `,
    })
  },

  beforeUnmount() {
    this.editor.destroy()
  },
}
</script>
</code>```

(which is available to test at https://tiptap.dev/api/nodes/paragraph)

I noticed that when pasting a text with multiple lines, such as :

```<code>Hello

This is a test with two break lines at the above and three after this:

Thanks!
</code>```

The resulting is :

```<code><p>Hello</p>
<p>This is a test with two break lines at the above and three after this:</p>
<p>Thanks!</p>
</code>```

In this case, all the "multiple" break lines has been removed!

Is there a way to keep them, which means that once the paste is executed, the content should be:

```<code><p>Hello</p>
<p></p>
<p></p>
<p>This is a test with two break lines at the above and three after this:</p>
<p></p>
<p></p>
<p></p>
<p>Thanks!</p>
</code>```

(I'm ok with having

 instead of

 by enabling the Hardbreak extension too, but in either case, it doesn't work).

答:
I found the solution by opening a ticket on Tiptap.

It turns out that it is the fault of Prosemirror for not handling the multiple break lines, but someone on a related ticket from Tiptap made a suggestion that works great:

```<code>import {Slice, Fragment, Node} from 'prosemirror-model'

function clipboardTextParser(text, context, plain)
{
    const blocks = text.replace().split(/(?:\r\n?|\n)/);
    const nodes = [];

    blocks.forEach(line => {
        let nodeJson = {type: "paragraph"};
        if (line.length > 0) {
            nodeJson.content = [{type: "text", text: line}]
        }
        let node = Node.fromJSON(context.doc.type.schema, nodeJson);
        nodes.push(node);
    });

    const fragment = Fragment.fromArray(nodes);
    return Slice.maxOpen(fragment);
}

new Editor({
    editorProps: {
        clipboardTextParser: clipboardTextParser,
    },
})
</code>```

Body:
Using the basic version fo Tiptap editor:

<template>

    <editor-content :editor="editor" />

</template>

(which is available to test at https://tiptap.dev/api/nodes/paragraph)

I noticed that when pasting a text with multiple lines, such as :

Hello

This is a test with two break lines at the above and three after this:

Thanks!

The resulting is :

Hello

This is a test with two break lines at the above and three after this:

Thanks!

In this case, all the "multiple" break lines has been removed!

Is there a way to keep them, which means that once the paste is executed, the content should be:

Hello

This is a test with two break lines at the above and three after this:

Thanks!

(I'm ok with having

 instead of

 by enabling the Hardbreak extension too, but in either case, it doesn't work).

Body:
I found the solution by opening a ticket on Tiptap.

It turns out that it is the fault of Prosemirror for not handling the multiple break lines, but someone on a related ticket from Tiptap made a suggestion that works great:

import {Slice, Fragment, Node} from 'prosemirror-model'

function clipboardTextParser(text, context, plain)
{
    const blocks = text.replace().split(/(?:\r\n?|\n)/);
    const nodes = [];

    blocks.forEach(line => {
        let nodeJson = {type: "paragraph"};
        if (line.length > 0) {
            nodeJson.content = [{type: "text", text: line}]
        }
        let node = Node.fromJSON(context.doc.type.schema, nodeJson);
        nodes.push(node);
    });

    const fragment = Fragment.fromArray(nodes);
    return Slice.maxOpen(fragment);
}

new Editor({
    editorProps: {
        clipboardTextParser: clipboardTextParser,
    },
})


问:
pivot_table(), multiple aggfuncs to the *same* column - possible?
EDIT - please don't lock this question, the similar question links do not provide answers as my question is for applying multiple aggfuncs to the same value column.

I have a standard pivot_table() function being applied to a dataframe in the following way:

```<code>pivot = df.pivot_table(index=['Year', 'Month'], values=['Claims', 'Policy Holdings'], aggfunc={'Claims': 'min', 'Policy Holdings': 'max'})
</code>```

I'm interested to know, say that I want to use the same column in my values twice, with a different aggfunc (i.e. min and max) - is this possible?

The following code doesn't work:

```<code>pivot = df.pivot_table(index=['Year', 'Month'], values=['Claims', 'Claims'], aggfunc={'Claims': 'min', 'Claims': 'max'})
</code>```

Of course I could make a copy of the column beforehand with a different name but I imagine there's a more elegant solution available?

答:
IIUC use:</p>
```<code>pivot = df.pivot_table(index=['Year', 'Month'], values=['Claims'], aggfunc={'Claims': ['min','max']})
</code>```

Body:
EDIT - please don't lock this question, the similar question links do not provide answers as my question is for applying multiple aggfuncs to the same value column.

I have a standard pivot_table() function being applied to a dataframe in the following way:

pivot = df.pivot_table(index=['Year', 'Month'], values=['Claims', 'Policy Holdings'], aggfunc={'Claims': 'min', 'Policy Holdings': 'max'})

I'm interested to know, say that I want to use the same column in my values twice, with a different aggfunc (i.e. min and max) - is this possible?

The following code doesn't work:

pivot = df.pivot_table(index=['Year', 'Month'], values=['Claims', 'Claims'], aggfunc={'Claims': 'min', 'Claims': 'max'})

Of course I could make a copy of the column beforehand with a different name but I imagine there's a more elegant solution available?

Body:
IIUC use:

pivot = df.pivot_table(index=['Year', 'Month'], values=['Claims'], aggfunc={'Claims': ['min','max']})


问:
Angular Object Array Sorting
Trying to sort the array of object, the property of the object contains alphanumeric values,
Tried methods which didn't worked

test.sort((a,b)=> a.Code.localeCompare(b.Code));
test.sort((a,b)=> +a.Code- +b.Code);

let test = [{Code: '16', Color: "Red"},
      {Code: '54', Color: "Yellow"},
      {Code: '24', Color: "Yellow"},
      {Code: '1600', Color: "Blue"},
      {Code: '16a', Color: "Green"},
      {Code: '22', Color: "Yellow"},
      {Code: '23', Color: "Yellow"}];

 test.sort((a,b) =>  a.Code.localeCompare(b.Code));
 console.log(test);```
</div>
</div>
</p>
<p>getting output as</p>
```[{"Code": "16", "Color": "Red" },
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"},
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"}]
```
<p>How I can get the Expected output as</p>
```[{"Code": "16", "Color": "Red" },
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"},
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"}]
```

答:
Try something as follows;

test.sort(a,b) =>  a.Code.localeCompare(b.Code, 'en', { numeric: true });

There is other possible solution if the above does not work as you expect.

Ref: Sort mixed alpha/numeric array

Title: Angular Object Array Sorting

Body:
Trying to sort the array of object, the property of the object contains alphanumeric values,
Tried methods which didn't worked

test.sort((a,b)=> a.Code.localeCompare(b.Code));
test.sort((a,b)=> +a.Code- +b.Code);

let test = [{Code: '16', Color: "Red"},
      {Code: '54', Color: "Yellow"},
      {Code: '24', Color: "Yellow"},
      {Code: '1600', Color: "Blue"},
      {Code: '16a', Color: "Green"},
      {Code: '22', Color: "Yellow"},
      {Code: '23', Color: "Yellow"}];

 test.sort((a,b) =>  a.Code.localeCompare(b.Code));
 console.log(test);

getting output as

[{"Code": "16", "Color": "Red" },
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"},
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"}]

How I can get the Expected output as

[{"Code": "16", "Color": "Red" },
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"},
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"}]


问:
First three items of of NSArray into an NSString?
What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

```<code>String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored
</code>```

答:
```<code>NSUInteger count = [bandArray count];
if (count > 3){
    count = 3;
}
NSString * resultString = [[bandArray subarrayWithRange:NSMakeRange(0,count)]  componentsJoinedByString:@", "];
</code>```

Body:
What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored


问:
Is there a way of conditionally selecting which WHERE-clause to use in an SQL query?
Knowing I have 2 variables declared called @Variable and @Name, I need something like this:

```<code>SELECT * from (myDbTable)
CASE WHEN (@Variable IS NOT NULL AND @Variable <> '')
THEN WHERE myDbTable.variable LIKE @Variable
ELSE WHERE myDbTable.name LIKE @Name
</code>```

Basically, if the user enters a "variable" value, it should do a WHERE-clause on that variable, if not, it should do a WHERE-clause on Name.

Can I do this in SQL?

答:
This would do the work(Not the most efficient though):

```<code>SELECT * from (myDbTable)
WHERE ((@Variable IS NOT NULL AND @Variable <> '') AND myDbTable.variable LIKE @Variable)
OR ((@Variable IS NULL OR @Variable = '') AND myDbTable.name LIKE @Name)
</code>```

You can also use dynamic sql like suggested in the comments.

Body:
Knowing I have 2 variables declared called @Variable and @Name, I need something like this:

SELECT * from (myDbTable)
CASE WHEN (@Variable IS NOT NULL AND @Variable <> '')
THEN WHERE myDbTable.variable LIKE @Variable
ELSE WHERE myDbTable.name LIKE @Name

Basically, if the user enters a "variable" value, it should do a WHERE-clause on that variable, if not, it should do a WHERE-clause on Name.

Can I do this in SQL?

Body:
This would do the work(Not the most efficient though):

SELECT * from (myDbTable)
WHERE ((@Variable IS NOT NULL AND @Variable <> '') AND myDbTable.variable LIKE @Variable)
OR ((@Variable IS NULL OR @Variable = '') AND myDbTable.name LIKE @Name)

You can also use dynamic sql like suggested in the comments.


问:
I Want To Fetch Only data With A Specific Field Value On Firebase
Here I have a collection of cars and bikes and don't want to fetch everything if users select they are looking for only Cars, there are 2 types of categories Vehicles and Motorcycles and in firestore I query them like:

```<code>[{category: vehicles, modelYear: 2008 }, {category: motorcycles, modelYear: 2012}]

</code>```

but is there a way to query only the one the user has selected, Like:

```<code>    const [results, setResults] = useState([])

     useEffect(() => {
           if(vehicles === true){
            db.collection("automotive")
            .orderBy("category == Vehicles")
            .limit(5)
            .get()
            .then((collections) =>{
              const auto = collections.docs.map((res) => res.data())
              setResult(auto)
             })
           }
      }, [])
</code>```

答:
Firebase Firestore have provided proper method to put condition on query and limit works only when you use orderby on field :</p>
```<code>db.collection("automotive")
    .where("category == Vehicles")
    .orderBy("modelYear")
    .limit(5)
    .get()
    .then((collections) =>{
        const auto = collections.docs.map((res) => res.data())
        setResult(auto)
     });
</code>```

Body:
Here I have a collection of cars and bikes and don't want to fetch everything if users select they are looking for only Cars, there are 2 types of categories Vehicles and Motorcycles and in firestore I query them like:

[{category: vehicles, modelYear: 2008 }, {category: motorcycles, modelYear: 2012}]

but is there a way to query only the one the user has selected, Like:

    const [results, setResults] = useState([])

     useEffect(() => {
           if(vehicles === true){
            db.collection("automotive")
            .orderBy("category == Vehicles")
            .limit(5)
            .get()
            .then((collections) =>{
              const auto = collections.docs.map((res) => res.data())
              setResult(auto)
             })
           }
      }, [])

Body:
Firebase Firestore have provided proper method to put condition on query and limit works only when you use orderby on field :

db.collection("automotive")
    .where("category == Vehicles")
    .orderBy("modelYear")
    .limit(5)
    .get()
    .then((collections) =>{
        const auto = collections.docs.map((res) => res.data())
        setResult(auto)
     });


问:
intervation image wont store image in public path after i uploaded my laravel project on host
i have a project that it has some posts on it
i have made admin panel to create new posts
since i uploaded my project on cpanel host i can create a post but image wont shown in my post but before that on my localhost i can craete a post and store image in my path
i checked my public path in my host and saw that there isn,t any new image related to my post that i have created with my admin panel on my host just my image name has saved in my database

this is my blog blade file

```<code><section class="w-80 mx-auto my-5">
    <div class="container">
        <div class="row">
            @foreach($posts as $post)
                <div class="col-md-4 translate-box relative mb-4">
                    <div class="blog-box-height">
                        <a href="{{route('blog.single',['title'=>$post->title])}}"> <img src="{{asset('image/'.$post->header_image)}}" alt="{{$post->title}}" class="img-fluid"></a>
                        <div class="py-3 px-4">
                            <a class="text-xmedium fw-bold text-decoration-none text-black" href="{{route('blog.single',['title'=>$post->title])}}">
                                {{str_replace('_',' ',$post->title)}}
                            </a>
                            <p class="text-muted-1 mt-2 text-small">
                               {!! strip_tags(mb_substr($post->content,0,270,'utf-8')) !!} ...
                            </p>
                            <div class="box-time absolute">
                                <p class="text-muted-1"><i class="far fa-clock"></i> {{$post->time}} دقیقه</p>
                            </div>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>
    </div>
</section>
</code>```

this is my postcontroller codes

```<code>public function storeImage(Request $request)
{
    $image_name = null;
    if ($request->file('image')) {
        $image = $request->file('image')->getClientOriginalName();
        $image_name = time() . $image;
        $folder = public_path('/image');
        $path = $folder . '/' . $image_name;

        if (is_dir($folder)) {
            $img = Image::make($request->file('image'))->resize(500, 438);
            $img->save($path);
        } else {
            File::makeDirectory($folder, 0755, true);
            $img = Image::make($request->file('image'))->resize(500, 438);
            $img->save($path);
        }
    }

    return $image_name;
}
</code>```

this code works great in my localhost server but when i uploaded it on host i think image intervation wont work

答:
You have to set the symlink to connect the stroge folder with the public folder.
Try running php artisan storage:link on the webserver.

Also in some hostings this command is banned. In that case you have to create the symlink manually using forexample midnight commander.

Body:
i have a project that it has some posts on it
i have made admin panel to create new posts
since i uploaded my project on cpanel host i can create a post but image wont shown in my post but before that on my localhost i can craete a post and store image in my path
i checked my public path in my host and saw that there isn,t any new image related to my post that i have created with my admin panel on my host just my image name has saved in my database

this is my blog blade file

            @foreach($posts as $post)

                        $post->title])}}"> header_image)}}" alt="{{$post->title}}" class="img-fluid">

                            $post->title])}}">
                                {{str_replace('_',' ',$post->title)}}

                               {!! strip_tags(mb_substr($post->content,0,270,'utf-8')) !!} ...

 {{$post->time}} دقیقه

            @endforeach

this is my postcontroller codes

public function storeImage(Request $request)
{
    $image_name = null;
    if ($request->file('image')) {
        $image = $request->file('image')->getClientOriginalName();
        $image_name = time() . $image;
        $folder = public_path('/image');
        $path = $folder . '/' . $image_name;

        if (is_dir($folder)) {
            $img = Image::make($request->file('image'))->resize(500, 438);
            $img->save($path);
        } else {
            File::makeDirectory($folder, 0755, true);
            $img = Image::make($request->file('image'))->resize(500, 438);
            $img->save($path);
        }
    }

    return $image_name;
}

this code works great in my localhost server but when i uploaded it on host i think image intervation wont work