问:
Full heigth containers filling remaining heigth
I am fighting on learning bootstrap 4 on redesigning a simple app.

The App has got a fixed height header, a fixed height footer and needs a flexible centered container using the remaining height.

It drives me crazy, cause I tried so many examples. None where working.

See this codepen of my last try.

document, html, body {
  height: 100%;
  width: 100%;
  position: absolute;
}

#topContainer{
  height: 95px;
}

#centerContainer{
  position: inherit;
  height: 100%;
}

#bottomContainer{
  height: 45px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="de">
<head>
  <!-- Required meta tags -->

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>Test Construction</title>

</head>
<body>

<div class="container-flex bg-success h-100">

    <div id="topContainer" class="row flex-row bg-primary">
        <div class="col-4 bg-danger">1</div>
        <div class="col-4 bg-info">2</div>
        <div class="col-4 bg-dark">3</div>
    </div>

    <div id="centerContainer" class="row flex-row bg-secondary">
        <div class="col-4 bg-dark">1</div>
        <div class="col-4 bg-danger">2</div>
        <div class="col-4 bg-info">3</div>
    </div>

    <div id="bottomContainer" class="row flex-row bg-warning">
        <div class="col-4 bg-info">1</div>
        <div class="col-4 bg-dark">2</div>
        <div class="col-4 bg-danger">3</div>
    </div>

</div>

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>

</body>
</html></code>```

Any hint for me how I can handle this?

After a while I found an example which might be working. I tried it on my windows machine and cool it works
https://codepen.io/anon/pen/aryXba

But the same layout in my symfony/bootstrap project on a linux machine in chrome does not work anymore

答:
here is a pretty simple example using bootstrap.

flex-grow applied to your center element will take up the remaining space dependent on the height of the container and the header and footer. Also note that for flex-grow to work your parent element needs to use flex box.

view example here
Code Pen

Body:
I am fighting on learning bootstrap 4 on redesigning a simple app.

The App has got a fixed height header, a fixed height footer and needs a flexible centered container using the remaining height.

It drives me crazy, cause I tried so many examples. None where working.

See this codepen of my last try.

document, html, body {
  height: 100%;
  width: 100%;
  position: absolute;
}

#topContainer{
  height: 95px;
}

#centerContainer{
  position: inherit;
  height: 100%;
}

#bottomContainer{
  height: 45px;
}

<!doctype html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>Test Construction</title>

1

2

3

1

2

3

1

2

3

Any hint for me how I can handle this?

After a while I found an example which might be working. I tried it on my windows machine and cool it works
https://codepen.io/anon/pen/aryXba

But the same layout in my symfony/bootstrap project on a linux machine in chrome does not work anymore


来源: stackexchange

问:
Creating a Hive table with an irregular date/time format column
I have to create a Hive table from a csv and two of the columns have a date/time field that are formatted like so: 11/28/2018 8:35:23 PM or 11/30/2018 5:02:17 AM, etc. For example:

```<code>responseid        process_start             process_end                status

26                11/28/2018 8:35:23 PM     11/30/2018 5:02:17 AM      complete
</code>```

I know that I can create these fields as a string first and then do something like this:

```<code>insert into table newtable
select process_start, from_unixtime(unix_timestamp(process_start, 'dd-MM-yyyy HH:mm:ss')) from oldtable;
</code>```

But I'm not quite sure how to deal with the AM and PM. I'm not quite sure I have the insert into table syntax quite right either. Any help would be appreciated.

答:
Use SimpleDateFormat class docs as a format reference. Correct format is

'MM/dd/yyyy h:mm:ss a'

```<code>select from_unixtime(unix_timestamp('11/28/2018 8:35:23 PM', 'MM/dd/yyyy h:mm:ss a'))
</code>```

Returns:

```<code>2018-11-28 20:35:23
</code>```

Insert into table like this:

```<code>INSERT INTO TABLE newtable
select responseid,
       from_unixtime(unix_timestamp(process_start, 'MM/dd/yyyy h:mm:ss a')) process_start,
       from_unixtime(unix_timestamp(process_end, 'MM/dd/yyyy h:mm:ss a')) process_end,
       status
  from oldtable;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have to create a Hive table from a csv and two of the columns have a date/time field that are formatted like so: 11/28/2018 8:35:23 PM or 11/30/2018 5:02:17 AM, etc. For example:

responseid        process_start             process_end                status

26                11/28/2018 8:35:23 PM     11/30/2018 5:02:17 AM      complete

I know that I can create these fields as a string first and then do something like this:

insert into table newtable
select process_start, from_unixtime(unix_timestamp(process_start, 'dd-MM-yyyy HH:mm:ss')) from oldtable;

But I'm not quite sure how to deal with the AM and PM. I'm not quite sure I have the insert into table syntax quite right either. Any help would be appreciated.

Body:
Use SimpleDateFormat class docs as a format reference. Correct format is

'MM/dd/yyyy h:mm:ss a'

select from_unixtime(unix_timestamp('11/28/2018 8:35:23 PM', 'MM/dd/yyyy h:mm:ss a'))

Returns:

2018-11-28 20:35:23

Insert into table like this:

INSERT INTO TABLE newtable
select responseid,
       from_unixtime(unix_timestamp(process_start, 'MM/dd/yyyy h:mm:ss a')) process_start,
       from_unixtime(unix_timestamp(process_end, 'MM/dd/yyyy h:mm:ss a')) process_end,
       status
  from oldtable;


问:
Wrong table formatting bootstrap
Hi I have a problem with this code in php, in practice in this table I want to cycle various information taken from the db, only if this information is of different length the formatting of each table is bad, I would like to have the same dimensions for each line, like I could do? the code works correctly, the formatting is wrong ... one column is wider than the other .I would like to leave the first line with the word "N, name, description" and cycle the rest with the same size. Sorry for english</p>

```<code>  while ($row = mysqli_fetch_array($r_query)) {
  echo '
  <table class="table table-bordered">
  <thead>
  <tr>
  <th scope="col">N°</th>
        <th scope="col">name</th>
        <th scope="col">description</th>
      </tr>
     </thead>
     <tbody>
      <tr>
        <th scope="row">' . $_id . '</th>
        <td>' . $_name . '</td>
        <td>' . $_description . '</td>
   <td>' . $_lingua . '</td>
   <td> <input class="btn btn-primary" type="submit"
   value="Send"></td>
   </tr>
   </tbody>
   </table>';
   }
</code>```

答:
Try moving the
 parts and the table header to outside of the PHP loop, so the loop is only iterating through each data item and adding a new table row instead of generating a whole new table for every piece of info.

```<code>echo '<table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">N°</th>
            <th scope="col">name</th>
            <th scope="col">description</th>
          </tr>
        </thead>
        <tbody>';

while ($row = mysqli_fetch_array($r_query)) {
  echo '<tr>
          <th scope="row">' . $_id . '</th>
          <td>' . $_name . '</td>
          <td>' . $_description . '</td>
          <td>' . $_lingua . '</td>
          <td><input class="btn btn-primary" type="submit" value="Send"></td>
        </tr>';
}

echo '</tbody>
    </table>';
</code>```

Title: Wrong table formatting bootstrap

Body:
Hi I have a problem with this code in php, in practice in this table I want to cycle various information taken from the db, only if this information is of different length the formatting of each table is bad, I would like to have the same dimensions for each line, like I could do? the code works correctly, the formatting is wrong ... one column is wider than the other .I would like to leave the first line with the word "N, name, description" and cycle the rest with the same size. Sorry for english

  while ($row = mysqli_fetch_array($r_query)) {
  echo '

  N°
        name
        description

        ' . $_id . '
        ' . $_name . '
        ' . $_description . '
   ' . $_lingua . '
    <input class="btn btn-primary" type="submit"
   value="Send">

';
   }

Body:
Try moving the <table> parts and the table header to outside of the PHP loop, so the loop is only iterating through each data item and adding a new table row instead of generating a whole new table for every piece of info.

echo '<table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">N°</th>
            <th scope="col">name</th>
            <th scope="col">description</th>
          </tr>
        </thead>
        <tbody>';

while ($row = mysqli_fetch_array($r_query)) {
  echo '<tr>
          <th scope="row">' . $_id . '</th>
          <td>' . $_name . '</td>
          <td>' . $_description . '</td>
          <td>' . $_lingua . '</td>
          <td><input class="btn btn-primary" type="submit" value="Send"></td>
        </tr>';
}

echo '</tbody>
    </table>';


问:
Azure Data Factory - Error ingesting data from MySql or Blob Storage
Since last week we're facing some issues involving Data Factory Copy Activities. The issue occurs when the data is already staged into the Blob Storage and it starts to be copied into the SQL DW.

What we can see is that the Throughput rate decreases till we get the following message error:

{ "errorCode": "2200", "message": "ErrorCode=UserErrorFailedToConnectToSqlServer,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=Cannot connect to SQL Server: 'despesas.database.windows.net', Database: 'csc', User: 'master'.,Source=Microsoft.DataTransfer.ClientLibrary,''Type=System.Data.SqlClient.SqlException,Message=A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.),Source=.Net SqlClient Data Provider,SqlErrorNumber=121,Class=20,ErrorCode=-2146232060,State=0,Errors=[{Class=20,Number=121,State=0,Message=A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.),},],''Type=System.ComponentModel.Win32Exception,Message=The semaphore timeout period has expired,Source=,'", "failureType": "UserError", "target": "Copy Data1"

Notice that the issue started last week!

答:
Try creating an Azure Integration Runtime in the same region of the SQL database, sometimes the auto detect region doesnt work.

Create an Azure IR in that region, and create the linked service again, using the new Integration Runtime.

That should solve your problem.

Hope this helped!


问:
Search NSFetchedResultsController using NSPredicate
I've been stuck on this problem for a while now and have tried my best to work out a solution.

I am using Core Data and, being relatively new to iOS coding, I'm having some trouble working out how to search my fetchedResultsController to filter out the string that the user types into the searchBar.

I know how to get the string from the searchBar and how to call my fetchResultsController method. But what I'm struggling with is how to use NSPredicate to match only the rows stored in using core data with that typed in the searchBar.

At the moment I'm doing this in - (NSFetchedResultsController *)fetchedResultsController

(I switch the sort alphabetically just to show myself that it's working).

```<code>if (!isSearching) {
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"LabelValue" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    [sortDescriptor release];
    [sortDescriptors release];
}

else {
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"LabelValue" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    NSLog(@"%@", searchBar.text);

    /*NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY contains[cd] %@", searchBar.text];
    [fetchRequest setPredicate:predicate];*/

    [fetchRequest setSortDescriptors:sortDescriptors];

    [sortDescriptor release];
    [sortDescriptors release];
}
</code>```

I don't quite understand how to use the predicate to filter my data. The commented out code causes an NSException when uncommented:

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "ANY contains[cd] %@"'
</code>```

It's probably quite a simple solution, but I'd be very grateful for any help you are able to offer. Thanks

答:
    </p>

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY <yourFieldNameHere> contains[cd] %@", searchBar.text];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've been stuck on this problem for a while now and have tried my best to work out a solution.

I am using Core Data and, being relatively new to iOS coding, I'm having some trouble working out how to search my fetchedResultsController to filter out the string that the user types into the searchBar.

I know how to get the string from the searchBar and how to call my fetchResultsController method. But what I'm struggling with is how to use NSPredicate to match only the rows stored in using core data with that typed in the searchBar.

At the moment I'm doing this in - (NSFetchedResultsController *)fetchedResultsController

(I switch the sort alphabetically just to show myself that it's working).

if (!isSearching) {
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"LabelValue" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    [sortDescriptor release];
    [sortDescriptors release];
}

else {
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"LabelValue" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    NSLog(@"%@", searchBar.text);

    /*NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY contains[cd] %@", searchBar.text];
    [fetchRequest setPredicate:predicate];*/

    [fetchRequest setSortDescriptors:sortDescriptors];

    [sortDescriptor release];
    [sortDescriptors release];
}

I don't quite understand how to use the predicate to filter my data. The commented out code causes an NSException when uncommented:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "ANY contains[cd] %@"'

It's probably quite a simple solution, but I'd be very grateful for any help you are able to offer. Thanks


问:
Multiple Objective Optimization Java
I've implemented a linear programming problem using the CPLEX API in Java. This problem has 5 linear objectives with different scales. I've tried to implement some normalization methods, but without success. Despite getting a result between 0 and 1, they end up with different orders of magnitude (as I'm using a weighted sum, this is a problem).

Now, I'm wondering to implement this problem with multi-objective optimization using, perhaps, priority criterion. Does CPLEX allow one to implement it? I didn't find much information nor examples. And if not, what are the possible workarounds?

答:
With CPLEX 12.9 you may use multi objective.

See https://www.ibm.com/support/knowledgecenter/SSSA5P_12.9.0/ilog.odms.studio.help/CPLEX/ReleaseNotes/topics/releasenotes1290/newJavaAPI.html

In the Java API of CPLEX V12.9.0, the new implementation of multiobjective optimization offers these new classes and methods. They are documented in the reference manual of the Java API of CPLEX.

These new methods support multiobjective optimization:

```<code>IloCplex.staticLex()
</code>```

Title: Multiple Objective Optimization Java

Body:
With CPLEX 12.9 you may use multi objective.

See https://www.ibm.com/support/knowledgecenter/SSSA5P_12.9.0/ilog.odms.studio.help/CPLEX/ReleaseNotes/topics/releasenotes1290/newJavaAPI.html

In the Java API of CPLEX V12.9.0, the new implementation of multiobjective optimization offers these new classes and methods. They are documented in the reference manual of the Java API of CPLEX.

These new methods support multiobjective optimization:

IloCplex.staticLex()


问:
Parsing html tables using jsoup
I am parsing tables using jsoup. I need to connect to division standing tables from this website: https://www.basketball-reference.com/leagues/NBA_2006.html. Don't know how to parse tables because I need to use the same method for every division standing table, but the id is different for older seasons (e.g. id="divs_standings_W", "id="divs_standings_E" and "id="divs_standings_"). Link to some older season: https://www.basketball-reference.com/leagues/NBA_1950.html.

How can I check if the table with the given id exists and if it exists put it in a variable table? Don't have much relevant code.

```<code>Document doc = Jsoup.connect("https://www.basketball-reference.com/leagues/NBA_1950.html").get();
Elements table = doc.select("table[id=\"divs_standings_\"]");
</code>```

答:
You can just use prefix matching. Use table[id^="divs_standings_"]. This will match all tables, with ids starting with divs_standings_:

```<code>Document doc = Jsoup.connect("https://www.basketball-reference.com/leagues/NBA_1950.html").get();
Element table = doc.selectFirst("table[id^=\"divs_standings_\"]");
</code>```

This will work for old and new seasons.

To wrap this in a method you can just use something like this:

```<code>private static void processTable(String url) throws IOException {
    Document doc = Jsoup.connect(url).get();
    Element table = doc.selectFirst("table[id^=\"divs_standings_\"]");
    System.out.println(table);
}
</code>```

and call it with both urls:

```<code>processTable("https://www.basketball-reference.com/leagues/NBA_1950.html");
processTable("https://www.basketball-reference.com/leagues/NBA_2006.html");
</code>```

You also can use pattern matching if you have more complex ids. Check out the link above for this.

Title: Parsing html tables using jsoup

Body:
I am parsing tables using jsoup. I need to connect to division standing tables from this website: https://www.basketball-reference.com/leagues/NBA_2006.html. Don't know how to parse tables because I need to use the same method for every division standing table, but the id is different for older seasons (e.g. id="divs_standings_W", "id="divs_standings_E" and "id="divs_standings_"). Link to some older season: https://www.basketball-reference.com/leagues/NBA_1950.html.

How can I check if the table with the given id exists and if it exists put it in a variable table? Don't have much relevant code.

Document doc = Jsoup.connect("https://www.basketball-reference.com/leagues/NBA_1950.html").get();
Elements table = doc.select("table[id=\"divs_standings_\"]");

Body:
You can just use prefix matching. Use table[id^="divs_standings_"]. This will match all tables, with ids starting with divs_standings_:

Document doc = Jsoup.connect("https://www.basketball-reference.com/leagues/NBA_1950.html").get();
Element table = doc.selectFirst("table[id^=\"divs_standings_\"]");

This will work for old and new seasons.

To wrap this in a method you can just use something like this:

private static void processTable(String url) throws IOException {
    Document doc = Jsoup.connect(url).get();
    Element table = doc.selectFirst("table[id^=\"divs_standings_\"]");
    System.out.println(table);
}

and call it with both urls:

processTable("https://www.basketball-reference.com/leagues/NBA_1950.html");
processTable("https://www.basketball-reference.com/leagues/NBA_2006.html");

You also can use pattern matching if you have more complex ids. Check out the link above for this.


问:
passing arguments to a dynamic form in django
I have a Dynamic Form in forms. How can I pass an argument from my view when I instantiate my form?

Something like:

```<code>form = DynamicForm("some string argument I'm passing to my form")
</code>```

This is the form I have:

```<code>class DynamicForm(Form):
def __init__(self, *args, **kwargs):
    super(DynamicForm, self).__init__(*args, **kwargs)
    for item in range(5):
        self.fields['test_field_%d' % item] = CharField(max_length=255)
</code>```

答:
You can also achieve this by overriding the get_form_kwargs of the FormMixin, available in class based views.

```<code>class CustomDynamicFormView(FormView):  # inherit any view with formmixin...
      form_class = DynamicForm

      def get_form_kwargs(self):
          kwargs = super(CustomDynamicFormView, self).get_form_kwargs()
          kwargs['custom_variable'] = 'my custom variable'
          return kwargs
</code>```

Then in your form

```<code>class DynamicForm(forms.Form):
    def __init__(self, *args, **kwargs):
        my_var = kwargs.pop('custom_variable')
        # remove this b4 calling super otherwise it will complian
        super(DynamicForm, self).__init__(*args, **kwargs)
        # do what you want with my_var
</code>```

For more information check here

Body:
I have a Dynamic Form in forms. How can I pass an argument from my view when I instantiate my form?

Something like:

form = DynamicForm("some string argument I'm passing to my form")

This is the form I have:

class DynamicForm(Form):
def __init__(self, *args, **kwargs):
    super(DynamicForm, self).__init__(*args, **kwargs)
    for item in range(5):
        self.fields['test_field_%d' % item] = CharField(max_length=255)

Body:
You can also achieve this by overriding the get_form_kwargs of the FormMixin, available in class based views.

class CustomDynamicFormView(FormView):  # inherit any view with formmixin...
      form_class = DynamicForm

      def get_form_kwargs(self):
          kwargs = super(CustomDynamicFormView, self).get_form_kwargs()
          kwargs['custom_variable'] = 'my custom variable'
          return kwargs

Then in your form

class DynamicForm(forms.Form):
    def __init__(self, *args, **kwargs):
        my_var = kwargs.pop('custom_variable')
        # remove this b4 calling super otherwise it will complian
        super(DynamicForm, self).__init__(*args, **kwargs)
        # do what you want with my_var

For more information check here


问:
[BotFramework]: Is there a way to Display Oauth prompt in hero card or Adaptive card in a BOT Developed using SDK V4 in C#?
I am developing a chatbot using V4 in C#; I have implemented an authentication functionality inside a waterfall dialog using OauthCard prompt, I want this oauth card prompt to be displayed inside a Hero Card or Adaptive card or any other card that is suitable such that Login functionality works in Webchat Channel.

Currently, the oauth card prompt is not displayed in the webchat Channel as a result I am unable to login so thought if I can display the sign in functionality of oauth Prompt in Hero card or any suitable card then I can proceed it with authentication functionality.

I have enabled Oauth Prompt using the below link and it perfectly works fine in emulator:

How to fix next step navigation with oauth prompt in waterfall dialog in SDK V4 bot created using C# without typing anything?

But not able to do it in Webchat Channel hence thought if i keep this in hero card it can work.

Language: C#

SDK: V4

Channel: WebChat channel

Please provide the code or procedure in step by step in a detailed guide manner as I am fairly new to BOT and coding so that i can fix my issue.

Please help.

Thanks & Regards
-ChaitayaNG

I do not know how to do it so i tried do the following in index.html:
https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

This is did not work for me either.

I looked into the below links also but according to my understanding there was comments for Team Channel but nothing concrete for webchat channel:

https://github.com/microsoft/botframework-sdk/issues/4768

I also looked into belowlink but since it was related to React i did not investigate it as i am doing the chatbot in webchat channel and in azure C#:

https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/10.a.customization-card-components

I also tried to call oauth prompt inside Singin card which did not work as it was not invoking the prompt either in Emulator or Webchannel.

Hence i need help as the oauth cards are not loading in Web Chat channel even after following above links information. So thought if we can keep in some cards it can be done but did not find any thing concrete to do also. Since i am new to BOT and coding i may have missed something so please help or provide step by step guide on how t do it.

Expected Result: Need the oauth prompt to be displayed inside a HeroCard or any other suitable card as it is code is not working or loading the oauth prompt in Webchat channel working fine in Emulator.
Actual Result: Do not know how to achieve it.

Adding details as per the comments from Richardson:
Hi Richardson,

I have used OauthPrompt in a Water fall dialog where in
STEP 1: I display OAuthCard prompt where i click on link and it pops up a new window to enter credentials and it gives a magic code. I enter the magic code in browser it goes to
STEP 2: Here i am retrieving token and proceeding further as i said this is working in Emulator as described in below link:

How to fix next step navigation with oauth prompt in waterfall dialog in SDK V4 bot created using C# without typing anything?

Coming to Webchat it displayed me the following:
[File of type 'application/vnd.microsoft.card.oauth']

Instead of sign in button or link.

The code i used is the following:

public class LoginDialog : WaterfallDialog
{
    public LoginDialog(string dialogId, IEnumerable<WaterfallStep> steps = null)
         : base(dialogId, steps)
    {
        AddStep(async (stepContext, cancellationToken) =>
        {
            await stepContext.Context.SendActivityAsync("Please login using below option in order to continue with other options...");

            return await stepContext.BeginDialogAsync("loginprompt", cancellationToken: cancellationToken); // This actually calls the  dialogue of OAuthPrompt whose name is  in EchoWithCounterBot.LoginPromptName.

        });

        AddStep(async (stepContext, cancellationToken) =>
        {
            Tokenresponse = (TokenResponse)stepContext.Result;

            if (Tokenresponse != null)
            {

                await stepContext.Context.SendActivityAsync($"logged in successfully... ");

                return await stepContext.BeginDialogAsync(DisplayOptionsDialog.Id); //Here it goes To another dialogue class where options are displayed
            }
            else
            {
                await stepContext.Context.SendActivityAsync("Login was not successful, Please try again...", cancellationToken: cancellationToken);

                await stepContext.BeginDialogAsync("loginprompt", cancellationToken: cancellationToken);
            }

            return await stepContext.EndDialogAsync();
        });
    }

    public static new string Id => "LoginDialog";

    public static LoginDialog Instance { get; } = new LoginDialog(Id);
}
```

<p>In the maindialog called as Mainrootdialog class:
 1. I have a variable  <code>LoginPromptName = "loginprompt"</code> and another parameter for connection name;
 <code>public const string ConnectionName = "conname";</code></p>

<ol start="2">
<li>Then I have a method called prompt which accepts connection name and has oauthprompt related code as given below:</li>
</ol>

<pre class="lang-cs prettyprint-override"><code>  private static OAuthPrompt Prompt(string connectionName)
        {
            return new OAuthPrompt(
               "loginprompt",
               new OAuthPromptSettings
               {
                   ConnectionName = connectionName,
                   Text = "signin",
                   Title = "signin",
                   Timeout = 300000, // User has 5 minutes to login (1000 * 60 *
               });
        }
</code>```

Finally this prompt is added in the Dialogset or stack as below:

     public MainRootDialog(UserState userState)
            : base("root")
        {
            _userStateAccessor = userState.CreateProperty<JObject>("result");

            AddDialog(Prompt(ConnectionName));
            AddDialog(LoginDialog.Instance);
            InitialDialogId = LoginDialog.Id;
        }
```

<p>As tried to explain earlier works perfectly fine in emulator as you could see from my comments in the above shared link  </p>

<p>But in webchat channel does not load button or link gives me this:
 [File of type 'application/vnd.microsoft.card.oauth']</p>

<p>I tried the following GitHub link which i did not work pasting or attaching the HTML file for reference:
https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Web Chat: Customize open URL behavior</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!--
      For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
      or lock down on a specific version with the following format: "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
        html, body {
            height: 100%
        }

        body {
            margin: 0
        }

        #webchat,
        #webchat > * {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="webchat" role="main">
        <iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<Given my secretkey of web chat channel>>' style='min-width: 400px; width: 100%; min-height: 500px;'></iframe>
    </div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
        const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });
        const { token } = await res.json();
        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          // We are adding a new middleware to handle card action
          cardActionMiddleware: () => next => async ({ cardAction, getSignInUrl }) => {
            const { type, value } = cardAction;
            switch (type) {
              case 'signin':
                // For OAuth or sign-in popups, we will open the auth dialog directly.
                const popup = window.open();
                const url = await getSignInUrl();
                popup.location.href = url;
                break;
              case 'openUrl':
                if (confirm(`Do you want to open this URL?\n\n${ value }`)) {
                  window.open(value, '_blank');
                }
                break;
              default:
                return next({ cardAction, getSignInUrl });
            }
          }
        }, document.getElementById('webchat'));
        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
</body>
</html></code>```

Coming to the link you have provided it does not open it gives me 404 error

Date: 29-May-2019
Reason: Further queries on inputs provided by Richardson

I understand there is a .NET Code written inside a controller class which generates the Token. There is a html page to load our web chat which contains required scripts
to store or expose tokens and then the chat bot opens whenever we open this HTML file. However,  I have following queries. These might seem very basic but please bear with me as I am new to coding:

Where the code should be written, how will it get called because I am not specifying in my html script
or anywhere call the Controller class Index method to generate the token and use it? Or will it call automatically the index method inside controller. If not, automatically where should I specify this that u call index method? Is it possible to provide whole solution like having bot code and controller class at solution so that I can get a better picture so that I can ask any other further queries if any?

Is this .net code is a separate solution or inside the same bot solution controller class should be written? If separate solution, then how to publish this to the BOT resource  in azure? How bot and new solution will interact automatically without providing any connection?

I am assuming it should a new class inside the same  BOT Code solution in Visual Studio. Now, I have further queries on this(based on this assumption):

a. As per my understanding on your explanation the post method is not working because there is no Token generator, so it gives you an error. You can use the below link to write the code and get the token which again brings to question number 1?

What is the correct way to authenticate from JavaScript in an HTML file to the Microsoft Web Chat control for Bot Framework v4?

b. In the HTML file if I write the script given as per above link then should be in the same async function or we have to remove the async function?

c. Still the style options like BOT Avatar and etc work if kept as is ? same way other scripts for displaying welcome message?

d. In the GetElementByID('') we are passing bot as the value from the link above but in actual samples we pass web chat is it because we have changed the POST method to the new script?

e. Should the post method still be kept or can be removed? Instead of the  post line:

const res = await fetch('https://examplebot.azurewebsites.net/directline/token', { method: 'POST' });
        Write new one as below: the script given below (taken from above link):

```<code>@model ChatConfig
@{
    ViewData["Title"] = "Home Page";
}
<link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />
<div id="bot" />
<script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
<script>
      BotChat.App({
          directLine: {
              secret: '@Model.Token'
          },
        user: { id: @Model.UserId },
        bot: { id: 'botid' },
        resize: 'detect'
      }, document.getElementById("bot"));
</script>
</code>```

You have also explained that to avoid all these complications and make it simple  just keep your secret in the file:
Current: const { token } = await res.json();
To make it simple: const { token } = <>;
Is my understanding, right?

On top of 4th question: Then the POST method line should also be removed i.e. below line and we don’t have to write the new controller class or the script given above of Model config and rest keep as is:
Something like below and the bot loads when I open the page and the OAuth prompts and adaptive cards work without any issue:

    Avanade D365 F&O Assets BOT

```<code><!--
  For demonstration purposes, we are using development branch of Web Chat at "/master/webchat.js".
  When you are using Web Chat for production, you should use the latest stable at "/latest/webchat.js".
  Or locked down on a specific version "/4.1.0/webchat.js".
-->
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
    html, body {
        height: 100%
    }

    body {
        margin: 0
    }

    #webchat {
        height: 100%;
        width: 100%;
    }
</style>
</code>```

```<code></div>
<script>
  (async function () {
    // In this demo, we are using Direct Line token from MockBot.
    // To talk to your bot, you should use the token exchanged using your Direct Line secret.
    // You should never put the Direct Line secret in the browser or client app.
    // https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication

      const { token } = <<Directline secret from azure portal durect line channel>>;

      const styleOptions = {
       botAvatarImage: 'https://learn.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
       botAvatarInitials: 'BF',
       userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
       userAvatarInitials: 'WC',
       bubbleBackground: 'rgba(0, 0, 255, .1)',
       bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
  };
    // We are using a customized store to add hooks to connect event
    const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
      if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
        // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
        dispatch({
          type: 'WEB_CHAT/SEND_EVENT',
          payload: {
            name: 'webchat/join',
            value: { language: window.navigator.language }
          }
        });
      }
      return next(action);
    });
    window.WebChat.renderWebChat({
      directLine: window.WebChat.createDirectLine({ token }),
      store
    }, document.getElementById('webchat'));
    document.querySelector('#webchat > *').focus();
  })().catch(err => console.error(err));
</script>
</code>```

Is my understanding, right?

30 May 2019
ChaitanyaNG Updates for the Comment:
Screenshot: For reference on the findings of using the HTML file provided by Richardson as is and replacing it by my BOT Direct Channel secret key

答:
The real issue is in your comment here:

Coming to Webchat it displayed me the following: [File of type 'application/vnd.microsoft.card.oauth']

which is caused by:

        <iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<Given my secretkey of web chat channel>>' style='min-width: 400px; width: 100%; min-height: 500px;'>

    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication

        // Token is found by going to Azure Portal > Your Web App Bot > Channels > Web Chat - Edit > Secret Keys - Show
        // It looks something like this: pD*********xI.8ZbgTHof3GL_nM5***********aggt5qLOBrigZ8
        const token = '<Directline secret from azure portal durect line channel>';

        // You can modify the style set by providing a limited set of style options
        const styleOptions = {
            botAvatarImage: 'https://learn.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
            botAvatarInitials: 'BF',
            userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
            userAvatarInitials: 'WC',
            bubbleBackground: 'rgba(0, 0, 255, .1)',
            bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
        };

        // We are using a customized store to add hooks to connect event
        const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
        if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
            // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
            dispatch({
            type: 'WEB_CHAT/SEND_EVENT',
            payload: {
                name: 'webchat/join',
                value: { language: window.navigator.language }
            }
            });
        }
        return next(action);
        });

        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          styleOptions
        }, document.getElementById('webchat'));

        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>

```

Answering your questions

a. Correct. POST method is not working because there wasn't a token server at the link you were using.

b. Use the code I have above

c. Yes, you can style however you want. Welcome messages should work because of the 'DIRECT_LINE/CONNECT_FULFILLED' code. You can add additional code from the WebChat samples to accomplish other things, yes.

d. Don't use the code that passes "bot" in getElementById. Use the code from the WebChat samples or the code I posted

e. Remove the post method unless you're using a token server.

That's mostly right. See above responses.

Yes. Remove the POST method. Your code was very close!!

Ensure the token you use comes from here:

Body:
I am developing a chatbot using V4 in C#; I have implemented an authentication functionality inside a waterfall dialog using OauthCard prompt, I want this oauth card prompt to be displayed inside a Hero Card or Adaptive card or any other card that is suitable such that Login functionality works in Webchat Channel.

Currently, the oauth card prompt is not displayed in the webchat Channel as a result I am unable to login so thought if I can display the sign in functionality of oauth Prompt in Hero card or any suitable card then I can proceed it with authentication functionality.

I have enabled Oauth Prompt using the below link and it perfectly works fine in emulator:

How to fix next step navigation with oauth prompt in waterfall dialog in SDK V4 bot created using C# without typing anything?

But not able to do it in Webchat Channel hence thought if i keep this in hero card it can work.

Language: C#

SDK: V4

Channel: WebChat channel

Please provide the code or procedure in step by step in a detailed guide manner as I am fairly new to BOT and coding so that i can fix my issue.

Please help.

Thanks & Regards
-ChaitayaNG

I do not know how to do it so i tried do the following in index.html:
https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

This is did not work for me either.

I looked into the below links also but according to my understanding there was comments for Team Channel but nothing concrete for webchat channel:

https://github.com/microsoft/botframework-sdk/issues/4768

I also looked into belowlink but since it was related to React i did not investigate it as i am doing the chatbot in webchat channel and in azure C#:

https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/10.a.customization-card-components

I also tried to call oauth prompt inside Singin card which did not work as it was not invoking the prompt either in Emulator or Webchannel.

Hence i need help as the oauth cards are not loading in Web Chat channel even after following above links information. So thought if we can keep in some cards it can be done but did not find any thing concrete to do also. Since i am new to BOT and coding i may have missed something so please help or provide step by step guide on how t do it.

Expected Result: Need the oauth prompt to be displayed inside a HeroCard or any other suitable card as it is code is not working or loading the oauth prompt in Webchat channel working fine in Emulator.
Actual Result: Do not know how to achieve it.

Adding details as per the comments from Richardson:
Hi Richardson,

I have used OauthPrompt in a Water fall dialog where in
STEP 1: I display OAuthCard prompt where i click on link and it pops up a new window to enter credentials and it gives a magic code. I enter the magic code in browser it goes to
STEP 2: Here i am retrieving token and proceeding further as i said this is working in Emulator as described in below link:

How to fix next step navigation with oauth prompt in waterfall dialog in SDK V4 bot created using C# without typing anything?

Coming to Webchat it displayed me the following:
[File of type 'application/vnd.microsoft.card.oauth']

Instead of sign in button or link.

The code i used is the following:

public class LoginDialog : WaterfallDialog
{
    public LoginDialog(string dialogId, IEnumerable<WaterfallStep> steps = null)
         : base(dialogId, steps)
    {
        AddStep(async (stepContext, cancellationToken) =>
        {
            await stepContext.Context.SendActivityAsync("Please login using below option in order to continue with other options...");

            return await stepContext.BeginDialogAsync("loginprompt", cancellationToken: cancellationToken); // This actually calls the  dialogue of OAuthPrompt whose name is  in EchoWithCounterBot.LoginPromptName.

        });

        AddStep(async (stepContext, cancellationToken) =>
        {
            Tokenresponse = (TokenResponse)stepContext.Result;

            if (Tokenresponse != null)
            {

                await stepContext.Context.SendActivityAsync($"logged in successfully... ");

                return await stepContext.BeginDialogAsync(DisplayOptionsDialog.Id); //Here it goes To another dialogue class where options are displayed
            }
            else
            {
                await stepContext.Context.SendActivityAsync("Login was not successful, Please try again...", cancellationToken: cancellationToken);

                await stepContext.BeginDialogAsync("loginprompt", cancellationToken: cancellationToken);
            }

            return await stepContext.EndDialogAsync();
        });
    }

    public static new string Id => "LoginDialog";

    public static LoginDialog Instance { get; } = new LoginDialog(Id);
}

In the maindialog called as Mainrootdialog class:
 1. I have a variable  LoginPromptName = "loginprompt" and another parameter for connection name;
 public const string ConnectionName = "conname";

Then I have a method called prompt which accepts connection name and has oauthprompt related code as given below:

  private static OAuthPrompt Prompt(string connectionName)
        {
            return new OAuthPrompt(
               "loginprompt",
               new OAuthPromptSettings
               {
                   ConnectionName = connectionName,
                   Text = "signin",
                   Title = "signin",
                   Timeout = 300000, // User has 5 minutes to login (1000 * 60 *
               });
        }

Finally this prompt is added in the Dialogset or stack as below:

     public MainRootDialog(UserState userState)
            : base("root")
        {
            _userStateAccessor = userState.CreateProperty<JObject>("result");

            AddDialog(Prompt(ConnectionName));
            AddDialog(LoginDialog.Instance);
            InitialDialogId = LoginDialog.Id;
        }

As tried to explain earlier works perfectly fine in emulator as you could see from my comments in the above shared link

But in webchat channel does not load button or link gives me this:
 [File of type 'application/vnd.microsoft.card.oauth']

I tried the following GitHub link which i did not work pasting or attaching the HTML file for reference:
https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/18.customization-open-url

<!DOCTYPE html>

    <title>Web Chat: Customize open URL behavior</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<Given my secretkey of web chat channel>>' style='min-width: 400px; width: 100%; min-height: 500px;'>

Coming to the link you have provided it does not open it gives me 404 error

Date: 29-May-2019
Reason: Further queries on inputs provided by Richardson

I understand there is a .NET Code written inside a controller class which generates the Token. There is a html page to load our web chat which contains required scripts
to store or expose tokens and then the chat bot opens whenever we open this HTML file. However,  I have following queries. These might seem very basic but please bear with me as I am new to coding:

Where the code should be written, how will it get called because I am not specifying in my html script
or anywhere call the Controller class Index method to generate the token and use it? Or will it call automatically the index method inside controller. If not, automatically where should I specify this that u call index method? Is it possible to provide whole solution like having bot code and controller class at solution so that I can get a better picture so that I can ask any other further queries if any?

Is this .net code is a separate solution or inside the same bot solution controller class should be written? If separate solution, then how to publish this to the BOT resource  in azure? How bot and new solution will interact automatically without providing any connection?

I am assuming it should a new class inside the same  BOT Code solution in Visual Studio. Now, I have further queries on this(based on this assumption):

a. As per my understanding on your explanation the post method is not working because there is no Token generator, so it gives you an error. You can use the below link to write the code and get the token which again brings to question number 1?

What is the correct way to authenticate from JavaScript in an HTML file to the Microsoft Web Chat control for Bot Framework v4?

b. In the HTML file if I write the script given as per above link then should be in the same async function or we have to remove the async function?

c. Still the style options like BOT Avatar and etc work if kept as is ? same way other scripts for displaying welcome message?

d. In the GetElementByID('') we are passing bot as the value from the link above but in actual samples we pass web chat is it because we have changed the POST method to the new script?

e. Should the post method still be kept or can be removed? Instead of the  post line:

const res = await fetch('https://examplebot.azurewebsites.net/directline/token', { method: 'POST' });
        Write new one as below: the script given below (taken from above link):

@model ChatConfig
@{
    ViewData["Title"] = "Home Page";
}
<link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />

You have also explained that to avoid all these complications and make it simple  just keep your secret in the file:
Current: const { token } = await res.json();
To make it simple: const { token } = <>;
Is my understanding, right?

On top of 4th question: Then the POST method line should also be removed i.e. below line and we don’t have to write the new controller class or the script given above of Model config and rest keep as is:
Something like below and the bot loads when I open the page and the OAuth prompts and adaptive cards work without any issue:

    Avanade D365 F&O Assets BOT

Is my understanding, right?

30 May 2019
ChaitanyaNG Updates for the Comment:
Screenshot: For reference on the findings of using the HTML file provided by Richardson as is and replacing it by my BOT Direct Channel secret key

Body:
The real issue is in your comment here:

Coming to Webchat it displayed me the following: [File of type 'application/vnd.microsoft.card.oauth']

which is caused by:

<div id="webchat" role="main">
        <iframe src='https://webchat.botframework.com/embed/TestBotForOauthPrompt?s=<<Given my secretkey of web chat channel>>' style='min-width: 400px; width: 100%; min-height: 500px;'></iframe>
    </div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
        const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });
        const { token } = await res.json();

First issue: You're using both the iframe (<iframe src='https://webchat...) and WebChat (<script> (async function ()...).

Fix: Remove the iframe and just use the WebChat code. This isn't really documented anywhere, but the iFrame uses botchat, which is an older version of WebChat, which doesn't work with OAuth and is what's giving you the [File of type... error.

Second issue: You aren't getting a valid token

const res = await fetch('https://testbotforoauthprompt.azurewebsites.net//directline//token', { method: 'POST' });

That code returns a 404 because https://testbotforoauthprompt.azurewebsites.net/directline/token doesn't exist.

You should follow the guide linked in the code comments, which would have you make a POST request to https://directline.botframework.com/v3/directline/tokens/generate with Authorization: Bearer <YourSecretFromAzurePortal> in the header.

Alternatively, you can use const token = <YourSecretFromAzurePortal> directly, instead. Note that it isn't a good idea to use your secret directly. You should really set up a token server. This should get you started (note: this is the link I intended to use in my comment above), but it's a little more complex. If you just want something simple and don't care if your app secret gets out, go with the const token = <YourSecretFromAzurePortal> method.

I just answered a similar question, here.

Regarding your updates

Token Generator

Regarding: this answer

If you want to keep your Secret private, you need to write your own token server. The first half of the linked answer explains a basic way to do this. You can either write your own, use the sample in that linked answer, or use the code from the blog posts that are linked in that answer.

Where to put the code is dependent on how you want it to run. The sample token server is entirely separate from the bot. The blog post samples show how to integrate it into your bot (although you can also host it separately).

The WebChat client makes a request to that token server, which makes a request to https://directline.botframework.com/v3/directline/tokens/generate and returns the response, which is a valid DirectLine token.

However, in many cases you don't need the extra security of writing your own token server. The second half of the linked answer explains that the security risks of exposing your secret are minimal for many simple bots.

I recommend, for you (since you said you're fairly new to coding), that you don't write your own token server and just leave the secret exposed in const token = <Directline secret from azure portal direct line channel>; (Note that I removed the {}, since your token is a string). If you really want to use a token server, you'll need to learn how to write a server in C#.

HTML File

The code you got from examplebot.azurewebsites... uses Angular (I think). It's old. Don't use it.

You should base your HTML code off of one of the WebChat Samples.

It looks like your last code block does. Since there's been a lot of confusion, just use this:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Web Chat: Custom style options</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--
      For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
      or lock down on a specific version with the following format: "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
    <style>
        html, body {
            height: 100%
        }

        body {
            margin: 0
        }

        #webchat {
            height: 100%;
            width: 100%;
        }
    </style>
  </head>
  <body>
    <div id="webchat" role="main"></div>
    <script>
      (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication

        // Token is found by going to Azure Portal > Your Web App Bot > Channels > Web Chat - Edit > Secret Keys - Show
        // It looks something like this: pD*********xI.8ZbgTHof3GL_nM5***********aggt5qLOBrigZ8
        const token = '<Directline secret from azure portal durect line channel>';

        // You can modify the style set by providing a limited set of style options
        const styleOptions = {
            botAvatarImage: 'https://learn.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
            botAvatarInitials: 'BF',
            userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
            userAvatarInitials: 'WC',
            bubbleBackground: 'rgba(0, 0, 255, .1)',
            bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
        };

        // We are using a customized store to add hooks to connect event
        const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
        if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
            // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
            dispatch({
            type: 'WEB_CHAT/SEND_EVENT',
            payload: {
                name: 'webchat/join',
                value: { language: window.navigator.language }
            }
            });
        }
        return next(action);
        });

        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token }),
          styleOptions
        }, document.getElementById('webchat'));

        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
  </body>
</html>

Answering your questions

a. Correct. POST method is not working because there wasn't a token server at the link you were using.

b. Use the code I have above

c. Yes, you can style however you want. Welcome messages should work because of the 'DIRECT_LINE/CONNECT_FULFILLED' code. You can add additional code from the WebChat samples to accomplish other things, yes.

d. Don't use the code that passes "bot" in getElementById. Use the code from the WebChat samples or the code I posted

e. Remove the post method unless you're using a token server.

That's mostly right. See above responses.

Yes. Remove the POST method. Your code was very close!!

Ensure the token you use comes from here:


问:
Public API is giving me CORS error when calling axios in create-react-app but all is well in Chrome and Postman
Forgive me for the obvious error I am obviously committing...

I understand CORS, how and why it's used.  But I'm missing the blindingly obvious in this instance.

I'm trying to access a publicly available API that should work fine (I've been assured)

If I hit the endpoint in Chrome, or in Postman, all works fine: wonderful JSON is returned.

When I try to do the same using axios from within my create-react-app's componentDidMount, I get a CORS error, specifically

```<code>Access to XMLHttpRequest at 'http://some-interesting-url/sub-url?blabla=blip&foo=bar' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

What is it I'm failing to grasp?  Is there anything I can do from my end? (I have no control over the server)

答:
The Postman app is not a browser so it isn't bound by the rules of CORS. In a browser too, trying to access a URL directly doesn't trigger Cross-Origin-Request-Sharing policies. CORS, by definition will only affects the 'cross-origin' requests made from background JS code of a web-page, to another web-page or API not hosted on same domain name.

Based on the error posted, the API in question is not sending Access-Control-Allow-Origin header. If it's possible to get the API changed, that you should get the header added to response (with value '*', or your domain name). However if that's not possible, then you'd need to route the request through a web-server that you own and include this header there. This kind of does work like a proxy, albeit for a specialized use-case.

If you already have some server side application running, you can simply add another end point to your application. A call to this new end point should trigger the 'Public API' call, and send the response back to client. Since the server side program (eg PHP/Python/NodeJS) would never be a browser, they will not face the CORS issues. If your original web-page is also loaded from same web-server, then the response header can be skipped.

Body:
Forgive me for the obvious error I am obviously committing...

I understand CORS, how and why it's used.  But I'm missing the blindingly obvious in this instance.

I'm trying to access a publicly available API that should work fine (I've been assured)

If I hit the endpoint in Chrome, or in Postman, all works fine: wonderful JSON is returned.

When I try to do the same using axios from within my create-react-app's componentDidMount, I get a CORS error, specifically

Access to XMLHttpRequest at 'http://some-interesting-url/sub-url?blabla=blip&foo=bar' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What is it I'm failing to grasp?  Is there anything I can do from my end? (I have no control over the server)


问:
Parse combination of command-line arguments and flags in bash
I am trying to write bash script which will read multiple filenames and a target directory, which is optional.

./myfile -t /home/users/ file1 file2

I have tried the following code, but I am not able to handle different scenarios mentioned below:

```<code>while getopts "t:" opt; do
  case $opt in
    t)
      echo "-t was triggered, Parameter: $OPTARG"
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument."
      exit 1
      ;;
  esac
done
</code>```

But the code should handle different scenarios like:
./myfile file1 file2 -t /home/users/,
./myfile file1  -t /home/users/ file2 file3,
./myfile file1 file2 file3 file4
and should be able to read the files.

答:
After your while loop, you need to shift out any options and their arguments. This works even if there aren't any flags/flag arguements.

```<code>shift $(($OPTIND - 1))
</code>```

Then the rest of the arguments are available in "$@" and can be dealt with in any of the usual ways. For example:

```<code>for arg in "$@"
do
    something_with "$arg"
done
</code>```

For some more information, see my answer here.

Body:
I am trying to write bash script which will read multiple filenames and a target directory, which is optional.

./myfile -t /home/users/ file1 file2

I have tried the following code, but I am not able to handle different scenarios mentioned below:

while getopts "t:" opt; do
  case $opt in
    t)
      echo "-t was triggered, Parameter: $OPTARG"
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument."
      exit 1
      ;;
  esac
done

But the code should handle different scenarios like:
./myfile file1 file2 -t /home/users/,
./myfile file1  -t /home/users/ file2 file3,
./myfile file1 file2 file3 file4
and should be able to read the files.

Body:
After your while loop, you need to shift out any options and their arguments. This works even if there aren't any flags/flag arguements.

shift $(($OPTIND - 1))

Then the rest of the arguments are available in "$@" and can be dealt with in any of the usual ways. For example:

for arg in "$@"
do
    something_with "$arg"
done

For some more information, see my answer here.


问:
Building custom controls: use WebControl or Control?
There are a lot of ways to build custom controls for Asp.Net. Some people use the System.Web.UI.WebControls.WebControl as a base class and other people use the System.Web.UI.Control as a base class for their new controls.

What are the reasons to choose the one or the other as a base?

答:
System.Web.UI.WebControls.Webcontrol derives from the System.Web.UI.Control and adds support for styling (BackgroundColor, Style, etc.).

Control doesn’t have that support by default, you’ll have to implement it yourself by creating properties and handle those on the Render() method. WebControls also come with theming and toolbox support for certain common properties.

ContentLicense: CC BY-SA 2.5


问:
Putting RUN commands in one line make build faster?
In my docker file, does it really matter if I put RUN commands in one line or not? Does putting them in one line make build time faster?

```<code>RUN apt-get update
RUN apt-get -y install --no-install-recommends python3
RUN apt-get -y install --no-install-recommends open-vm-tools
</code>```

vs.

```<code>RUN apt-get update && apt-get -y install --no-install-recommends python3
RUN apt-get -y install --no-install-recommends open-vm-tools
</code>```

答:
If you don't clean the apt cache at the end of your "one liner" you are actually not achieving a lot. A big layer is still added to your image.

The main idea is to put all the installations on one line and end that line with a cleanup, so that when docker saves that layer (before moving on to the next command) it only saves the newly installed software without all the downloads and cache that are not used anymore anyway.

As for the speed probably you gain a little with writing more on 1 line but I don't think it is that much. Of course if you have hundreds of them then you would see a difference.

Body:
In my docker file, does it really matter if I put RUN commands in one line or not? Does putting them in one line make build time faster?

RUN apt-get update
RUN apt-get -y install --no-install-recommends python3
RUN apt-get -y install --no-install-recommends open-vm-tools

vs.

RUN apt-get update && apt-get -y install --no-install-recommends python3
RUN apt-get -y install --no-install-recommends open-vm-tools


问:
Cypher Neo4j Couldn't load the external resource
In a Windows environment, I'm trying to load a .csv file with statement:

```<code>LOAD CSV WITH HEADERS FROM "file:///E:/Neo4j/customers.csv" AS row
</code>```

It seems not to work properly and returns:
Couldn't load the external resource at:

file:/E:/Neo4j/Customers.csv
  Neo.TransientError.Statement.ExternalResourceFailure

What am I doing wrong? thanks in advance

答:
For macOS Mojave v 10.14.5

Actually, I had to uncomment dbms.directories.import=import from ~/Library/Application Support/Neo4j Desktop/Application/neo4jDatabases/database-e2dd2a9c-d450-4639-861b-1e7e42b56b31/installation-3.5.5/conf/neo4j.conf and restart the service. Then it worked. All files has to be placed in import directory.

Run command LOAD CSV WITH HEADERS FROM 'FILE:/<yourCSV>.csv' as l return l

Body:
In a Windows environment, I'm trying to load a .csv file with statement:

LOAD CSV WITH HEADERS FROM "file:///E:/Neo4j/customers.csv" AS row

It seems not to work properly and returns:
Couldn't load the external resource at:

file:/E:/Neo4j/Customers.csv
  Neo.TransientError.Statement.ExternalResourceFailure

What am I doing wrong? thanks in advance


问:
Java: Why internal class has to be static?
I know that internal class has to be static because will link between public and internal classes and internal class will be created all times that created public classes.
And my question how to check it?
I mean write some simple application and make some loop for creating objects and see that objects do not deleted by GC in some profiler, Can I to do something like that nad some one done it?
Thanks.</p>

答:
An internal class does not have to be static. In fact, one of their most common manifestations - anonymous inner classes - are never static.

The phrase "static class" does not cause a class to get created at runtime - classes are only "created" once, by the classloader, when they are loaded. What you meant to say is that the instance of the internal class will be created every time an instance of the outer class is created. And this too is false in general (see Thilo's answer).

Don't worry - I misunderstood internal classes in exactly the same way as you when I first learned about them!

A non-static inner class will have an implicit (i.e. it's there automatically, you don't declare it) reference to the instance of the outer class which created it. This will prevent the instance of the outer class being GCed as long as the instance of the inner class exists, just like a normal Java reference.

A static internal class will not have such a reference, because it is not created by an outer instance but by the classloader.


问:
How to give different divs a different height in the same line
I have 3 images with text next to it (Social media). And I want the text have a different padding or margin so it is in the center of the image. But when I use one of these, the images are going higher as well. I think this is because they all have display: inline-block;.

This is the html code;

```<code>    <footer>
        <div id="socialIcon"><img src="images/media/telefoon.png" width="30"></div>
        <div id="socialText">06-123456</div>
        <div id="socialIcon"><img src="images/media/mail.png" width="30"></div>
        <div id="socialText">example@gmail.com</div>
        <div id="socialIcon"><a class="socialIcon" href="https://www.instagram.com/example/"><img src="images/media/instagram.png" width="30px"</a></div>
        <div id="socialText"><a class="socialText" href="https://www.instagram.com/example/">@example</a></div>
    </footer>
</code>```

This is the css code:

```<code>footer {
    background: #222222;
    position: fixed;
    bottom: 0;
    width: 100%;
    color: white;
    font-family: proxima-nova, sans-serif;
    text-align: center;
    font-size: 20px;
}
#socialText{
    display: inline-block;
    margin-bottom: 10px;

}
#socialIcon{
    display: inline-block;
    margin-left: 10px;
    margin-right: 3px;
    margin-bottom: 0px;
    margin-top: 0px;
    padding-bottom: 0px;
    height: 30px;
}
</code>```

But right now not only the socialText goes 10px up, the socialIcon as well.

答:
One of your problem will be caused by the missing closing bracket in the <img src="images/media/instagram.png" width="30px" line that causes the next opening tag to be interpreted as part of the previous (unclosed) HTML tag. All following opening and closing tags will then be interpreted incorrectly e.g. the closing
 does not fit the opening  tag that came before the .

Besides that you should set:

```<code>img {
  vertical-align: middle;
}
</code>```

to have other containers align with your images in the vertical middle.

As mentioned by BugsArePeopleToo please do not use duplicate IDs, use CSS classes instead. Here's a snippet of the changed code:

footer {
  background: #666;
  position: fixed;
  bottom: 0;
  width: 100%;
  color: white;
  font-family: proxima-nova, sans-serif;
  text-align: center;
  font-size: 20px;
  padding: 5px;
}

.socialText {
  display: inline-block;
}

.socialIcon {
  display: inline-block;
  margin-left: 10px;
  margin-right: 3px;
  margin-bottom: 0px;
  margin-top: 0px;
  padding-bottom: 0px;
  height: 30px;
}

footer img {
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="socialIcon"><img src="https://pngimage.net/wp-content/uploads/2018/06/telefoon-png.png" height="30"></div>
  <div class="socialText">06-123456</div>
  <div class="socialIcon"><img src="https://pngimage.net/wp-content/uploads/2019/05/white-mail-png-1.png" height="30"></div>
  <div class="socialText">Example@GMail.com</div>
  <div class="socialIcon">
  <img src="https://pngimage.net/wp-content/uploads/2019/05/white-transparent-instagram-png-1.png" height="30"/></div>
  <div class="socialText">@example</div>
</footer></code>```

Body:
I have 3 images with text next to it (Social media). And I want the text have a different padding or margin so it is in the center of the image. But when I use one of these, the images are going higher as well. I think this is because they all have display: inline-block;.

This is the html code;

06-123456

example@gmail.com

<img src="images/media/instagram.png" width="30px"

@example

This is the css code:

footer {
    background: #222222;
    position: fixed;
    bottom: 0;
    width: 100%;
    color: white;
    font-family: proxima-nova, sans-serif;
    text-align: center;
    font-size: 20px;
}
#socialText{
    display: inline-block;
    margin-bottom: 10px;

}
#socialIcon{
    display: inline-block;
    margin-left: 10px;
    margin-right: 3px;
    margin-bottom: 0px;
    margin-top: 0px;
    padding-bottom: 0px;
    height: 30px;
}

But right now not only the socialText goes 10px up, the socialIcon as well.

Body:
One of your problem will be caused by the missing closing bracket in the <img src="images/media/instagram.png" width="30px" line that causes the next opening tag to be interpreted as part of the previous (unclosed) HTML tag. All following opening and closing tags will then be interpreted incorrectly e.g. the closing </div> does not fit the opening <a> tag that came before the <img>.

Besides that you should set:

img {
  vertical-align: middle;
}

to have other containers align with your images in the vertical middle.

As mentioned by BugsArePeopleToo please do not use duplicate IDs, use CSS classes instead. Here's a snippet of the changed code:

footer {
  background: #666;
  position: fixed;
  bottom: 0;
  width: 100%;
  color: white;
  font-family: proxima-nova, sans-serif;
  text-align: center;
  font-size: 20px;
  padding: 5px;
}

.socialText {
  display: inline-block;
}

.socialIcon {
  display: inline-block;
  margin-left: 10px;
  margin-right: 3px;
  margin-bottom: 0px;
  margin-top: 0px;
  padding-bottom: 0px;
  height: 30px;
}

footer img {
  vertical-align: middle;
}

<footer>
  <div class="socialIcon"><img src="https://pngimage.net/wp-content/uploads/2018/06/telefoon-png.png" height="30"></div>
  <div class="socialText">06-123456</div>
  <div class="socialIcon"><img src="https://pngimage.net/wp-content/uploads/2019/05/white-mail-png-1.png" height="30"></div>
  <div class="socialText">Example@GMail.com</div>
  <div class="socialIcon"><a class="socialIcon" href="https://www.instagram.com/example/">
  <img src="https://pngimage.net/wp-content/uploads/2019/05/white-transparent-instagram-png-1.png" height="30"/></a></div>
  <div class="socialText"><a class="socialText" href="https://www.instagram.com/example/">@example</a></div>
</footer>


问:
Can a trait have a supertrait that is parameterized by a generic?
Can you do something like this in Rust?

```<code>trait A : forall<T> B<T> { ... }
</code>```

That is, if we want:

```<code>impl A for D { ... }
</code>```

We must first implement:

```<code>impl<T> B<T> for D { ... }
</code>```

答:
No. Rust's type system doesn't currently support any features involving higher kinded types. It does, however, support a similar construction to what you described, but limited to lifetime parameters. For example:

```<code>trait B<'a> {}

trait A: for<'a> B<'a> {}

struct D;

impl A for D { }
</code>```

This is an error:

error[E0277]: the trait bound `for<'a> D: B<'a>` is not satisfied
 --> src/lib.rs:7:6
  |
7 | impl A for D { }
  |      ^ the trait `for<'a> B<'a>` is not implemented for `D`
```

<p>Until you add the blanket implementation:</p>

```impl<'a> B<'a> for D { }
```

It's not impossible that Rust will eventually add similar functionality for types too, but I wouldn't expect it any time soon.

Body:
Can you do something like this in Rust?

trait A : forall<T> B<T> { ... }

That is, if we want:

impl A for D { ... }

We must first implement:

impl<T> B<T> for D { ... }

Body:
No. Rust's type system doesn't currently support any features involving higher kinded types. It does, however, support a similar construction to what you described, but limited to lifetime parameters. For example:

trait B<'a> {}

trait A: for<'a> B<'a> {}

struct D;

impl A for D { }

This is an error:

error[E0277]: the trait bound `for<'a> D: B<'a>` is not satisfied
 --> src/lib.rs:7:6
  |
7 | impl A for D { }
  |      ^ the trait `for<'a> B<'a>` is not implemented for `D`

Until you add the blanket implementation:

impl<'a> B<'a> for D { }

It's not impossible that Rust will eventually add similar functionality for types too, but I wouldn't expect it any time soon.


问:
How to transform a DataFrame into a dictionary taking just the mapped values?
I need to reset some values in a DataFrame of objects

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

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})

def test(ar):
    if ar == ['']:
        return False
    else:
        return True

df.applymap(test)
</code>```

The applymap returns this:

I just need to take the columns and cells with True into a structure like the following:

```<code>d = {
    'x': [(0, [''])],
    'y': [(0, ['']), (1, ['']),]
    'z': [(0, ['']), (1, ['']),]
}
</code>```

Which is the fastest method to achieve this? There has to be a simple way to solve it.

答:
There's probably a smarter way to do this, but this gets the job done:

```<code>>>> df = pd.DataFrame({'x': [True, False], 'y': [True, True], 'z': [True, True]})
>>> df
       x     y     z
0   True  True  True
1  False  True  True

>>> d = {}

>>> for column in df.columns:
...:     d[column] = []
...:     for index, value in enumerate(column):
...:         if value == True:
...:             d[column].append((index, ['']))
...:
>>> d
{'x': [(0, [''])], 'y': [(0, ['']), (1, [''])], 'z': [(0, ['']), (1, [''])]}
</code>```

Algorythm improved by the asker

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

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'q': [[''], ['']],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})

def test(ar):
    if ar == ['']:
        return False
    else:
        return True

new_df = df.applymap(test)
d = {}
for column in new_df.columns:
    s = new_df[column][new_df[column] == True]
    if s.size >= 1:
        d[column] = []
        for index, value in enumerate(s):
            if value == True:
                d[column].append((index, ['']))
d
</code>```

Body:
I need to reset some values in a DataFrame of objects

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})

def test(ar):
    if ar == ['']:
        return False
    else:
        return True

df.applymap(test)

The applymap returns this:

I just need to take the columns and cells with True into a structure like the following:

d = {
    'x': [(0, [''])],
    'y': [(0, ['']), (1, ['']),]
    'z': [(0, ['']), (1, ['']),]
}

Which is the fastest method to achieve this? There has to be a simple way to solve it.

Body:
There's probably a smarter way to do this, but this gets the job done:

>>> df = pd.DataFrame({'x': [True, False], 'y': [True, True], 'z': [True, True]})
>>> df
       x     y     z
0   True  True  True
1  False  True  True

>>> d = {}

>>> for column in df.columns:
...:     d[column] = []
...:     for index, value in enumerate(column):
...:         if value == True:
...:             d[column].append((index, ['']))
...:
>>> d
{'x': [(0, [''])], 'y': [(0, ['']), (1, [''])], 'z': [(0, ['']), (1, [''])]}

Algorythm improved by the asker

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'q': [[''], ['']],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})

def test(ar):
    if ar == ['']:
        return False
    else:
        return True

new_df = df.applymap(test)
d = {}
for column in new_df.columns:
    s = new_df[column][new_df[column] == True]
    if s.size >= 1:
        d[column] = []
        for index, value in enumerate(s):
            if value == True:
                d[column].append((index, ['']))
d


问:
Let's Encrypt on Android gives java.security.cert.CertPathValidatorException: Trust anchor for certification path not found
Hi have setup a small serve, generated a free certificate from Let's encrypt and configured Nginx to use that certificate (fullchain.pem and privkey.pem)

However, when I attempt to make a call from my Android app (with OkHttp3)
I get this error

```<code>java.security.cert.CertPathValidatorException: Trust anchor for certification path not found
</code>```

Is Let's encrypt root certificate not trusted by the Android cert trust store? Or did I miss something when setting up nginx?
What is a work around for this If i still want to use Let's encrypt certificates?

答:
In let's encrypt user guide:

```<code>If you’re using OCSP stapling with Nginx >= 1.3.7, chain.pem should be provided as the ssl_trusted_certificate to validate OCSP responses.
</code>```

For others who are using Apache, check your apache version.
For one of my server I set up. I was using Apache < 2.4.8. In let's encrypt user guide:

```<code>cert.pem contains the server certificate by itself, and chain.pem contains the additional intermediate certificate...
Apache < 2.4.8 needs these for SSLCertificateFile and SSLCertificateChainFile, respectively.
</code>```

So, for SSLCertificateFile, use cert.pem;
for SSLCertificateChainFile use chain.pem.

I originally using fullchain.pem for SSLCertificateFile only. it worked for most browsers, and iOS. But Android complained about it with the above error.

Separately configuring the cert and chain in Apache, all platforms work well.

Body:
Hi have setup a small serve, generated a free certificate from Let's encrypt and configured Nginx to use that certificate (fullchain.pem and privkey.pem)

However, when I attempt to make a call from my Android app (with OkHttp3)
I get this error

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Is Let's encrypt root certificate not trusted by the Android cert trust store? Or did I miss something when setting up nginx?
What is a work around for this If i still want to use Let's encrypt certificates?

Body:
In let's encrypt user guide:

If you’re using OCSP stapling with Nginx >= 1.3.7, chain.pem should be provided as the ssl_trusted_certificate to validate OCSP responses.

For others who are using Apache, check your apache version.
For one of my server I set up. I was using Apache < 2.4.8. In let's encrypt user guide:

cert.pem contains the server certificate by itself, and chain.pem contains the additional intermediate certificate...
Apache < 2.4.8 needs these for SSLCertificateFile and SSLCertificateChainFile, respectively.

So, for SSLCertificateFile, use cert.pem;
for SSLCertificateChainFile use chain.pem.

I originally using fullchain.pem for SSLCertificateFile only. it worked for most browsers, and iOS. But Android complained about it with the above error.

Separately configuring the cert and chain in Apache, all platforms work well.


问:
How to make an if statement to disable select option?
I have three select menus where the user selects a subject, year and season. However, I want it so that if the user selects the year '2019', the 'Fall' option will get disabled.

<select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring">Spring</option>
    <option value="Fall">Fall</option>
</select>```

答:
```<code><select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year" id="years">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season" id="seasons">
    <option value="Spring">Spring</option>
    <option value="Fall">Fall</option>
</select>

$('#years').on('change', function(){
    if($(this).val()==='2019'){
        $("#seasons option").each(function()
        {
            if($(this).val() === 'Fall'){
                $(this).attr('disabled', 'disabled');
            }
        });
    }
});
</code>```


问:
required country combobox
In my project I hava one field that is country name.Till now I am inserting the country name on textfield. I want the combobox which already contain all the country name. Is there any combobox like that in java? </p>

答: If you are using swing then you have JComboBox. or in Webproject in html you have Select tag.</p>

Title: required country combobox


问:
How to paste in a new line with vim?
I often have to paste some stuff on a new line in vim. What I usually do is:

```<code>o<Esc>p
</code>```

Which inserts a new line and puts me in insertion mode, than quits insertion mode, and finally pastes.

Three keystrokes. Not very efficient. Any better ideas?

答:
Using this plugin: https://github.com/tpope/vim-unimpaired

]p pastes on the line below

[p pastes on the line above

advantages:

works on all yanked text (word, line, character, etc)

indents the pasted text to match the indentation of the text
around it

2 keystrokes instead of 3 and much "easier" strokes

fast

Title: How to paste in a new line with vim?

Body:
I often have to paste some stuff on a new line in vim. What I usually do is:

o<Esc>p

Which inserts a new line and puts me in insertion mode, than quits insertion mode, and finally pastes.

Three keystrokes. Not very efficient. Any better ideas?


问:
How to get Executor for main thread on API level < 28
On API level 28(Pie) a new method is introduced in the Context class to get Executor for the main thread getMainExecutor().

How to get this executor on API level below 28?

答:
You can use new HandlerExecutor(Looper.getMainLooper()); from com.google.android.gms.common.util.concurrent.HandlerExecutor...in the end it's the same answer as atarasenko.

I added an extension in Kotlin for that:

```<code>fun Context.mainExecutor(): Executor {
    return if (VERSION.SDK_INT >= VERSION_CODES.P) {
        mainExecutor
    } else {
        HandlerExecutor(mainLooper)
    }
}
</code>```

Body:
You can use new HandlerExecutor(Looper.getMainLooper()); from com.google.android.gms.common.util.concurrent.HandlerExecutor...in the end it's the same answer as atarasenko.

I added an extension in Kotlin for that:

fun Context.mainExecutor(): Executor {
    return if (VERSION.SDK_INT >= VERSION_CODES.P) {
        mainExecutor
    } else {
        HandlerExecutor(mainLooper)
    }
}


问:
Mongoose - How to get a value from an array of objects?
I implemented the following Scheme:

```<code>const UserSchema = new mongoose.Schema({
  statement: [
      {
        date: Date,
        description: String,
        amount: SchemaTypes.Double,
        balance: SchemaTypes.Double
      }
    ],
});
</code>```

I want to get the balance of the last statement array object. If I query this: const statement = await User.findById(req.params.id).select("statement"); it returns:

```<code>{
  "_id": "5cbb934d834d00a955a74081",
  "statement": [
    {
      "date": "2019-05-27T18:15:24.022Z",
      "description": "Account opening",
      "amount": 0,
      "balance": 0
    }
  ]
}
</code>```

However, if I console.log(statement.statement) I get the Mongoose object properties instead of the object stored in the array, so I can't do a statement.statement[-1]

How can I solve it?

Thanks in advance

答:
You should use toJSON method to get normal JSON object

https://mongoosejs.com/docs/guide.html#toJSON

Also you can't use -1 as an index to the array, to get the last element of an array you can do it like this

```<code>array.slice(-1)[0]
</code>```

this will return undefined in case of empty array

Body:
I implemented the following Scheme:

const UserSchema = new mongoose.Schema({
  statement: [
      {
        date: Date,
        description: String,
        amount: SchemaTypes.Double,
        balance: SchemaTypes.Double
      }
    ],
});

I want to get the balance of the last statement array object. If I query this: const statement = await User.findById(req.params.id).select("statement"); it returns:

{
  "_id": "5cbb934d834d00a955a74081",
  "statement": [
    {
      "date": "2019-05-27T18:15:24.022Z",
      "description": "Account opening",
      "amount": 0,
      "balance": 0
    }
  ]
}

However, if I console.log(statement.statement) I get the Mongoose object properties instead of the object stored in the array, so I can't do a statement.statement[-1]

How can I solve it?

Thanks in advance

Body:
You should use toJSON method to get normal JSON object

https://mongoosejs.com/docs/guide.html#toJSON

Also you can't use -1 as an index to the array, to get the last element of an array you can do it like this

array.slice(-1)[0]

this will return undefined in case of empty array