问:
generate resource URL within controller endpoint
I want to minimize my API response bodies by replacing information about subresource with a resource URL. So let's say you would fetch a vendor and don't want to list all the products he is selling but you want to provide a URL that leads to those information.

For example I tried this in my controller endpoint

```<code>string resourceUrl = Url.Link(nameof(GetVendorById), new { id = 1 });
</code>```

and was expecting to get the following string

```<code>https://localhost:5001/vendors/1
</code>```

Unfortunately the string returns null. So how do you generate such resource urls?

The following dummy code is just an example of what I want to achieve, I know I shouldn't return the vendor products when fetching a vendor.

```<code>[HttpGet("{id:int}")]
public async Task<ActionResult<VendorResponseModel>> GetVendorById([FromRoute] int id)
{
    VendorResponseModel vendor = new VendorResponseModel()
    {
        Id = id,
        Name = "Vendor " + id,
        Products = new List<VendorProductResponseModel>()
        {
            new VendorProductResponseModel()
            {
                Id = 1,
                ResourceUrl = Url.Link(nameof(ProductsController.GetProductById), new { id = 1 })
            }
        }
    };

    return Ok(vendor);
}
</code>```

答:
Url.Link does work for me when tagging the resource method with a Name attribute. So when calling Url.Link(nameof(GetVendorById), new { id = 1 }); I had to make sure that the GetVendorById method is named like so

```<code>[HttpGet("{id:int}", Name = "GetVendorById")]
public async Task<ActionResult<VendorResponseModel>> GetVendorById([FromRoute] int id)
{
    // ...
}
</code>```

Body:
I want to minimize my API response bodies by replacing information about subresource with a resource URL. So let's say you would fetch a vendor and don't want to list all the products he is selling but you want to provide a URL that leads to those information.

For example I tried this in my controller endpoint

string resourceUrl = Url.Link(nameof(GetVendorById), new { id = 1 });

and was expecting to get the following string

https://localhost:5001/vendors/1

Unfortunately the string returns null. So how do you generate such resource urls?

The following dummy code is just an example of what I want to achieve, I know I shouldn't return the vendor products when fetching a vendor.

[HttpGet("{id:int}")]
public async Task<ActionResult<VendorResponseModel>> GetVendorById([FromRoute] int id)
{
    VendorResponseModel vendor = new VendorResponseModel()
    {
        Id = id,
        Name = "Vendor " + id,
        Products = new List<VendorProductResponseModel>()
        {
            new VendorProductResponseModel()
            {
                Id = 1,
                ResourceUrl = Url.Link(nameof(ProductsController.GetProductById), new { id = 1 })
            }
        }
    };

    return Ok(vendor);
}

Body:
Url.Link does work for me when tagging the resource method with a Name attribute. So when calling Url.Link(nameof(GetVendorById), new { id = 1 }); I had to make sure that the GetVendorById method is named like so

[HttpGet("{id:int}", Name = "GetVendorById")]
public async Task<ActionResult<VendorResponseModel>> GetVendorById([FromRoute] int id)
{
    // ...
}


来源: stackexchange

问:
Problem with setting header "Content-Type" in uploading file with HttpClient4
I'm trying to a upload file (or multiple files) to my servlet, which is using Apache file-upload to handle and get post-ed files.

All is going well and the file is send and recieved, when I use the following code.

```<code>DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://myservice.com/servlet");

MultipartEntity entity2 = new MultipartEntity();
FileBody fileBody = new FileBody(new File("C:/docOut.pdf"));
entity2.addPart("file", fileBody);
post.setEntity(entity2);

HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
</code>```

But when I try to set my own "Content-Type" to recommended one (or the one only accepted with the Apache file-upload library) with uploading file:

```<code>post.addHeader("Content-Type", "multipart/form-data");
</code>```

My servlet doesn't get any of files and throws an exeption:

```<code>org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:931)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:349)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at com.myservice.server.filerep.action.FileUploadFormAction.execute(FileUploadFormAction.java:54)
at com.myservice.server.filerep.web.FileRepServlet.doGet(FileRepServlet.java:34)
at com.myservice.server.filerep.web.FileRepServlet.doPost(FileRepServlet.java:41)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
</code>```

I'm aware that POST requests with the uploading file shouldn't contain boundary "elements" in request to determine the order of uploaded byte chunks, but I thought HttpClient will add all the needed information to my request (similar as when I don't specify content-type).

My questions are:

Why did adding "Content-Type" break my request? Shouldn't HttpClient add boundary elements to content-type defined by me?

Should I explicity set "Content-Type" to my request or let the library handle it?

If I can set Content-Type explicity could you provide a code snippet?

If I can explicity set Content-Type why should I use and prefer "multipart/form-data" to "application/x-www-form-urlencoded" when it comes to POSTing to some forms?

PS: I found somehow related questions, but not addressing my problem:

ContentType issue with commons-upload and httpcomponent client

How can I See the content of a MultipartForm request?

答:
If you have form data enctype, you must follow the rules as specified in RFC 2388. Data in multipart message are treated as entity so each entity must have a header (with Content-Disposition, Content-Type, etc.) and a boundary.

As to answer question 1, the RFC states:

As with all multipart MIME types, each
part has an optional "Content-Type",
which defaults to text/plain.

For 2), As mentioned, every multipart message must have an header, so you have to specify your Content-Type (if you're not fully using HttpClient library features).

For 3) and 4) RFC states:

If multiple files are to be returned
as the result of a single form entry,
they should be represented as a
"multipart/mixed" part embedded within
the "multipart/form-data".

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to a upload file (or multiple files) to my servlet, which is using Apache file-upload to handle and get post-ed files.

All is going well and the file is send and recieved, when I use the following code.

DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://myservice.com/servlet");

MultipartEntity entity2 = new MultipartEntity();
FileBody fileBody = new FileBody(new File("C:/docOut.pdf"));
entity2.addPart("file", fileBody);
post.setEntity(entity2);

HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));

But when I try to set my own "Content-Type" to recommended one (or the one only accepted with the Apache file-upload library) with uploading file:

post.addHeader("Content-Type", "multipart/form-data");

My servlet doesn't get any of files and throws an exeption:

org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:931)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:349)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at com.myservice.server.filerep.action.FileUploadFormAction.execute(FileUploadFormAction.java:54)
at com.myservice.server.filerep.web.FileRepServlet.doGet(FileRepServlet.java:34)
at com.myservice.server.filerep.web.FileRepServlet.doPost(FileRepServlet.java:41)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)

I'm aware that POST requests with the uploading file shouldn't contain boundary "elements" in request to determine the order of uploaded byte chunks, but I thought HttpClient will add all the needed information to my request (similar as when I don't specify content-type).

My questions are:

Why did adding "Content-Type" break my request? Shouldn't HttpClient add boundary elements to content-type defined by me?

Should I explicity set "Content-Type" to my request or let the library handle it?

If I can set Content-Type explicity could you provide a code snippet?

If I can explicity set Content-Type why should I use and prefer "multipart/form-data" to "application/x-www-form-urlencoded" when it comes to POSTing to some forms?

PS: I found somehow related questions, but not addressing my problem:

ContentType issue with commons-upload and httpcomponent client

How can I See the content of a MultipartForm request?


问:
Show a specific component based on Dynamic Angular Routing path
My routes:

/dashboard

/dashboard/view-all

/dashboard/edit/:id

Basically, I have a table in the /dashboard/view-all and for each row, I have an Edit Button to take me to the /dashboard/edit/:id, and it works fine.

The Problem: I can't show/hide the EditComponent according to the Dynamic Router. I usually show/hide Angular Component based on Router using something like this:

<app-view-all *ngIf="route.url == '/dashboard/view-all'"></app-view-all>```
</div>
</div>
</p>

<p>For a dynamic router, when I am trying to write it like:</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><app-edit *ngIf="route.url == '/dashboard/edit/:id'"></app-edit></code>```

It doesn't work, but it works when I change it to something like: /dashboard/edit/26. I am new to Angular, and I didn't find such a duplicate question on SOF, maybe it's a very basic Angular question? :D

Thank You!!

答:
Your Route Config should be like

```<code>{
  path: 'dashboard',
  component: DashboardComponent,
},
{
  path: 'dashboard/:section',
  component: DashBoardComponent
},
{
  path: 'dashboard/:section/:id',
  component: DashBoardComponent
}
</code>```

In Dashboard.component.ts

```<code>public isEditing = false;
public editId;
constructor(private route: ActivatedRoute){}

ngOnInit() {
   this.route.params.subscribe((param) => {
       isEditing = param.section==='edit';
       editId = param.id;
   });
}
</code>```

In dashboard.component.html

```<code><app-view-all *ngIf="!isEditing"></app-view-all>

<app-edit *ngIf="isEditing"></app-edit>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My routes:

/dashboard

/dashboard/view-all

/dashboard/edit/:id

Basically, I have a table in the /dashboard/view-all and for each row, I have an Edit Button to take me to the /dashboard/edit/:id, and it works fine.

The Problem: I can't show/hide the EditComponent according to the Dynamic Router. I usually show/hide Angular Component based on Router using something like this:

<app-view-all *ngIf="route.url == '/dashboard/view-all'"></app-view-all>

For a dynamic router, when I am trying to write it like:

<app-edit *ngIf="route.url == '/dashboard/edit/:id'"></app-edit>

It doesn't work, but it works when I change it to something like: /dashboard/edit/26. I am new to Angular, and I didn't find such a duplicate question on SOF, maybe it's a very basic Angular question? :D

Thank You!!

Body:
Your Route Config should be like

{
  path: 'dashboard',
  component: DashboardComponent,
},
{
  path: 'dashboard/:section',
  component: DashBoardComponent
},
{
  path: 'dashboard/:section/:id',
  component: DashBoardComponent
}

In Dashboard.component.ts

public isEditing = false;
public editId;
constructor(private route: ActivatedRoute){}

ngOnInit() {
   this.route.params.subscribe((param) => {
       isEditing = param.section==='edit';
       editId = param.id;
   });
}

In dashboard.component.html

<app-view-all *ngIf="!isEditing"></app-view-all>

<app-edit *ngIf="isEditing"></app-edit>


问:
Add the values of two tables based on a combination of columns
I have two tables:

```<code>df1 = pd.DataFrame({
    "c_id": [2000,3000,3000],
    "cloud":["GCP","GCP","Azure"],
    "invoice":[100,100,300]
})

c_id    cloud   invoice
2000    GCP     100
3000    GCP     100
3000    Azure   300

df2 = pd.DataFrame({
    "c_id": [1000,2000,2000,3000,3000],
    "cloud":["Azure","GCP","Azure","AWS","Azure"],
    "invoice":[200,200,300,100,100]
})

c_id    cloud   invoice
1000    Azure   200
2000    GCP     200
2000    Azure   300
3000    AWS     100
3000    Azure   100
</code>```

I want to add the two tables based on the combination of columns c_id and cloud. The result I'm looking for is:

```<code>c_id    cloud   invoice
1000    Azure   200
2000    Azure   300
2000    GCP     300
3000    AWS     100
3000    Azure   400
3000    GCP     100
</code>```

In my example, I only displayed the column invoice. In my actual dataset, there are actually more than 40 columns with a lot more constraints. Several of the columns only have value when the cloud is Azure, while others only have value when the cloud is either Azure or GCP

Is there's a clean way to add df1 and df2?

Body:
I have two tables:

df1 = pd.DataFrame({
    "c_id": [2000,3000,3000],
    "cloud":["GCP","GCP","Azure"],
    "invoice":[100,100,300]
})

c_id    cloud   invoice
2000    GCP     100
3000    GCP     100
3000    Azure   300

df2 = pd.DataFrame({
    "c_id": [1000,2000,2000,3000,3000],
    "cloud":["Azure","GCP","Azure","AWS","Azure"],
    "invoice":[200,200,300,100,100]
})

c_id    cloud   invoice
1000    Azure   200
2000    GCP     200
2000    Azure   300
3000    AWS     100
3000    Azure   100

I want to add the two tables based on the combination of columns c_id and cloud. The result I'm looking for is:

c_id    cloud   invoice
1000    Azure   200
2000    Azure   300
2000    GCP     300
3000    AWS     100
3000    Azure   400
3000    GCP     100

In my example, I only displayed the column invoice. In my actual dataset, there are actually more than 40 columns with a lot more constraints. Several of the columns only have value when the cloud is Azure, while others only have value when the cloud is either Azure or GCP

Is there's a clean way to add df1 and df2?

Body:
Use concat with aggregate sum:

df1 = pd.DataFrame({
    "c_id": [2000,3000,3000],
    "cloud":["GCP","GCP","Azure"],
    "invoice":[100,100,300]
})
print (df1)
   c_id  cloud  invoice
0  2000    GCP      100
1  3000    GCP      100
2  3000  Azure      300

df2 = pd.DataFrame({
    "c_id": [1000,2000,2000,3000,3000],
    "cloud":["Azure","GCP","Azure","AWS","Azure"],
    "invoice":[200,200,300,100,100]
})
print (df2)
   c_id  cloud  invoice
0  1000  Azure      200
1  2000    GCP      200
2  2000  Azure      300
3  3000    AWS      100
4  3000  Azure      100

df = pd.concat([df1, df2]).groupby(['c_id','cloud'], as_index=False).sum()
print (df)
   c_id  cloud  invoice
0  1000  Azure      200
1  2000  Azure      300
2  2000    GCP      300
3  3000    AWS      100
4  3000  Azure      400
5  3000    GCP      100


问:
Can't fetch XML response in PHP
This is my code to fetch api

```<code> $apiurl = "https://class.cvcngr.in/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-1495797&moderatorPW=mp&name=random-1495797&record=false&voiceBridge=74999&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=ad1f82091f78ee18673f9c5be36df9eef7860187";

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $apiurl);
  $response = curl_exec($ch);
  curl_close($ch);
  $xml = simplexml_load_string($response);
  echo $xml;
</code>```

In the above, I have used an apiurl which stores URL of API. this is my custom API and there is a test API provided by the service provider

```<code>$apiurl2 "http://test-install.blindsidenetworks.com/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-9370670&moderatorPW=mp&name=random-9370670&record=false&voiceBridge=79891&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=0aae50d2d079fd67138a7b266837f6b0112166b5";
</code>```

Bothe the URL gives the same response but I can get data only when I use apiurl2. when I use the first one there is no response. but when I use in the browser directly there is no issues

答:
It works just fine, the $xml variable is a SimpleXMLElement instance. echo tries to print a string. You can print all of its contents with var_dump($xml) and access its elements directly with an object operator: echo $xml->dialNumber and even loop thru them:

```<code><?php

  $apiurl = "https://class.cvcngr.in/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-1495797&moderatorPW=mp&name=random-1495797&record=false&voiceBridge=74999&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=ad1f82091f78ee18673f9c5be36df9eef7860187";

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $apiurl);

  $response = curl_exec($ch);
  $xml      = simplexml_load_string($response);

  // var_dump($xml);
  // echo 'Dial number: ' . $xml->dialNumber;

  foreach ($xml as $key => $value) {
      echo "{$key}: {$value}\n";
  }

  curl_close($ch);
</code>```

Title: Can't fetch XML response in PHP

Body:
This is my code to fetch api

 $apiurl = "https://class.cvcngr.in/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-1495797&moderatorPW=mp&name=random-1495797&record=false&voiceBridge=74999&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=ad1f82091f78ee18673f9c5be36df9eef7860187";

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $apiurl);
  $response = curl_exec($ch);
  curl_close($ch);
  $xml = simplexml_load_string($response);
  echo $xml;

In the above, I have used an apiurl which stores URL of API. this is my custom API and there is a test API provided by the service provider

$apiurl2 "http://test-install.blindsidenetworks.com/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-9370670&moderatorPW=mp&name=random-9370670&record=false&voiceBridge=79891&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=0aae50d2d079fd67138a7b266837f6b0112166b5";

Bothe the URL gives the same response but I can get data only when I use apiurl2. when I use the first one there is no response. but when I use in the browser directly there is no issues

Body:
It works just fine, the $xml variable is a SimpleXMLElement instance. echo tries to print a string. You can print all of its contents with var_dump($xml) and access its elements directly with an object operator: echo $xml->dialNumber and even loop thru them:

<?php

  $apiurl = "https://class.cvcngr.in/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-1495797&moderatorPW=mp&name=random-1495797&record=false&voiceBridge=74999&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=ad1f82091f78ee18673f9c5be36df9eef7860187";

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $apiurl);

  $response = curl_exec($ch);
  $xml      = simplexml_load_string($response);

  // var_dump($xml);
  // echo 'Dial number: ' . $xml->dialNumber;

  foreach ($xml as $key => $value) {
      echo "{$key}: {$value}\n";
  }

  curl_close($ch);


问:
Contenteditable DIV is not working properly with angular two way binding in firefox
I have made my div contenteditable div and it also opens ngx-popover on keyup and populate search results into popover on basis of searchText so I need two way binding as well as content editable further I need div rather than input:

```<code><span>
   <div id="contenteditablediv" contenteditable="true" (keyup)="triggerUserSearch()" type="text" [popover]="searchTemplate"
        placement="bottom"  triggers="keyup click" [textContent]="searchText" (input)="searchText=$event.target.textContent" [outsideClick]="true"
        containerClass="searchUsersPopup" placeholder="To" class="recipientInput searchTerm">{{searchText}}
   </div>
</span>
</code>```

But when I add below line of code:

```<code>(input)="searchText=$event.target.textContent"
</code>```

It does not work correctly in firefox browser. It types backward in firefox when you place cursor at end.

I took reference from below Plunker which is also not working correctly in firefox.

Also happens same for
SO Answer and
Plunker

I am not sure what (input)="searchText=$event.target.textContent" code exactly does. But it bind searchText and div value.
So it is required but it is also causing issue.
Please  explain meaning of above code if possible. Thanks!

答:
In .html:

```<code><div (blur)="getContent($event.target.innerHTML)" contenteditable [innerHTML]="content"></div>
</code>```

In .ts:

```<code>getContent(innerText){
  this.content = innerText;
}
</code>```

Body:
I have made my div contenteditable div and it also opens ngx-popover on keyup and populate search results into popover on basis of searchText so I need two way binding as well as content editable further I need div rather than input:

{{searchText}}

But when I add below line of code:

(input)="searchText=$event.target.textContent"

It does not work correctly in firefox browser. It types backward in firefox when you place cursor at end.

I took reference from below Plunker which is also not working correctly in firefox.

Also happens same for
SO Answer and
Plunker

I am not sure what (input)="searchText=$event.target.textContent" code exactly does. But it bind searchText and div value.
So it is required but it is also causing issue.
Please  explain meaning of above code if possible. Thanks!

Body:
In .html:

<div (blur)="getContent($event.target.innerHTML)" contenteditable [innerHTML]="content"></div>

In .ts:

getContent(innerText){
  this.content = innerText;
}


问:
Custom page show blog posts on tag
Since I am not so great programming in PHP I wanted to ask my question here, hopefully you guys can help me out.

I'm building a WordPress website, this website has a custom page template like custom-single.php.

On that custom template I want to show posts filtered on a tag. And the tag is coming from a Angular value like so {{ctrl.name.tagname}} and yes ofcourse I've made a tag as well in WordPress.

The code must show max 5 posts (fully with title and ofcourse the content), after the posts it must show max 5 items which are older then 5 posts before, but then only with title using a bullet-list.

答:
https://tr.wordpress.org/plugins/display-posts-shortcode/

When you install and activate this plugin called Display Posts Shortcode, you will add the feature that enables you to create text lists.

If we want to list our articles about a label, we can use a shortcode like [display-posts tag = ”tag_name”].

Number of posts to be displayed on one page (eg 20): posts_per_page = ”20 ″

I hope it will be the answer

Title: Custom page show blog posts on tag


问:
Can we configure the Eclipse TFS plugin to require a work item on check in?
When we check in a file, we would like to have the plugin not allow check-in unless a work order(s) has been specified. I've looked for that before but haven't found a way. I'm looking in Preferences > Team > Team Foundation Server and don't see anything there.</p>

答:
It's supposed you are using Team Explorer Everywhere. What you are looking for is check-in policy. You need to add Work Item Policy if you want to require that one or more work items is associated with each changeset.

Check following link for more details:

https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/gg475890(v=vs.100)


问:
EventHandle in ReactJS for a particular element in a list
I have component, where I make an API call and I get a response as an array of objects. Then I'm mapping through it and printing the data as rows and columns as follow:

```<code>{
  this.state.listUser.map((list, index) => {
    return (
      <tbody key={index}>
        <tr>
          <th>{list.first_name}</th>
          <th>{list.last_name}</th>
          <th>
            <img id={index} src={list.avatar} onClick={this.showEmailAddress} />
          </th>
          {this.state.showEmail && <th>{list.email}</th>}
        </tr>
      </tbody>
    );
  });
}
</code>```

And onClicking the Img tag, I wanted to show the email address of that particular user. I'm not able to find how to do it for that particular item in the list. Now it show the email for all the items of the list. I want to write a showEmailAddress handler which will show the email for that particular item instead of all. Thanks in advance.

Here's my component:

```<code>import React from "react";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      listUser: "",
      showEmail: "",
    };
  }

  showEmailAddress(email) {
    this.setState({ showEmail: email });
  }

  componentDidMount() {
    axios
      .get("https://reqres.in/api/users?page=2")
      .then((res) => {
        console.log(res.data.data);
        this.setState({ listUser: res.data.data });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    if (!this.state.listUser) {
      return <div>...loading</div>;
    }

    return (
      <div>
        <thead>
          <tr>
            <th>first_name</th>
            <th>last_name</th>
            <th>avatar</th>
          </tr>
        </thead>
        {this.state.listUser.map((list, index) => {
          return (
            <tbody key={index}>
              <tr>
                <th>{list.first_name}</th>
                <th>{list.last_name}</th>
                <th>
                  <img
                    alt="test"
                    id={index}
                    src={list.avatar}
                    onClick={this.showEmailAddress.bind(this, list.email)}
                  />
                </th>
                <th>{this.state.showEmail}</th>
              </tr>
            </tbody>
          );
        })}
      </div>
    );
  }
}

export default App;
</code>```

答:
You need to just manage state in onclick of image then you can able to toggle your

Please have a look I hope it works for you.

Thanks

```<code>{this.state.listUser.map((list, index) => {
      return (
        <tbody key={index}>
          <tr>
            <th>{list.first_name}</th>
            <th>{list.last_name}</th>
            <th><img id={index} src={list.avatar} onClick={this.setState({showEmail:!this.state.showEmail})}/></th>
            {this.state.showEmail &&
            <th>{list.email}</th>
            }
          </tr>
        </tbody>
      );
    })}
</code>```

Body:
I have component, where I make an API call and I get a response as an array of objects. Then I'm mapping through it and printing the data as rows and columns as follow:

{
  this.state.listUser.map((list, index) => {
    return (

          {list.first_name}
          {list.last_name}

          {this.state.showEmail && {list.email}	}

    );
  });
}

And onClicking the Img tag, I wanted to show the email address of that particular user. I'm not able to find how to do it for that particular item in the list. Now it show the email for all the items of the list. I want to write a showEmailAddress handler which will show the email for that particular item instead of all. Thanks in advance.

Here's my component:

import React from "react";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      listUser: "",
      showEmail: "",
    };
  }

  showEmailAddress(email) {
    this.setState({ showEmail: email });
  }

  componentDidMount() {
    axios
      .get("https://reqres.in/api/users?page=2")
      .then((res) => {
        console.log(res.data.data);
        this.setState({ listUser: res.data.data });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    if (!this.state.listUser) {
      return
...loading
;
    }

    return (

            first_name
            last_name
            avatar

        {this.state.listUser.map((list, index) => {
          return (

                {list.first_name}
                {list.last_name}

                {this.state.showEmail}

          );
        })}

    );
  }
}

export default App;

Body:
You need to just manage state in onclick of image then you can able to toggle your <th>

Please have a look I hope it works for you.

Thanks

{this.state.listUser.map((list, index) => {
      return (
        <tbody key={index}>
          <tr>
            <th>{list.first_name}</th>
            <th>{list.last_name}</th>
            <th><img id={index} src={list.avatar} onClick={this.setState({showEmail:!this.state.showEmail})}/></th>
            {this.state.showEmail &&
            <th>{list.email}</th>
            }
          </tr>
        </tbody>
      );
    })}


问:
How to stop password field from showing 'null' as a placeholder?
I have a password field which is interactive and has some js going on behind the scenes. However I have this issue of when I click on the field, it shows 'null' as a value, as per the image.

This only shows when I click on the field, and I have no placeholder given to the input either. How do I prevent this from showing?

The code

//floating input controller

const FloatLabel = (() => {

  // add active class
  const handleFocus = (e) => {
    const target = e.target;
    target.parentNode.classList.add('active');
    target.setAttribute('placeholder', target.getAttribute('data-placeholder'));
  };

  // remove active class
  const handleBlur = (e) => {
    const target = e.target;
    if (!target.value) {
      target.parentNode.classList.remove('active');
    }
    target.removeAttribute('placeholder');
  };

  // register events
  const bindEvents = (element) => {
    const floatField = element.querySelector('input');
    floatField.addEventListener('focus', handleFocus);
    floatField.addEventListener('blur', handleBlur);
  };

  // get DOM elements
  const init = () => {
    const floatContainers = document.querySelectorAll('.float-container');

    floatContainers.forEach((element) => {

      if (element.querySelector('input').value) {
        element.classList.add('active');
      }

      bindEvents(element);
    });
  };

  return {
    init: init
  };
})();

FloatLabel.init();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.float-container {
  position: relative;
  background-color: #dfecff;
  width: 100%;
  border-radius: 5px;
  transition: 150ms;
  padding-top: .6em;
  padding-bottom: .6em;
  border: 2px solid #b9d6ff;
}

.float-container:hover {
  background-color: #1a73e8;
  cursor: text;
}

.password-toggle-button {
  position: absolute;
  font-size: 1em;
  padding-top: 8px;
  color: #333333;
  margin-left: 93%;
}

.password-toggle-button:hover {
  cursor: pointer;
  color: #eeeeee;
}

label {
  font-size: 1em;
  font-family: Arial, Helvetica, sans-serif;
  color: #5e5e5e;
  position: absolute;
  margin-left: 3%;
  z-index: 140;
  transform: translate(0, 0) scale(1);
  pointer-events: none;
  user-select: none;
  transform-origin: top left;
  transition: all .1s ease-in-out;
}

.float-container input {
  color: #eeeeee;
}

.float-container.active label {
  transform: translate(-0.5em, -1.5em) scale(.95);
  font-style: italic;
  font-weight: 200;
  border-radius: 10px;
  background-color: #1a73e8;
  padding-left: .5em;
  padding-right: .5em;
  color: #eeeeee;
}

.float-container.active input {
  color: #eeeeee;
}

.float-container.active {
  background-color: #1a73e8;
  border: 2px solid #eeeeee;
}

.form-center {
  display: relative;
  margin-top: 3em;
  margin-left: 5vw;
  margin-bottom: 5em;
  word-break: break-all;
  padding-top: 3%;
  padding-left: 5vw;
  padding-right: 3vw;
  padding-bottom: 5%;
  width: 60vw;
  line-height: 2em;
  background-color: #1a73e8;
  border-radius: 20px;
  border-width: 3px;
  border-style: solid;
  border-color: #333333;
}

input{
  border: none;
  background-color: transparent;
  color: #333333;
  outline: 0;
  margin-top: auto;
  margin-left: 3%;
  margin-right: 20%;
  width: 90%;
  z-index: 150;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

  Password

  <input type="password" class="floatField id="pw" placeholder="">

```

答:
```<code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

<div class="form-center"><div id="float-container" class="float-container" onclick="document.getElementById('pw').focus(); return false;">
  <label for="pw" class="inner-label">Password</label>
  <i class="fa fa-eye password-toggle-button" aria-hidden="true"></i>
  <input type="password" class="floatField id="pw">
</div>
</div>
</code>```

Have you tried removing the placeholder?

Body:
I have a password field which is interactive and has some js going on behind the scenes. However I have this issue of when I click on the field, it shows 'null' as a value, as per the image.

This only shows when I click on the field, and I have no placeholder given to the input either. How do I prevent this from showing?

The code

//floating input controller

const FloatLabel = (() => {

  // add active class
  const handleFocus = (e) => {
    const target = e.target;
    target.parentNode.classList.add('active');
    target.setAttribute('placeholder', target.getAttribute('data-placeholder'));
  };

  // remove active class
  const handleBlur = (e) => {
    const target = e.target;
    if (!target.value) {
      target.parentNode.classList.remove('active');
    }
    target.removeAttribute('placeholder');
  };

  // register events
  const bindEvents = (element) => {
    const floatField = element.querySelector('input');
    floatField.addEventListener('focus', handleFocus);
    floatField.addEventListener('blur', handleBlur);
  };

  // get DOM elements
  const init = () => {
    const floatContainers = document.querySelectorAll('.float-container');

    floatContainers.forEach((element) => {

      if (element.querySelector('input').value) {
        element.classList.add('active');
      }

      bindEvents(element);
    });
  };

  return {
    init: init
  };
})();

FloatLabel.init();

.float-container {
  position: relative;
  background-color: #dfecff;
  width: 100%;
  border-radius: 5px;
  transition: 150ms;
  padding-top: .6em;
  padding-bottom: .6em;
  border: 2px solid #b9d6ff;
}

.float-container:hover {
  background-color: #1a73e8;
  cursor: text;
}

.password-toggle-button {
  position: absolute;
  font-size: 1em;
  padding-top: 8px;
  color: #333333;
  margin-left: 93%;
}

.password-toggle-button:hover {
  cursor: pointer;
  color: #eeeeee;
}

label {
  font-size: 1em;
  font-family: Arial, Helvetica, sans-serif;
  color: #5e5e5e;
  position: absolute;
  margin-left: 3%;
  z-index: 140;
  transform: translate(0, 0) scale(1);
  pointer-events: none;
  user-select: none;
  transform-origin: top left;
  transition: all .1s ease-in-out;
}

.float-container input {
  color: #eeeeee;
}

.float-container.active label {
  transform: translate(-0.5em, -1.5em) scale(.95);
  font-style: italic;
  font-weight: 200;
  border-radius: 10px;
  background-color: #1a73e8;
  padding-left: .5em;
  padding-right: .5em;
  color: #eeeeee;
}

.float-container.active input {
  color: #eeeeee;
}

.float-container.active {
  background-color: #1a73e8;
  border: 2px solid #eeeeee;
}

.form-center {
  display: relative;
  margin-top: 3em;
  margin-left: 5vw;
  margin-bottom: 5em;
  word-break: break-all;
  padding-top: 3%;
  padding-left: 5vw;
  padding-right: 3vw;
  padding-bottom: 5%;
  width: 60vw;
  line-height: 2em;
  background-color: #1a73e8;
  border-radius: 20px;
  border-width: 3px;
  border-style: solid;
  border-color: #333333;
}

input{
  border: none;
  background-color: transparent;
  color: #333333;
  outline: 0;
  margin-top: auto;
  margin-left: 3%;
  margin-right: 20%;
  width: 90%;
  z-index: 150;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

  Password

  <input type="password" class="floatField id="pw" placeholder="">

Body:
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

<div class="form-center"><div id="float-container" class="float-container" onclick="document.getElementById('pw').focus(); return false;">
  <label for="pw" class="inner-label">Password</label>
  <i class="fa fa-eye password-toggle-button" aria-hidden="true"></i>
  <input type="password" class="floatField id="pw">
</div>
</div>

Have you tried removing the placeholder?


问:
can not connect Azure SQL with Azure AD user in Azure
I have a powershell script used to query Azure SQL database with Azure AD user. I can run the poweshell script on my local machine. But when I host the powershell script on Azure function, I always get the error : keyword not supported: 'authentication'

My script

```<code>$Username = “”
$Password = “”
$Port = 1433

$cxnString = "Server=tcp:$serverName,$Port;Database=$databaseName;UID=$UserName;PWD=$Password;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;Authentication=Active Directory Password"

$query = ''

Invoke-Sqlcmd -ConnectionString $cxnString - Query $query
</code>```

答:
According to my test, now we can not implement it with PowerShell in Azure Function. Now we can implement it with .Net Core Function. We need to package Microsoft.Data.SqlClient

For example

```<code> SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            string userName = "<>";
            string password = "<>";
            string server = "<>.database.windows.net";
            string database = "test";
            builder.ConnectionString = "Server=tcp:" + server + ",1433;Initial Catalog=" + database + ";Authentication=Active Directory Password;User ID=" + userName + ";Password=" + password + ";MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;";

            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                connection.Open();
                string sql = "SELECT * FROM StarWars";
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            log.LogInformation(reader.GetString(2));
                        }
                    }
                }
            }
</code>```

Body:
I have a powershell script used to query Azure SQL database with Azure AD user. I can run the poweshell script on my local machine. But when I host the powershell script on Azure function, I always get the error : keyword not supported: 'authentication'

My script

$Username = “”
$Password = “”
$Port = 1433

$cxnString = "Server=tcp:$serverName,$Port;Database=$databaseName;UID=$UserName;PWD=$Password;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;Authentication=Active Directory Password"

$query = ''

Invoke-Sqlcmd -ConnectionString $cxnString - Query $query

Body:
According to my test, now we can not implement it with PowerShell in Azure Function. Now we can implement it with .Net Core Function. We need to package Microsoft.Data.SqlClient

For example

 SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            string userName = "<>";
            string password = "<>";
            string server = "<>.database.windows.net";
            string database = "test";
            builder.ConnectionString = "Server=tcp:" + server + ",1433;Initial Catalog=" + database + ";Authentication=Active Directory Password;User ID=" + userName + ";Password=" + password + ";MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;";

            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                connection.Open();
                string sql = "SELECT * FROM StarWars";
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            log.LogInformation(reader.GetString(2));
                        }
                    }
                }
            }


问:
Create a boolean array comparing each matrix in a Numpy tensor to a different integer in a Numpy Array
Say I have a Numpy tensor X that is 3*3*3 (actual dimensions would vary).  I want to test each matrix in the tensor against a different value in a set of integers.

For example if

```<code>X=np.array([1,2,3]*9).reshape(3,3,3)
test=np.array([1,2,3])
</code>```

The desired output would be:

```<code> [[[ True, False, False],
    [True, False, False],
    [True, False, False]],

   [[False,  True, False],
    [False,  True, False],
    [False,  True, False]],

   [[False, False,  True],
    [False, False,  True],
    [False, False,  True]]])
</code>```

However I can't seem to get this result.
X==test returns:

```<code>array([[[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]]])
</code>```

If

```<code>test=[[1],[2],[3]]
</code>```

I get:

```<code>array([[[ True, False, False],
        [False,  True, False],
        [False, False,  True]],

       [[ True, False, False],
        [False,  True, False],
        [False, False,  True]],

       [[ True, False, False],
        [False,  True, False],
        [False, False,  True]]])
</code>```

The same result holds true for np.equal. Is there any direct way to do this without using any loops? It seems like there would be a way given that with indexing

```<code>X[[0,1,2],[0,2,1]]
</code>```

would yield

```<code>np.array([X[0][0],X[1][2],X[2][1]])
</code>```

rather than

```<code>X[:,[0,2,1]]
</code>```

答:
This is a simple equality comparison, but the tricky part is figuring out how to broadcast the operation. You can do this as,

```<code>X == test[:, None, None]

array([[[ True, False, False],
        [ True, False, False],
        [ True, False, False]],

       [[False,  True, False],
        [False,  True, False],
        [False,  True, False]],

       [[False, False,  True],
        [False, False,  True],
        [False, False,  True]]])
</code>```

Where,

```<code>test[:, None, None]

array([[[1]],

       [[2]],

       [[3]]])
</code>```

The idea is to make the dimensions of X and test match, that way we can broadcast the equality comparison so first item of test is compared with the first sub-matrix of X, second item compared with the second sub-matrix, and so on.

Body:
Say I have a Numpy tensor X that is 3*3*3 (actual dimensions would vary).  I want to test each matrix in the tensor against a different value in a set of integers.

For example if

X=np.array([1,2,3]*9).reshape(3,3,3)
test=np.array([1,2,3])

The desired output would be:

 [[[ True, False, False],
    [True, False, False],
    [True, False, False]],

   [[False,  True, False],
    [False,  True, False],
    [False,  True, False]],

   [[False, False,  True],
    [False, False,  True],
    [False, False,  True]]])

However I can't seem to get this result.
X==test returns:

array([[[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]]])

If

test=[[1],[2],[3]]

I get:

array([[[ True, False, False],
        [False,  True, False],
        [False, False,  True]],

       [[ True, False, False],
        [False,  True, False],
        [False, False,  True]],

       [[ True, False, False],
        [False,  True, False],
        [False, False,  True]]])

The same result holds true for np.equal. Is there any direct way to do this without using any loops? It seems like there would be a way given that with indexing

X[[0,1,2],[0,2,1]]

would yield

np.array([X[0][0],X[1][2],X[2][1]])

rather than

X[:,[0,2,1]]

Body:
This is a simple equality comparison, but the tricky part is figuring out how to broadcast the operation. You can do this as,

X == test[:, None, None]

array([[[ True, False, False],
        [ True, False, False],
        [ True, False, False]],

       [[False,  True, False],
        [False,  True, False],
        [False,  True, False]],

       [[False, False,  True],
        [False, False,  True],
        [False, False,  True]]])

Where,

test[:, None, None]

array([[[1]],

       [[2]],

       [[3]]])

The idea is to make the dimensions of X and test match, that way we can broadcast the equality comparison so first item of test is compared with the first sub-matrix of X, second item compared with the second sub-matrix, and so on.


问:
How to update onlineMeeting - Graph API Microsoft teams meeting?
I am trying to insert a teams meeting link into our emails that are sent out. I want to call the api to generate a teams meeting link, WHICH I can do. However, how do I update this meeting if the time needs to be changed or if new participants are added? I can't find anything on the Microsoft Graph API documentation.

https://learn.microsoft.com/en-us/graph/api/application-post-onlinemeetings?view=graph-rest-1.0&tabs=http

Only see get,create,delete options

答: Currently only create meeting event is exposed by Graph API.</p>


问:
How to querySelectorAll elements added to the DOM with javascript?
I am developing a chat app, and my issue raises when I try to add new elements to a list of chat rooms, see them, and interact with them without reloading the page.

I am adding HTML elements to a list with JavaScript.

Then I try to querySelectorAll elements in the list.

The elements that were loaded from the server on page load can be selected.

But the newly created elements with JavaScript don't seem to get selected.

Here is how I try to select my elements and, when clicked, execute some code for each of them:

```<code> document.querySelectorAll('.select-room').forEach(p => {
        p.onclick = () => { <my code here> })
</code>```

The elements that are already on the list get selected just fine and my code executes alright.

But when I add a new element with JavaScript. Even though the HTML of it looks just the same as the HTML of other existing elements, including the class by which it gets selected, the result is I can only select those after reloading the page.

Is there a way I can listen for changes made to the DOM, so that after adding with JavaScript new elements with the same class, they will be selected like the others without having to reload the page?

Here is a Minimal, Complete, Reproducible Example of my problem:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>mcr problem</title>
    <script>
      document.addEventListener("DOMContentLoaded", () => {
        // Clicking element in the list shows an alert.
        document.querySelectorAll(".clickable").forEach(li => {
          li.onclick = () => {alert("interaction!")};
        });

        // Clicking on button adds new element to the list
        document.querySelector("#add-btn").onclick = () => {
          newLi = document.createElement("li");
          newLi.classList.add("clickable");
          newLi.innerHTML = "New Item";
          document.querySelector("#parent-list").append(newLi);
        };
      });
    </script>
  </head>
  <body>
    <h1>List of items</h1>
    <button id="add-btn">Add</button>
    <ul id="parent-list">
      <li class="clickable" id="post-1">Item 1</li>
      <li class="clickable" id="post-2">Item 2</li>
      <li class="clickable" id="post-3">Item 3</li>
    </ul>
  </body>
</html>
</code>```

答:
Reasons why alert was not getting called DOMContentLoaded

This event triggers when the DOM tree forms i.e. the script is loading. Scripts start to run before all the resources like images, CSS, and JavaScript loads. You can attach this event either to the window or the document objects

 and at that time the query selector has only 3 node of class .clickable so it apply only on those 3 elements.

In javascript DOMNodeInserted

It fires when the script inserts a new node in the DOM tree using appendChild(), replaceChild(), insertBefore(), etc.

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll(".clickable").forEach((li) => {
    li.onclick = () => commonAlertMethod();
  });
  // Clicking on button adds new elemnt to the list
  document.querySelector("#add-btn").onclick = () => {
    newLi = document.createElement("li");
    newLi.classList.add("clickable");
    newLi.innerHTML = "New Item";
    document.querySelector("#parent-list").append(newLi);
  };
});

document.addEventListener("DOMNodeInserted", () => {
  // Clicking element in the list shows an alert.
  document.querySelectorAll(".clickable").forEach((li) => {
    li.onclick = () => commonAlertMethod();
  });
});

function commonAlertMethod() {
  alert("interaction!");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>List of items</h1>
    <button id="add-btn">Add</button>
    <ul id="parent-list">
      <li class="clickable" id="post-1">Item 1</li>
      <li class="clickable" id="post-2">Item 2</li>
      <li class="clickable" id="post-3">Item 3</li>
    </ul>
</body>
</html></code>```

Body:
I am developing a chat app, and my issue raises when I try to add new elements to a list of chat rooms, see them, and interact with them without reloading the page.

I am adding HTML elements to a list with JavaScript.

Then I try to querySelectorAll elements in the list.

The elements that were loaded from the server on page load can be selected.

But the newly created elements with JavaScript don't seem to get selected.

Here is how I try to select my elements and, when clicked, execute some code for each of them:

 document.querySelectorAll('.select-room').forEach(p => {
        p.onclick = () => { <my code here> })

The elements that are already on the list get selected just fine and my code executes alright.

But when I add a new element with JavaScript. Even though the HTML of it looks just the same as the HTML of other existing elements, including the class by which it gets selected, the result is I can only select those after reloading the page.

Is there a way I can listen for changes made to the DOM, so that after adding with JavaScript new elements with the same class, they will be selected like the others without having to reload the page?

Here is a Minimal, Complete, Reproducible Example of my problem:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>mcr problem</title>

List of items

    <button id="add-btn">Add</button>

Item 1

Item 2

Item 3

Body:
Reasons why alert was not getting called DOMContentLoaded

This event triggers when the DOM tree forms i.e. the script is loading. Scripts start to run before all the resources like images, CSS, and JavaScript loads. You can attach this event either to the window or the document objects

 and at that time the query selector has only 3 node of class .clickable so it apply only on those 3 elements.

In javascript DOMNodeInserted

It fires when the script inserts a new node in the DOM tree using appendChild(), replaceChild(), insertBefore(), etc.

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll(".clickable").forEach((li) => {
    li.onclick = () => commonAlertMethod();
  });
  // Clicking on button adds new elemnt to the list
  document.querySelector("#add-btn").onclick = () => {
    newLi = document.createElement("li");
    newLi.classList.add("clickable");
    newLi.innerHTML = "New Item";
    document.querySelector("#parent-list").append(newLi);
  };
});

document.addEventListener("DOMNodeInserted", () => {
  // Clicking element in the list shows an alert.
  document.querySelectorAll(".clickable").forEach((li) => {
    li.onclick = () => commonAlertMethod();
  });
});

function commonAlertMethod() {
  alert("interaction!");
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>List of items</h1>
    <button id="add-btn">Add</button>
    <ul id="parent-list">
      <li class="clickable" id="post-1">Item 1</li>
      <li class="clickable" id="post-2">Item 2</li>
      <li class="clickable" id="post-3">Item 3</li>
    </ul>
</body>
</html>


问:
How to evaluate an equation with a function?
I'm trying to create a function which will solve for some numeric computation – which is given as a string.

Example:

def calculate(expression):
   # Solve the expression below
   return

# Result should be 19
calculate("5+8-3+9")
```

I have tried using .split() but got stuck.

答:
I would suggest breaking the question down to its numbers and operators.

Also, I've made the assumption that only whole numbers will be used – and only addition and subtraction.

```<code>def calculate(expression):
  # Get all components
  components = re.findall("[+-]{1}[0-9]*|^[0-9]*",expression)

  # get each number with its positive or negative operator
  operators = re.compile("[-+]")

  # Iterate and add to a list
  all_nums = []
  for x in components:
    # get the number
    n = int(re.sub(operators,"",x))
    # For all terms after the first
    if operators.search(x):
      op = operators.search(x).group()
      if op=="+":
        n = n
      elif op=="-":
        n=-n
    # Save the number
    all_nums.append(n)

  # Finally, add them up
  return sum(all_nums)

x = "5+8-3+9"
calculate(x)
# returns 19
</code>```

Body:
I'm trying to create a function which will solve for some numeric computation – which is given as a string.

Example:

def calculate(expression):
   # Solve the expression below
   return

# Result should be 19
calculate("5+8-3+9")

I have tried using .split() but got stuck.

Body:
I would suggest breaking the question down to its numbers and operators.

Also, I've made the assumption that only whole numbers will be used – and only addition and subtraction.

def calculate(expression):
  # Get all components
  components = re.findall("[+-]{1}[0-9]*|^[0-9]*",expression)

  # get each number with its positive or negative operator
  operators = re.compile("[-+]")

  # Iterate and add to a list
  all_nums = []
  for x in components:
    # get the number
    n = int(re.sub(operators,"",x))
    # For all terms after the first
    if operators.search(x):
      op = operators.search(x).group()
      if op=="+":
        n = n
      elif op=="-":
        n=-n
    # Save the number
    all_nums.append(n)

  # Finally, add them up
  return sum(all_nums)

x = "5+8-3+9"
calculate(x)
# returns 19


问:
How to use Google fonts without internet connection
Is there any way to download Google fonts and link them offline on localhost web page?</p>

答:
thanks for help
but i got it by help of this site https://transfonter.org/
then put all genereated woff files in same folder of css file then append font face to  my css file
then use font normally as described by transfonter.org</p>


问:
Jquery stop function from being called in a particular scenario (when its already being called by other event)
I'm trying to call a function in 2 ways: either way, when the function is called it should not allow the other one to call the method

Here renameFolder is called in 2 places: first on focus out and second when enter is being pressed.

The problem is that when enter is pressed it calls the function 2 times 1 for enter being pressed and second for focus out as well.

$('#rename').click(function() {

  //delete previous popup-menu if exists
  removeMenu();

  var folder = e.target.id;
  var folderId = $("#" + folder).attr("id");
  var folderName = $('#' + folder).parent().parent().children('.bd-title').text().trim();

  $('#' + folder).parent().parent().children('.bd-title').replaceWith('<textarea class="bd-folder-title-input" oninput="this.style.height = `1px`;this.style.height = (10+this.scrollHeight)+`px`;"  onfocusout="renameFolder()" maxlength="50" cols="10">' + folderName + '</textarea>');
  $('textarea').focus();
  $('textarea').select();
  $("textarea").keypress(function(e) {
    if (e.which == 13 && !e.shiftKey) {
      renameFolder();
    }
  });

});```

答:
There are many possible method, one easy way would just be to funnel everything through one path:</p>

```<code>$("textarea").keypress(function (e) {
  if (e.which == 13 && !e.shiftKey) {
    $(e.currentTarget).trigger('focusout'); // or blur
  }
});
</code>```

Body:
There are many possible method, one easy way would just be to funnel everything through one path:

$("textarea").keypress(function (e) {
  if (e.which == 13 && !e.shiftKey) {
    $(e.currentTarget).trigger('focusout'); // or blur
  }
});


问:
ClipDrawable width does not fit its parent
I have the parent relative layout with android:layout_width="match_parent" and a child ClipDrawable width also set to android:layout_width="match_parent ,but the ClipDrawable does not fit the parent width though the parent layout does not have a padding at all. I'd appreciate your help.

答: I found the solution, adding android:scaleType="fitXY" will make the ClipDrawable image fit it's parent.


问:
How to load elements into a string array
I have the following code to display filenames in a gridview. the variable filename contains the filenames that are present in a folder. now i want to store these filename values into a string array for further usage.

'Displaying files from a folder onto a gridview

```<code>   Dim inqueuePath As String = "C:\Users\Desktop\Sample"
   Dim fileInfo() As String
   Dim rowint As Integer = 0
   Dim name As String
   Dim directoryInfo As New System.IO.DirectoryInfo(inqueuePath)
fileInfo = System.IO.Directory.GetFiles(inqueuePath)

  With TaskGrid
    .Columns.Add("Column 0", "TaskName")
    .AutoResizeColumns()
 End With

For Each name In fileInfo
    ConfigWindow.TaskGrid.Rows.Add()
    Dim filename As String = System.IO.Path.GetFileName(name)
    ConfigWindow.TaskGrid.Item(0, rowint).Value = filename
    rowint = rowint + 1
Next
</code>```

Any suggestions please?

答:
As Stevo3000 points out in his comment, fileInfo already is a string array.

Just declare your fileinfo() variable at module/class level and you have your file list in array for using elsewhere

EDIT: Modify your loop

Declare fileInfo at Class level

```<code>Dim name as String
For i as integer = 0 To fileInfo.Length() - 1
    name = fileinfo(i)
    ConfigWindow.TaskGrid.Rows.Add()
    Dim filename As String = System.IO.Path.GetFileName(name)
    ConfigWindow.TaskGrid.Item(0, rowint).Value = filename
    rowint = rowint + 1
    fileinfo(i) = filename
Next
</code>```

Body:
I have the following code to display filenames in a gridview. the variable filename contains the filenames that are present in a folder. now i want to store these filename values into a string array for further usage.

'Displaying files from a folder onto a gridview

   Dim inqueuePath As String = "C:\Users\Desktop\Sample"
   Dim fileInfo() As String
   Dim rowint As Integer = 0
   Dim name As String
   Dim directoryInfo As New System.IO.DirectoryInfo(inqueuePath)
fileInfo = System.IO.Directory.GetFiles(inqueuePath)

  With TaskGrid
    .Columns.Add("Column 0", "TaskName")
    .AutoResizeColumns()
 End With

For Each name In fileInfo
    ConfigWindow.TaskGrid.Rows.Add()
    Dim filename As String = System.IO.Path.GetFileName(name)
    ConfigWindow.TaskGrid.Item(0, rowint).Value = filename
    rowint = rowint + 1
Next

Any suggestions please?

Body:
As Stevo3000 points out in his comment, fileInfo already is a string array.

Just declare your fileinfo() variable at module/class level and you have your file list in array for using elsewhere

EDIT: Modify your loop

Declare fileInfo at Class level

Dim name as String
For i as integer = 0 To fileInfo.Length() - 1
    name = fileinfo(i)
    ConfigWindow.TaskGrid.Rows.Add()
    Dim filename As String = System.IO.Path.GetFileName(name)
    ConfigWindow.TaskGrid.Item(0, rowint).Value = filename
    rowint = rowint + 1
    fileinfo(i) = filename
Next


问:
How to hide/disable TabLayouts when items on navigation drawer is clicked?
I am very new to android development and hence, I am not able to solve my problems via help from other internet resources. Using Youtube videos, I am designing an app that uses both NavigationDrawer and TabLayout, and all the TabLayout items and navigation drawer items use fragments. My problem is that when I clicked on items in navigation drawers, the app still displays TabLayout's fragments instead of displaying the fragment corresponding to the clicked item from `NavigationDrawer. Please help me with this. I have included code and even an image below. Thanks a lot.

The abovementioned image.

    public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //following gives toolbar and navigation bar can be viewed by sliding L-R
        Toolbar toolbar = findViewById(R.id.toolbar_main);
        setSupportActionBar(toolbar);
        //attach sectionpageadapter to viewpager
        SectionPagerAdapter pagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
        ViewPager pager = findViewById(R.id.pager);
        pager.setAdapter(pagerAdapter);

        //attach viewpager to tablayout
        TabLayout tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(pager);

        //following to give hamburger sign to navigation drawer
        drawer = findViewById(R.id.drawer_layout);

        //references to listen to click events on navigation views
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //following for hamburger sign to rotate when slide from L-R
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer,toolbar,
                R.string.navigation_drawer_open,R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //below is our default fragment which will be shown on create, without any clicks
        //if statement so that it wont reload on rotation or resume of the device
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new HomeFragment()).commit();
            navigationView.setCheckedItem(R.id.nav_home);
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.nav_home:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new HomeFragment()).commit();
            break;
            case R.id.nav_myaccount:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new AccountFragment()).commit();
                break;
            case R.id.nav_mymessages:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MessageFragment()).commit();
                break;
            case R.id.nav_mysongs:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MySongFragment()).commit();
                break;
            case R.id.nav_mystores:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new StoreFragment()).commit();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    //following for closing navagation bar instead of leaving activity immediately  when you press back button
    public void onBackPressed() {
        if(drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
        }else {
            super.onBackPressed();
        }
    }
    private class SectionPagerAdapter extends FragmentPagerAdapter{
        public SectionPagerAdapter(FragmentManager fm){
            super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

        @Override
        public int getCount() {
            return 4;
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return new HomeFragment();
                case 1:
                    return new FragmentArtists();
                case 2:
                    return new FragmentAlbum();
                case 3:
                    return new FragmentPlaylists();
            }
            return null;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            switch (position){
                case 0:
                    return getResources().getText(R.string.home_tab);
                case 1:
                    return getResources().getText(R.string.artist_tab);
                case 2:
                    return getResources().getText(R.string.album_tab);
                case 3:
                    return getResources().getText(R.string.playlist_tab);
            }
            return null;
        }
    }
}
```

答:
Replace this code!

```<code> @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.nav_home:
                pager.setVisibility(View.VISIBLE);
                tabs.setVisibility(View.VISIBLE);
                fragmentConterner.setVisibility(View.GONE);

                break;
            case R.id.nav_myaccount:
                pager.setVisibility(View.GONE);
                tabs.setVisibility(View.GONE);
                fragmentConterner.setVisibility(View.VISIBLE);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new AccountFragment()).commit();
                break;
            case R.id.nav_mymessages:
                pager.setVisibility(View.GONE);
                tabs.setVisibility(View.GONE);
                fragmentConterner.setVisibility(View.VISIBLE);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MessageFragment()).commit();
                break;
            case R.id.nav_mysongs:
                pager.setVisibility(View.GONE);
                tabs.setVisibility(View.GONE);
                fragmentConterner.setVisibility(View.VISIBLE);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MySongFragment()).commit();
                break;
            case R.id.nav_mystores:
                pager.setVisibility(View.GONE);
                tabs.setVisibility(View.GONE);
                fragmentConterner.setVisibility(View.VISIBLE);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new StoreFragment()).commit();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
</code>```

I hope it's helpful for you!

Body:
Replace this code!

 @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.nav_home:
                pager.setVisibility(View.VISIBLE);
                tabs.setVisibility(View.VISIBLE);
                fragmentConterner.setVisibility(View.GONE);

                break;
            case R.id.nav_myaccount:
                pager.setVisibility(View.GONE);
                tabs.setVisibility(View.GONE);
                fragmentConterner.setVisibility(View.VISIBLE);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new AccountFragment()).commit();
                break;
            case R.id.nav_mymessages:
                pager.setVisibility(View.GONE);
                tabs.setVisibility(View.GONE);
                fragmentConterner.setVisibility(View.VISIBLE);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MessageFragment()).commit();
                break;
            case R.id.nav_mysongs:
                pager.setVisibility(View.GONE);
                tabs.setVisibility(View.GONE);
                fragmentConterner.setVisibility(View.VISIBLE);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MySongFragment()).commit();
                break;
            case R.id.nav_mystores:
                pager.setVisibility(View.GONE);
                tabs.setVisibility(View.GONE);
                fragmentConterner.setVisibility(View.VISIBLE);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new StoreFragment()).commit();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

I hope it's helpful for you!


问:
Python string sequcence like excel
I want sequence like excel headers.

e.g :
A,B,C,..,Z,AA,AB....

My code

```<code>>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)
</code>```

答:
You can trying this:</p>

```<code>def get_colnum_string(n):
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string
</code>```

```<code>>>> get_colnum_string(1)
'A'
>>> get_colnum_string(26)
'Z'
>>> get_colnum_string(27)
'AA'
>>>
</code>```

Title: Python string sequcence like excel

Body:
I want sequence like excel headers.

e.g :
A,B,C,..,Z,AA,AB....

My code

>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)

Body:
You can trying this:

def get_colnum_string(n):
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

>>> get_colnum_string(1)
'A'
>>> get_colnum_string(26)
'Z'
>>> get_colnum_string(27)
'AA'
>>>


问:
Django admin not allowing superuser to log in (Custom User Model)
I have created a custom user class which appears to be working correctly however whenever I try to log in to the admin, I keep getting the following error on the login page:

Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.

I have already created several superuser which are all saving to the DB correctly with the is_staff/is_superuser/is_active flags set to True as you can see below:

```<code>CustomUser.objects.all().values()
<QuerySet [{'id': 1, 'password': 'test', 'last_login': None, 'is_superuser': True, 'username': 'test1', 'first_name': '', 'last_name': '', 'email': 'test1@test.com', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2020, 6, 1, 0, 17, 30, 297149, tzinfo=<UTC>), 'role_id': 1, 'user_type_id': 1, 'created_by_id': None, 'update_date': datetime.datetime(2020, 6, 1, 0, 17, 30, 298524, tzinfo=<UTC>), 'updated_by_id': None}]>
</code>```

I am officially puzzled as to what I have done incorrectly... Please help me figure this one out...

models.py:

```<code>from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.conf import settings

class UserType(models.Model):
    """
    This model defines the types of users which are allowed to be created in the application. Examples include:
    API Read Only User
    API Full CRUD User
    Business User
    """
    name = models.CharField(max_length=50, blank=False, null=False)
    description = models.TextField()
    active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_type_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_type_updated_by')

class Role(models.Model):
    """
    This model defines the job code/organization role a particular user is related to within their organization.
    Examples include:
    System User
    Business User
    Business User Manager
    """
    name = models.CharField(max_length=50)
    description = models.TextField()
    active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='role_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='role_updated_by')

class CustomBaseUserManager(BaseUserManager):
    """
    Defined a custom base user manager class so as operations are executed against the CustomUser model, application
    specific fields can be utilized.
    """

    def create_user(self, role, user_type, username=None, email=None, password=None):
        # Verify that email was submitted
        if not email:
            raise ValueError('Email is required to create a user')
        else:
            email = BaseUserManager.normalize_email(email)

        # If no username was submitted but email was, assign email to the username
        if not username:
            username = email

        # Validate and get role ID from Role model
        role = Role.objects.get(id=role, active=True)

        # Validate and get the user_type ID from UserType model
        user_type = UserType.objects.get(id=user_type, active=True)

        user = self.model(
            email=email,
            username=username,
            role=role,
            user_type=user_type
        )

        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, role, user_type, username=None, email=None, password=None):

    # Verify that email was submitted
        if not email:
            raise ValueError('Email is required to create a user')
        else:
            email = BaseUserManager.normalize_email(email)

    # If no username was submitted but email was, assign email to the username
        if not username:
            username = email

        # Validate and get role ID from Role model
        role = Role.objects.get(id=role, active=True).id

        # Validate and get the user_type ID from UserType model
        user_type = UserType.objects.get(id=user_type, active=True).id

        user = self.create_user(
            email=email,
            username=username,
            role=role,
            user_type=user_type
        )

        user.is_staff = True
        user.is_superuser = True
        user.is_active = True
        user.is_admin = True
        user.set_password(password)
        user.save(using=self._db)

        return user

class CustomUser(AbstractUser):
    """
    This is a custom user model allowing for the required relationship between a user and a specific role as defined
    by the organization. The only roles which will be allowed to be assigned to users are those which are active at the
    time the user is being created.
    """

    role = models.ForeignKey(Role, on_delete=models.DO_NOTHING, limit_choices_to={'active': True}, null=False,
                             blank=False)
    user_type = models.ForeignKey(UserType, on_delete=models.DO_NOTHING, limit_choices_to={'active': True}, null=False,
                                  blank=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_updated_by')

    objects = CustomBaseUserManager()

    REQUIRED_FIELDS = AbstractUser.REQUIRED_FIELDS + [
        'role',
        'user_type'
    ]

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def __str__(self):
        return '{} <{}>'.format(self.get_full_name(), self.email)

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True
</code>```

settings.py:

```<code>"""
Django settings for CategoryManager project.

Generated by 'django-admin startproject' using Django 3.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

SESSION_COOKIE_DOMAIN = '127.0.0.1:8000/'

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l%sn*03#ls^d6e5e-&)u93lyqzvh$bh1nij)ye2h4la$&jz^t!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Users',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CategoryManager.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CategoryManager.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Custom user definition
AUTH_USER_MODEL = 'Users.CustomUser'

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTHENTICATION_BACKENDS = (
    # Needed to login by custom User model, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",
)

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
</code>```

SOLVED:
Turns out there was some issue in my local cache which was preventing django from being able to actually allow me to log in. Once I cleared my cache locally, I was able to log in.

答: under create_superuser method change user=self.model to user=self.create_user</p>

Body:
I have created a custom user class which appears to be working correctly however whenever I try to log in to the admin, I keep getting the following error on the login page:

Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.

I have already created several superuser which are all saving to the DB correctly with the is_staff/is_superuser/is_active flags set to True as you can see below:

CustomUser.objects.all().values()
<QuerySet [{'id': 1, 'password': 'test', 'last_login': None, 'is_superuser': True, 'username': 'test1', 'first_name': '', 'last_name': '', 'email': 'test1@test.com', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2020, 6, 1, 0, 17, 30, 297149, tzinfo=<UTC>), 'role_id': 1, 'user_type_id': 1, 'created_by_id': None, 'update_date': datetime.datetime(2020, 6, 1, 0, 17, 30, 298524, tzinfo=<UTC>), 'updated_by_id': None}]>

I am officially puzzled as to what I have done incorrectly... Please help me figure this one out...

models.py:

from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.conf import settings

class UserType(models.Model):
    """
    This model defines the types of users which are allowed to be created in the application. Examples include:
    API Read Only User
    API Full CRUD User
    Business User
    """
    name = models.CharField(max_length=50, blank=False, null=False)
    description = models.TextField()
    active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_type_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_type_updated_by')

class Role(models.Model):
    """
    This model defines the job code/organization role a particular user is related to within their organization.
    Examples include:
    System User
    Business User
    Business User Manager
    """
    name = models.CharField(max_length=50)
    description = models.TextField()
    active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='role_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='role_updated_by')

class CustomBaseUserManager(BaseUserManager):
    """
    Defined a custom base user manager class so as operations are executed against the CustomUser model, application
    specific fields can be utilized.
    """

    def create_user(self, role, user_type, username=None, email=None, password=None):
        # Verify that email was submitted
        if not email:
            raise ValueError('Email is required to create a user')
        else:
            email = BaseUserManager.normalize_email(email)

        # If no username was submitted but email was, assign email to the username
        if not username:
            username = email

        # Validate and get role ID from Role model
        role = Role.objects.get(id=role, active=True)

        # Validate and get the user_type ID from UserType model
        user_type = UserType.objects.get(id=user_type, active=True)

        user = self.model(
            email=email,
            username=username,
            role=role,
            user_type=user_type
        )

        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, role, user_type, username=None, email=None, password=None):

    # Verify that email was submitted
        if not email:
            raise ValueError('Email is required to create a user')
        else:
            email = BaseUserManager.normalize_email(email)

    # If no username was submitted but email was, assign email to the username
        if not username:
            username = email

        # Validate and get role ID from Role model
        role = Role.objects.get(id=role, active=True).id

        # Validate and get the user_type ID from UserType model
        user_type = UserType.objects.get(id=user_type, active=True).id

        user = self.create_user(
            email=email,
            username=username,
            role=role,
            user_type=user_type
        )

        user.is_staff = True
        user.is_superuser = True
        user.is_active = True
        user.is_admin = True
        user.set_password(password)
        user.save(using=self._db)

        return user

class CustomUser(AbstractUser):
    """
    This is a custom user model allowing for the required relationship between a user and a specific role as defined
    by the organization. The only roles which will be allowed to be assigned to users are those which are active at the
    time the user is being created.
    """

    role = models.ForeignKey(Role, on_delete=models.DO_NOTHING, limit_choices_to={'active': True}, null=False,
                             blank=False)
    user_type = models.ForeignKey(UserType, on_delete=models.DO_NOTHING, limit_choices_to={'active': True}, null=False,
                                  blank=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_created_by')
    update_date = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True,
                                   related_name='user_updated_by')

    objects = CustomBaseUserManager()

    REQUIRED_FIELDS = AbstractUser.REQUIRED_FIELDS + [
        'role',
        'user_type'
    ]

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def __str__(self):
        return '{} <{}>'.format(self.get_full_name(), self.email)

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

settings.py:

"""
Django settings for CategoryManager project.

Generated by 'django-admin startproject' using Django 3.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

SESSION_COOKIE_DOMAIN = '127.0.0.1:8000/'

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l%sn*03#ls^d6e5e-&)u93lyqzvh$bh1nij)ye2h4la$&jz^t!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Users',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CategoryManager.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CategoryManager.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Custom user definition
AUTH_USER_MODEL = 'Users.CustomUser'

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTHENTICATION_BACKENDS = (
    # Needed to login by custom User model, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",
)

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

SOLVED:
Turns out there was some issue in my local cache which was preventing django from being able to actually allow me to log in. Once I cleared my cache locally, I was able to log in.


问:
Add the values of two tables based on a combination of columns
I have two tables:

```<code>df1 = pd.DataFrame({
    "c_id": [2000,3000,3000],
    "cloud":["GCP","GCP","Azure"],
    "invoice":[100,100,300]
})

c_id    cloud   invoice
2000    GCP     100
3000    GCP     100
3000    Azure   300

df2 = pd.DataFrame({
    "c_id": [1000,2000,2000,3000,3000],
    "cloud":["Azure","GCP","Azure","AWS","Azure"],
    "invoice":[200,200,300,100,100]
})

c_id    cloud   invoice
1000    Azure   200
2000    GCP     200
2000    Azure   300
3000    AWS     100
3000    Azure   100
</code>```

I want to add the two tables based on the combination of columns c_id and cloud. The result I'm looking for is:

```<code>c_id    cloud   invoice
1000    Azure   200
2000    Azure   300
2000    GCP     300
3000    AWS     100
3000    Azure   400
3000    GCP     100
</code>```

In my example, I only displayed the column invoice. In my actual dataset, there are actually more than 40 columns with a lot more constraints. Several of the columns only have value when the cloud is Azure, while others only have value when the cloud is either Azure or GCP

Is there's a clean way to add df1 and df2?

答:
You can also use df.set_index:

```<code>df1.set_index(['c_id', 'cloud']).add(df2.set_index(['c_id', 'cloud']), fill_value=0).reset_index()
</code>```

Output:

```<code>    c_id  cloud  invoice
0  1000  Azure   200.00
1  2000  Azure   300.00
2  2000    GCP   300.00
3  3000    AWS   100.00
4  3000  Azure   400.00
5  3000    GCP   100.00
</code>```

Body:
I have two tables:

df1 = pd.DataFrame({
    "c_id": [2000,3000,3000],
    "cloud":["GCP","GCP","Azure"],
    "invoice":[100,100,300]
})

c_id    cloud   invoice
2000    GCP     100
3000    GCP     100
3000    Azure   300

df2 = pd.DataFrame({
    "c_id": [1000,2000,2000,3000,3000],
    "cloud":["Azure","GCP","Azure","AWS","Azure"],
    "invoice":[200,200,300,100,100]
})

c_id    cloud   invoice
1000    Azure   200
2000    GCP     200
2000    Azure   300
3000    AWS     100
3000    Azure   100

I want to add the two tables based on the combination of columns c_id and cloud. The result I'm looking for is:

c_id    cloud   invoice
1000    Azure   200
2000    Azure   300
2000    GCP     300
3000    AWS     100
3000    Azure   400
3000    GCP     100

In my example, I only displayed the column invoice. In my actual dataset, there are actually more than 40 columns with a lot more constraints. Several of the columns only have value when the cloud is Azure, while others only have value when the cloud is either Azure or GCP

Is there's a clean way to add df1 and df2?

Body:
You can also use df.set_index:

df1.set_index(['c_id', 'cloud']).add(df2.set_index(['c_id', 'cloud']), fill_value=0).reset_index()

Output:

    c_id  cloud  invoice
0  1000  Azure   200.00
1  2000  Azure   300.00
2  2000    GCP   300.00
3  3000    AWS   100.00
4  3000  Azure   400.00
5  3000    GCP   100.00