问:
Why is this Angular Material table not rendering?
I am working on a Contacts app with Angular 9 and Angular Material. The list component should display, for each contact, some info and an image, in a table row.

In my app.module.ts I have imported, among others, MatTableModule.

In app\services\contacts-list.service.ts I have:

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

import { Contact } from '../models/Contact';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})

export class ContactsListService {

  contactsUrl = 'https://randomuser.me/api/?&results=20&inc=name,location,email,cell,picture';

  constructor(private http:HttpClient) { }

  getContcts():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

  getOneContact():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

}
</code>```

In the app\components\list\list.component.ts I have:

```<code>import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'city', 'country'];

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => {
        this.contactsList = contactsList; console.log(contactsList);
        this.contactsTableData = new MatTableDataSource(contactsList);
      },
      error => { }
    );
  }
}
</code>```

I the above component's template:

```<code><div class="container">
    <h2 class="mat-display-1 page-title">{{pageTitle}}</h2>
    <div class="mat-elevation-z8">
        <mat-table [data-source]="contactsTableData">

            <ng-container matColumnDef="fullName">
                <mat-header-cell *matHeaderCellDef> Full Name </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.name.first}} {{element.name.last}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="photo">
                <mat-header-cell *matHeaderCellDef> Photo </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.picture.large}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="email">
                <mat-header-cell *matHeaderCellDef> Email address </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="city">
                <mat-header-cell *matHeaderCellDef> City </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.city}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="phone">
                <mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.cell}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="country">
                <mat-header-cell *matHeaderCellDef> Country </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.country}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
    </div>
</div>
</code>```

The problem

The problem I am faced with is that only the table header is displayed (the column names) with no data, evan thought the line console.log(contactsList) from the component correctly shows the arrary of contacts:

```<code>[
  {
     "name":{
        "title":"Mr",
        "first":"Mair",
        "last":"da Cunha"
     },
     "location":{
        "street":{
           "number":1198,
           "name":"Rua Belo Horizonte "
        },
        "city":"Cachoeiro de Itapemirim",
        "state":"Tocantins",
        "country":"Brazil",
        "postcode":36034,
        "coordinates":{
           "latitude":"-78.1101",
           "longitude":"-171.0313"
        },
        "timezone":{
           "offset":"+5:00",
           "description":"Ekaterinburg, Islamabad, Karachi, Tashkent"
        }
     },
     "email":"mair.dacunha@example.com",
     "cell":"(66) 5998-0008",
     "picture":{
        "large":"https://randomuser.me/api/portraits/men/88.jpg",
        "medium":"https://randomuser.me/api/portraits/med/men/88.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/men/88.jpg"
     }
  }
]
</code>```

What is missing?

答:
Here is how the problem was solved, in case anybody else could use this piece of information:

In app\components\list\list.component.ts file I have:

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'phone', 'city', 'country'];

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => {
        this.contactsList = contactsList;
        this.contactsTableData = new MatTableDataSource(contactsList);
        this.contactsTableData.paginator = this.paginator;
      },
      error => { }
    );
  }
}
</code>```

In the component's template I have:

```<code><div class="container">
    <div class="mat-elevation-z8">
        <table mat-table [dataSource]="contactsTableData" class="w-100">
            <ng-container matColumnDef="fullName">
                <th mat-header-cell *matHeaderCellDef>Full Name</th>
                <td mat-cell *matCellDef="let element">{{element.name.first}} {{element.name.last}}</td>
            </ng-container>

            <ng-container matColumnDef="photo">
                <th mat-header-cell *matHeaderCellDef>Photo</th>
                <td mat-cell *matCellDef="let element">
                    <img src="{{element.picture.large}}" alt="{{element.name.first}} {{element.name.last}}" class="thumbnail rounded-circle">
                </td>
            </ng-container>

            <ng-container matColumnDef="email">
                <th mat-header-cell *matHeaderCellDef>Email address</th>
                <td mat-cell *matCellDef="let element">
                    <a href="mailto:{{element.email}}">{{element.email}}</a>
                </td>
            </ng-container>

            <ng-container matColumnDef="phone">
                <th mat-header-cell *matHeaderCellDef>Phone</th>
                <td mat-cell *matCellDef="let element">
                    <a href="tel:{{element.phone}}">{{element.cell}}</a>
                </td>
            </ng-container>

            <ng-container matColumnDef="city">
                <th mat-header-cell *matHeaderCellDef>City</th>
                <td mat-cell *matCellDef="let element">{{element.location.city}}</td>
            </ng-container>

            <ng-container matColumnDef="country">
                <th mat-header-cell *matHeaderCellDef>Country</th>
                <td mat-cell *matCellDef="let element">{{element.location.country}}</td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
        </table>
        <mat-paginator [pageSizeOptions]="[10, 20, 50]" [pageSize]="10" showFirstLastButtons></mat-paginator>
    </div>
</div>
</code>```

I also have this styles, for the images:

```<code>.rounded-circle {
    border-radius: 50%!important;
}

.thumbnail {
    padding: 2px;
    line-height: 1;
    background-color: #fff;
    border: 1px solid #ddd;
    height: 40px;
    width: auto;
}
</code>```

Body:
I am working on a Contacts app with Angular 9 and Angular Material. The list component should display, for each contact, some info and an image, in a table row.

In my app.module.ts I have imported, among others, MatTableModule.

In app\services\contacts-list.service.ts I have:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

import { Contact } from '../models/Contact';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})

export class ContactsListService {

  contactsUrl = 'https://randomuser.me/api/?&results=20&inc=name,location,email,cell,picture';

  constructor(private http:HttpClient) { }

  getContcts():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

  getOneContact():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

}

In the app\components\list\list.component.ts I have:

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'city', 'country'];

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => {
        this.contactsList = contactsList; console.log(contactsList);
        this.contactsTableData = new MatTableDataSource(contactsList);
      },
      error => { }
    );
  }
}

I the above component's template:

{{pageTitle}}

        <mat-table [data-source]="contactsTableData">

            <ng-container matColumnDef="fullName">
                <mat-header-cell *matHeaderCellDef> Full Name </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.name.first}} {{element.name.last}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="photo">
                <mat-header-cell *matHeaderCellDef> Photo </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.picture.large}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="email">
                <mat-header-cell *matHeaderCellDef> Email address </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="city">
                <mat-header-cell *matHeaderCellDef> City </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.city}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="phone">
                <mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.cell}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="country">
                <mat-header-cell *matHeaderCellDef> Country </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.country}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>

The problem

The problem I am faced with is that only the table header is displayed (the column names) with no data, evan thought the line console.log(contactsList) from the component correctly shows the arrary of contacts:

[
  {
     "name":{
        "title":"Mr",
        "first":"Mair",
        "last":"da Cunha"
     },
     "location":{
        "street":{
           "number":1198,
           "name":"Rua Belo Horizonte "
        },
        "city":"Cachoeiro de Itapemirim",
        "state":"Tocantins",
        "country":"Brazil",
        "postcode":36034,
        "coordinates":{
           "latitude":"-78.1101",
           "longitude":"-171.0313"
        },
        "timezone":{
           "offset":"+5:00",
           "description":"Ekaterinburg, Islamabad, Karachi, Tashkent"
        }
     },
     "email":"mair.dacunha@example.com",
     "cell":"(66) 5998-0008",
     "picture":{
        "large":"https://randomuser.me/api/portraits/men/88.jpg",
        "medium":"https://randomuser.me/api/portraits/med/men/88.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/men/88.jpg"
     }
  }
]

What is missing?

Body:
Here is how the problem was solved, in case anybody else could use this piece of information:

In app\components\list\list.component.ts file I have:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'phone', 'city', 'country'];

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => {
        this.contactsList = contactsList;
        this.contactsTableData = new MatTableDataSource(contactsList);
        this.contactsTableData.paginator = this.paginator;
      },
      error => { }
    );
  }
}

In the component's template I have:

<div class="container">
    <div class="mat-elevation-z8">
        <table mat-table [dataSource]="contactsTableData" class="w-100">
            <ng-container matColumnDef="fullName">
                <th mat-header-cell *matHeaderCellDef>Full Name</th>
                <td mat-cell *matCellDef="let element">{{element.name.first}} {{element.name.last}}</td>
            </ng-container>

            <ng-container matColumnDef="photo">
                <th mat-header-cell *matHeaderCellDef>Photo</th>
                <td mat-cell *matCellDef="let element">
                    <img src="{{element.picture.large}}" alt="{{element.name.first}} {{element.name.last}}" class="thumbnail rounded-circle">
                </td>
            </ng-container>

            <ng-container matColumnDef="email">
                <th mat-header-cell *matHeaderCellDef>Email address</th>
                <td mat-cell *matCellDef="let element">
                    <a href="mailto:{{element.email}}">{{element.email}}</a>
                </td>
            </ng-container>

            <ng-container matColumnDef="phone">
                <th mat-header-cell *matHeaderCellDef>Phone</th>
                <td mat-cell *matCellDef="let element">
                    <a href="tel:{{element.phone}}">{{element.cell}}</a>
                </td>
            </ng-container>

            <ng-container matColumnDef="city">
                <th mat-header-cell *matHeaderCellDef>City</th>
                <td mat-cell *matCellDef="let element">{{element.location.city}}</td>
            </ng-container>

            <ng-container matColumnDef="country">
                <th mat-header-cell *matHeaderCellDef>Country</th>
                <td mat-cell *matCellDef="let element">{{element.location.country}}</td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
        </table>
        <mat-paginator [pageSizeOptions]="[10, 20, 50]" [pageSize]="10" showFirstLastButtons></mat-paginator>
    </div>
</div>

I also have this styles, for the images:

.rounded-circle {
    border-radius: 50%!important;
}

.thumbnail {
    padding: 2px;
    line-height: 1;
    background-color: #fff;
    border: 1px solid #ddd;
    height: 40px;
    width: auto;
}


来源: stackexchange

问:
Will creating a Toast inside a Runnable cause a memory leak?
I use this portion of code, seen in many places, to push a Toast to the UI thread from a background thread:

```<code>new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivityFragment.this.getActivity(), "My Message"
                                Toast.LENGTH_SHORT).show();
                    }
                });
</code>```

It works great. However, because Runnable is an anonymous inner class with an implicit reference to the Fragment or Activity, will it cause a memory leak to occur? Or is the lifespan of the Toast so short that it isn't a factor and will be garbage collected soon?

答:
Or is the lifespan of the Toast so short that it isn't a factor and will be garbage collected soon?

You answered own question. It's potentially a "short-living" memory leak.

ContentLicense: CC BY-SA 4.0

Body:
I use this portion of code, seen in many places, to push a Toast to the UI thread from a background thread:

new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivityFragment.this.getActivity(), "My Message"
                                Toast.LENGTH_SHORT).show();
                    }
                });

It works great. However, because Runnable is an anonymous inner class with an implicit reference to the Fragment or Activity, will it cause a memory leak to occur? Or is the lifespan of the Toast so short that it isn't a factor and will be garbage collected soon?


问:
XSLT switching order of elements
I need to switch elements e.g. as in this xml:

```<code><configuration>
  <sites>
   <site name="site1"/>
   <site name="site2" />
   <site name="site3"/>
   <site name="site4"/>
  </sites>
</configuration>
</code>```

to:

```<code><configuration>
  <sites>
   <site name="site3"/>
   <site name="site4" />
   <site name="site1"/>
   <site name="site2"/>
  </sites>
</configuration>
</code>```

through XSLT. Can anybody help with this transformation ?

```<code><xsl:template match="node()|@*">
  <xsl:copy>
     <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
</xsl:template>

<xsl:variable name="site1" select="configuration/sites/site[@name='site1']" />

<xsl:variable name="site2" select="configuration/sites/site[@name='site2']" />

<xsl:template match="site[@name='site1'"/>
<xsl:template match="site[@name='site2'"/>

<xsl:template match="configuration/sitecore/sites">
  <xsl:apply-templates select="node()|@*"/>
  <xsl:value-of select="$site1"/>
  <xsl:value-of select="$site2"/>
</xsl:template>
</code>```

What I tried to do is and I am not sure if I can use some variable to store all specific element content to it remove appropriate element copy rest of node and append it at the end.

Thanks

Krp0

答:
The OP question, more precise

Late in the game, in comments it looked like what OP needed was not filter by name to reorder two items out of four, but apparently to extract the first ten items and output them after all the other items (which exact number is not known when writing style sheet).

Principle of solution

Apply the template just twice, using position() operator:

  <xsl:template match="sites">
    <xsl:copy>
      <xsl:apply-templates select="site[position()>10]"/>
      <xsl:apply-templates select="site[10>=position()]"/>
    </xsl:copy>
  </xsl:template>
```

<p>or (less readable, but does not confuse some incomplete parsers and syntax highlighters):</p>

<pre class="lang-xml prettyprint-override"><code>      <xsl:apply-templates select="site[position()>10]"/>
      <xsl:apply-templates select="site[10>=position()]"/>
</code>```

Reproducible solution

This file:

<configuration>
  <sites>
   <site name="site1"/>
   <site name="site2" />
   <site name="site3"/>
   <site name="site4"/>
   <site name="site5"/>
   <site name="site6"/>
   <site name="site7"/>
   <site name="site8"/>
   <site name="site9"/>
   <site name="site10"/>
   <site name="site11"/>
   <site name="site12"/>
   <site name="site13"/>
   <site name="site14"/>
   <site name="site15"/>
   <site name="site16"/>
   <site name="site17"/>
  </sites>
</configuration>
```

<p>is transformed into this (lacking some line feeds):</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0"?>
<configuration>
  <sites>
    <site name="site11"/>
    <site name="site12"/>
    <site name="site13"/>
    <site name="site14"/>
    <site name="site15"/>
    <site name="site16"/>
    <site name="site17"/>
    <site name="site1"/>
    <site name="site2"/>
    <site name="site3"/>
    <site name="site4"/>
    <site name="site5"/>
    <site name="site6"/>
    <site name="site7"/>
    <site name="site8"/>
    <site name="site9"/>
    <site name="site10"/>
  </sites>
</configuration>
</code>```

by this

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@*|*|processing-instruction()|comment()|node()">
    <xsl:copy>
      <xsl:apply-templates select="*|@*|text()|processing-instruction()|comment()|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="sites">
    <xsl:copy>
      <xsl:apply-templates select="site[position()>10]"/>
      <xsl:apply-templates select="site[10>=position()]"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
```

<p>Tested with </p>

<pre class="lang-sh prettyprint-override"><code>xsltproc -o out.xml sheet.xsl in.xml && cat out.xml
</code>```

ContentLicense: CC BY-SA 3.0

Title: XSLT switching order of elements

Body:
I need to switch elements e.g. as in this xml:

<configuration>
  <sites>
   <site name="site1"/>
   <site name="site2" />
   <site name="site3"/>
   <site name="site4"/>
  </sites>
</configuration>

to:

<configuration>
  <sites>
   <site name="site3"/>
   <site name="site4" />
   <site name="site1"/>
   <site name="site2"/>
  </sites>
</configuration>

through XSLT. Can anybody help with this transformation ?

<xsl:template match="node()|@*">
  <xsl:copy>
     <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
</xsl:template>

<xsl:variable name="site1" select="configuration/sites/site[@name='site1']" />

<xsl:variable name="site2" select="configuration/sites/site[@name='site2']" />

<xsl:template match="site[@name='site1'"/>
<xsl:template match="site[@name='site2'"/>

<xsl:template match="configuration/sitecore/sites">
  <xsl:apply-templates select="node()|@*"/>
  <xsl:value-of select="$site1"/>
  <xsl:value-of select="$site2"/>
</xsl:template>

What I tried to do is and I am not sure if I can use some variable to store all specific element content to it remove appropriate element copy rest of node and append it at the end.

Thanks

Krp0

Body:
The OP question, more precise

Late in the game, in comments it looked like what OP needed was not filter by name to reorder two items out of four, but apparently to extract the first ten items and output them after all the other items (which exact number is not known when writing style sheet).

Principle of solution

Apply the template just twice, using position() operator:

  <xsl:template match="sites">
    <xsl:copy>
      <xsl:apply-templates select="site[position()>10]"/>
      <xsl:apply-templates select="site[10>=position()]"/>
    </xsl:copy>
  </xsl:template>

or (less readable, but does not confuse some incomplete parsers and syntax highlighters):

      <xsl:apply-templates select="site[position()&gt;10]"/>
      <xsl:apply-templates select="site[10&gt;=position()]"/>

Reproducible solution

This file:

<configuration>
  <sites>
   <site name="site1"/>
   <site name="site2" />
   <site name="site3"/>
   <site name="site4"/>
   <site name="site5"/>
   <site name="site6"/>
   <site name="site7"/>
   <site name="site8"/>
   <site name="site9"/>
   <site name="site10"/>
   <site name="site11"/>
   <site name="site12"/>
   <site name="site13"/>
   <site name="site14"/>
   <site name="site15"/>
   <site name="site16"/>
   <site name="site17"/>
  </sites>
</configuration>

is transformed into this (lacking some line feeds):

<?xml version="1.0"?>
<configuration>
  <sites>
    <site name="site11"/>
    <site name="site12"/>
    <site name="site13"/>
    <site name="site14"/>
    <site name="site15"/>
    <site name="site16"/>
    <site name="site17"/>
    <site name="site1"/>
    <site name="site2"/>
    <site name="site3"/>
    <site name="site4"/>
    <site name="site5"/>
    <site name="site6"/>
    <site name="site7"/>
    <site name="site8"/>
    <site name="site9"/>
    <site name="site10"/>
  </sites>
</configuration>

by this

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@*|*|processing-instruction()|comment()|node()">
    <xsl:copy>
      <xsl:apply-templates select="*|@*|text()|processing-instruction()|comment()|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="sites">
    <xsl:copy>
      <xsl:apply-templates select="site[position()&gt;10]"/>
      <xsl:apply-templates select="site[10&gt;=position()]"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Tested with

xsltproc -o out.xml sheet.xsl in.xml && cat out.xml


问:
Convert raw data to pandas dataframe?
I have raw data in a string, which are basically multiple keywords in the form-

```<code>Law, of, three, stages
Alienation
Social, Facts
Theory, of, Social, System
</code>```

How do I import it into a dataframe such that it counts repetition and returns me a count of each word?

Edit: I've converted it into the following format

```<code> Law,of,three,stages,Alienation,Social,Facts,Theory,of,Social,System
</code>```

I want to convert it into a dataframe because i want to eventually predict which word has the highest probability of reocurring.

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

df = pd.DataFrame({
    'name': [ 'Law','of','three','stages','Alienation','Social','Facts','Theory','of','Social','System']
})

df['name'] = df.name.str.split('[ ,]', expand=True)

print(df)

word_freq = pd.Series(np.concatenate([x.split() for x in df.name])).value_counts()
print(word_freq)
</code>```

Title: Convert raw data to pandas dataframe?

Body:
I have raw data in a string, which are basically multiple keywords in the form-

Law, of, three, stages
Alienation
Social, Facts
Theory, of, Social, System

How do I import it into a dataframe such that it counts repetition and returns me a count of each word?

Edit: I've converted it into the following format

 Law,of,three,stages,Alienation,Social,Facts,Theory,of,Social,System

I want to convert it into a dataframe because i want to eventually predict which word has the highest probability of reocurring.


问:
Google Spreadsheet Formula with imported datas
i have imported data from another spreadsheet with importrage, and all is fine!

is it possible to add in a column formulas ?

i am tryng to use a function =IF(H:H=0,"",LEFT(H:H,FIND(",",H:H)-1)) but with imported data don't work

答:
A way to solve this is to import the data wanted and then reference it from the same spreadsheet.

So in your example, you can place the IMPORTRANGE formula in the H column and then later use the data from it in the formula you have.

Another way to actually be able to access the columns wanted from the imported range is to make use of the QUERY function.

For example the formula below will return the values from the first column of the imported range which are different from 0.

```<code>=QUERY(IMPORTRANGE("SPREADSHEET_URL", "RANGE"), "SELECT Col1 WHERE Col1 <> '0'")
</code>```

Note

For the QUERY formula, the cells from the imported range were formatted to Plain text in order to facilitate data manipulation since QUERY automatically assigns a data type for the column.

Also in order to format data in the way you want, you can make use of the CONTAINS and FORMAT clauses from the Google Query Language.

Reference

Google Query Language;

QUERY function

Body:
A way to solve this is to import the data wanted and then reference it from the same spreadsheet.

So in your example, you can place the IMPORTRANGE formula in the H column and then later use the data from it in the formula you have.

Another way to actually be able to access the columns wanted from the imported range is to make use of the QUERY function.

For example the formula below will return the values from the first column of the imported range which are different from 0.

=QUERY(IMPORTRANGE("SPREADSHEET_URL", "RANGE"), "SELECT Col1 WHERE Col1 <> '0'")

Note

For the QUERY formula, the cells from the imported range were formatted to Plain text in order to facilitate data manipulation since QUERY automatically assigns a data type for the column.

Also in order to format data in the way you want, you can make use of the CONTAINS and FORMAT clauses from the Google Query Language.

Reference

Google Query Language;

QUERY function


问:
How do I authenticate an Expo React Native app using PKCE and allow token refresh?
I feel like I'm missing a trick here. We have a managed Expo app and we're trying to authenticate the user against an OIDC identity provider (in our case it's Cognito).

It seems to two options we have are either expo-auth-session or expo-app-auth.

It seems that expo-auth-session will support a PKCE flow, but doesn't have a mechanism for refreshing the token.

expo-app-auth, on the other hand, does have a mechanism for refreshing the token but doesn't seem to support a PKCE flow.

I don't want to increase the token timeout because that's a security risk.
I also don't want to use an implicit flow because that's also a security risk.

There is an open PR against AuthSession to add refresh token support, but the fact that the library has been out for this long without it makes me wonder if I'm missing something.

Any help much appreciated!

答:
AppAuth supports both PKCE and refresh tokens, and is the most recommended option from a security viewpoint, but is tricky to implement. In React Native there is an AppAuth Bridge, though you would have more options with native mobile tech.

I have some code samples and blog posts that highlight AppAuth usage. Steps 8-10 of each post demonstrate PKCE and steps 15-16 demonstrate token refresh:

iOS Sample in SwiftUI

Android Sample in Kotlin


问:
Regex for German house number
Looking for a regex that specifies a German house number:

Valid house number:

25

25 a

25b

25-ab

12-14

1

9

21

1a

121 b

25A

25 a

Not valid house number:

1 a1

1a1

12ab12

0

b

0a

00a

a a

00 a

13àâäèéêë

The last example excludes every non Latin character

My regex doesn't match the way it should:

```<code>\d+(\s|-)?\w*$
</code>```

EDIT: Sorry, I had to change the examples above! Please have a look!

答:
Making the assumption (since you haven't provided those) this should also exclude patterns like 12-a1, 12-1a, 12-01 and 12-A1. If so, then maybe:

```<code>^[1-9]\d*(?:[ -]?(?:[a-zA-Z]+|[1-9]\d*))?$
</code>```

See the Online Demo

^ - Start string ancor.

[1-9]\d* - A single digit from range 1-9 followed by zero or more digits.

(?: - 1st Non-capture group.

[ -]? - An optional space or hyphen.

(?: - 2nd Non-capture group.

[a-zA-Z]+|[1-9]\d* - One or more characters from a-zA-Z or  single digit from range 1-9 followed by zero or more digits.

) - Closing 2nd non-capture group

) - Closing 1st non-capture group

? - Optional 1st non-capture group (to allow for single digits numbers).

$ - End string ancor.

Title: Regex for German house number

Body:
Looking for a regex that specifies a German house number:

Valid house number:

25

25 a

25b

25-ab

12-14

1

9

21

1a

121 b

25A

25 a

Not valid house number:

1 a1

1a1

12ab12

0

b

0a

00a

a a

00 a

13àâäèéêë

The last example excludes every non Latin character

My regex doesn't match the way it should:

\d+(\s|-)?\w*$

EDIT: Sorry, I had to change the examples above! Please have a look!

Body:
Making the assumption (since you haven't provided those) this should also exclude patterns like 12-a1, 12-1a, 12-01 and 12-A1. If so, then maybe:

^[1-9]\d*(?:[ -]?(?:[a-zA-Z]+|[1-9]\d*))?$

See the Online Demo

^ - Start string ancor.

[1-9]\d* - A single digit from range 1-9 followed by zero or more digits.

(?: - 1st Non-capture group.

[ -]? - An optional space or hyphen.

(?: - 2nd Non-capture group.

[a-zA-Z]+|[1-9]\d* - One or more characters from a-zA-Z or  single digit from range 1-9 followed by zero or more digits.

) - Closing 2nd non-capture group

) - Closing 1st non-capture group

? - Optional 1st non-capture group (to allow for single digits numbers).

$ - End string ancor.


问:
How to combine a pagination with Observables and the AsyncPipe in Angular 9?
There's a list of products coming from an API. The products are paginated and the user can switch to another page. The simplified template looks like this:

```<code><ul>
  <li *ngFor="let product of products$ | async">{{ product.name }}</li>
</ul>

<button type="button" (click)="gotoPage(1)">1</button>
<button type="button" (click)="gotoPage(2)">2</button>
</code>```

The component does look like this:

```<code>export class ProductsComponent implements OnInit {
  products$: Observable<Product[]>;

  constructor(
    private service: ProductService
  ) { }

  ngOnInit() {
    this.products$ = this.service.getAll({page: 1});
  }

  gotoPage(page: number): void {
    this.products$ = this.service.getAll({page: page});
  }
}
</code>```

My questions are:
Is this the correct way to update the Obersavble? Or does this produce memory leaks?

As a note: The URL will not change and the component should not reloaded on pagination change.

答:
You don't even subscribe to your observable so I don't think there is possible memory leak here, you just get some datas and the async pipe handle the 'transformation' for you.

Just in case, when you subscribe to a observable, you need to add few lines of code to properly unsubscribe and prevent memory leak :

```<code>ngUnsubscribe = new Subject();
myObservable: Observable<any>;

ngOnInit(){
  this.myObservable.pipe(takeUntil(ngUnsubscribe))
  .subscribe(...)
}

ngOnDestroy() {
  this.ngUnsubscribe.next();
  this.ngUnsubscribe.complete();
}
</code>```

A subject that will allow you to trigger the correct unsubscribe on everySubscribe that has the takeUntil.

The .next and .complete are necessary because .unsubscribe does not work as expected (Noticed it at work with NGRX and found some stackoverflow thread that talk about it).

Body:
There's a list of products coming from an API. The products are paginated and the user can switch to another page. The simplified template looks like this:

{{ product.name }}

<button type="button" (click)="gotoPage(1)">1</button>
<button type="button" (click)="gotoPage(2)">2</button>

The component does look like this:

export class ProductsComponent implements OnInit {
  products$: Observable<Product[]>;

  constructor(
    private service: ProductService
  ) { }

  ngOnInit() {
    this.products$ = this.service.getAll({page: 1});
  }

  gotoPage(page: number): void {
    this.products$ = this.service.getAll({page: page});
  }
}

My questions are:
Is this the correct way to update the Obersavble? Or does this produce memory leaks?

As a note: The URL will not change and the component should not reloaded on pagination change.

Body:
You don't even subscribe to your observable so I don't think there is possible memory leak here, you just get some datas and the async pipe handle the 'transformation' for you.

Just in case, when you subscribe to a observable, you need to add few lines of code to properly unsubscribe and prevent memory leak :

ngUnsubscribe = new Subject();
myObservable: Observable<any>;

ngOnInit(){
  this.myObservable.pipe(takeUntil(ngUnsubscribe))
  .subscribe(...)
}

ngOnDestroy() {
  this.ngUnsubscribe.next();
  this.ngUnsubscribe.complete();
}

A subject that will allow you to trigger the correct unsubscribe on everySubscribe that has the takeUntil.

The .next and .complete are necessary because .unsubscribe does not work as expected (Noticed it at work with NGRX and found some stackoverflow thread that talk about it).


问:
How to integrate Paypal Subscription API with Django
I have tried to integrate paypal subscription payment system with my django application. But there are some issue in API calling from backend.

Option 1:

```<code>url = "https://api.sandbox.paypal.com/v1/billing/subscriptions/I-VL5K5767RB6S"
headers = {'Authorization': 'Bearer Ae2UGxdThO9xMgFCSJihnhqDrv7zqTSngh6ILNc3imd6RrOM-GovHN_R0jFVL80Qm5oKhDi6rg715G9_', 'Content-Type': 'application/json'}
response = requests.get(url, headers=headers)
</code>```

Response to #1:

```<code>headers  {'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate', 'Content-Length': '83', 'Content-Type': 'application/json', 'Date': 'Fri, 29 May 2020 08:57:14 GMT', 'Paypal-Debug-Id': '50867574d2a79'}
status_code  401
response text {"error":"invalid_token","error_description":"Token signature verification failed"}
</code>```

Option 2:

```<code>url = "https://api.sandbox.paypal.com/v1/billing/subscriptions/I-VL5K5767RB6S"
headers = {'Authorization': 'Ae2UGxdThO9xMgFCSJihnhqDrv7zqTSngh6ILNc3imd6RrOM-GovHN_R0jFVL80Qm5oKhDi6rg715G9_', 'Content-Type': 'application/json'}
response = requests.get(url, headers=headers)
</code>```

Response to #2:

```<code>  {'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate', 'Content-Length': '244', 'Content-Type': 'application/json', 'Date': 'Fri, 29 May 2020 08:58:50 GMT', 'Paypal-Debug-Id': '3e1641470db08'}
status_code  401
response text {"name":"AUTHENTICATION_FAILURE","message":"Authentication failed due to invalid authentication credentials or a missing Authorization header.","links":[{"href":"https://developer.paypal.com/docs/api/overview/#error","rel":"information_link"}]}
</code>```

How can I get a successful response?

答:
Option #1 is the correct format for on Oauth2 Bearer token call. However, this:

```<code>Ae2UGxdThO9xMgFCSJihnhqDrv7zqTSngh6ILNc3imd6RrOM-GovHN_R0jFVL80Qm5oKhDi6rg715G9_
</code>```

Is not an Oauth2 access_token.  It is instead a PayPal REST App client ID, presumably for sandbox mode, which is one of the things you need to first use to obtain the appropriate access_token.

See PayPal's REST API documentation for information how to pass those Oauth 2.0 credentials and obtain the required access_token:

Note that access_tokens are typically valid for 9 hours, and after one expires you will need to generate a new one with that same call.

Body:
I have tried to integrate paypal subscription payment system with my django application. But there are some issue in API calling from backend.

Option 1:

url = "https://api.sandbox.paypal.com/v1/billing/subscriptions/I-VL5K5767RB6S"
headers = {'Authorization': 'Bearer Ae2UGxdThO9xMgFCSJihnhqDrv7zqTSngh6ILNc3imd6RrOM-GovHN_R0jFVL80Qm5oKhDi6rg715G9_', 'Content-Type': 'application/json'}
response = requests.get(url, headers=headers)

Response to #1:

headers  {'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate', 'Content-Length': '83', 'Content-Type': 'application/json', 'Date': 'Fri, 29 May 2020 08:57:14 GMT', 'Paypal-Debug-Id': '50867574d2a79'}
status_code  401
response text {"error":"invalid_token","error_description":"Token signature verification failed"}

Option 2:

url = "https://api.sandbox.paypal.com/v1/billing/subscriptions/I-VL5K5767RB6S"
headers = {'Authorization': 'Ae2UGxdThO9xMgFCSJihnhqDrv7zqTSngh6ILNc3imd6RrOM-GovHN_R0jFVL80Qm5oKhDi6rg715G9_', 'Content-Type': 'application/json'}
response = requests.get(url, headers=headers)

Response to #2:

  {'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate', 'Content-Length': '244', 'Content-Type': 'application/json', 'Date': 'Fri, 29 May 2020 08:58:50 GMT', 'Paypal-Debug-Id': '3e1641470db08'}
status_code  401
response text {"name":"AUTHENTICATION_FAILURE","message":"Authentication failed due to invalid authentication credentials or a missing Authorization header.","links":[{"href":"https://developer.paypal.com/docs/api/overview/#error","rel":"information_link"}]}

How can I get a successful response?

Body:
Option #1 is the correct format for on Oauth2 Bearer token call. However, this:

Ae2UGxdThO9xMgFCSJihnhqDrv7zqTSngh6ILNc3imd6RrOM-GovHN_R0jFVL80Qm5oKhDi6rg715G9_

Is not an Oauth2 access_token.  It is instead a PayPal REST App client ID, presumably for sandbox mode, which is one of the things you need to first use to obtain the appropriate access_token.

See PayPal's REST API documentation for information how to pass those Oauth 2.0 credentials and obtain the required access_token:

Note that access_tokens are typically valid for 9 hours, and after one expires you will need to generate a new one with that same call.


问:
How can I tell what is taking my request so long?
So here's the final line of my request:

```<code>Completed in 9209ms (View: 358, DB: 1582)
</code>```

So I need to figure out what's holding up the request.  This request can get to be upwards of a minute, so I really need to figure this one out.  If the DB and View take 1.9 seconds, then that means there's 7.2 seconds that are unaccounted for in the log.  How can I further analyze other parts of the code?  It would be great to know if, say, there was a single callback that's largely responsible for the delay.

答: Generally code that isn't in the DB or the view is in the controller (or it could be in the logic part of the model). The biggest culprits I've had problems with are loops within loops, or gratuitous use of :include => {...stuff...}

Body:
So here's the final line of my request:

Completed in 9209ms (View: 358, DB: 1582)

So I need to figure out what's holding up the request.  This request can get to be upwards of a minute, so I really need to figure this one out.  If the DB and View take 1.9 seconds, then that means there's 7.2 seconds that are unaccounted for in the log.  How can I further analyze other parts of the code?  It would be great to know if, say, there was a single callback that's largely responsible for the delay.


问:
Is __exit__ method called when there's an exception inside context manager?
Imagine we have a context manager called abc. So in the below code does the __exit__method defined inside abc be called if there's an exception.

```<code>with abc:
    print("entered context manager")
    raise Exception("raising exception")

</code>```

答:
Yes, according to the docs. The __exit__ method receives the exception as arguments:

object.__exit__(self, exc_type, exc_value, traceback)

Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None.

This question has a lot more answers and information.

It was the first google result when I typed in python __exit__ exception.

Body:
Imagine we have a context manager called abc. So in the below code does the __exit__method defined inside abc be called if there's an exception.

with abc:
    print("entered context manager")
    raise Exception("raising exception")


问:
Error: Bad Gateway 502 when opening Google App Engine Python Domain
When I'm visiting my website (https://osm-messaging-platform.appspot.com), I get this error on the main webpage:

```<code>502 Bad Gateway. nginx/1.14.0 (Ubuntu).
</code>```

It's really weird, since when I run it locally

```<code>python app.py
</code>```

I get no errors, and my app and the website load fine.

I've already tried looking it up, but most of the answers I've found on stack overflow either have no errors or don't relate to me. Here is the error when I look at my GCloud logs:

```<code>019-02-07 02:07:05 default[20190206t175104]  Traceback (most recent
call last):    File "/env/lib/python3.7/site-
packages/gunicorn/arbiter.py", line 583, in spawn_worker
worker.init_process()    File "/env/lib/python3.7/site-
packages/gunicorn/workers/gthread.py", line 104, in init_process
super(ThreadWorker, self).init_process()    File
"/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line
129, in init_process      self.load_wsgi()    File
"/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line
138, in load_wsgi      self.wsgi = self.app.wsgi()    File
"/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in
wsgi      self.callable = self.load()    File
"/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52,
in load      return self.load_wsgiapp()    File
"/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41,
in load_wsgiapp      return util.import_app(self.app_uri)    File
"/env/lib/python3.7/site-packages/gunicorn/util.py", line 350, in
import_app      __import__(module)  ModuleNotFoundError: No module
named 'main'
2019-02-07 02:07:05 default[20190206t175104]  [2019-02-07 02:07:05
+0000] [25] [INFO] Worker exiting (pid: 25)
2019-02-07 02:07:05 default[20190206t175104]  [2019-02-07 02:07:05
+0000] [8] [INFO] Shutting down: Master
2019-02-07 02:07:05 default[20190206t175104]  [2019-02-07 02:07:05
+0000] [8] [INFO] Reason: Worker failed to boot.
</code>```

And here are the contents of my app.yaml file:

```<code>runtime: python37

handlers:
 # This configures Google App Engine to serve the files in the app's
static
 # directory.
 - url: /static
 static_dir: static

- url: /.*
  script: auto
</code>```

I expected it to show my website, but it didn't. Can anyone help?

答: My mistake was naming the main app "main" which conflicted with main.py. It worked fine locally as it did not use main.py. I changed it to root and everything worked fine. It took me a whole day to solve it out.</p>

Body:
When I'm visiting my website (https://osm-messaging-platform.appspot.com), I get this error on the main webpage:

502 Bad Gateway. nginx/1.14.0 (Ubuntu).

It's really weird, since when I run it locally

python app.py

I get no errors, and my app and the website load fine.

I've already tried looking it up, but most of the answers I've found on stack overflow either have no errors or don't relate to me. Here is the error when I look at my GCloud logs:

019-02-07 02:07:05 default[20190206t175104]  Traceback (most recent
call last):    File "/env/lib/python3.7/site-
packages/gunicorn/arbiter.py", line 583, in spawn_worker
worker.init_process()    File "/env/lib/python3.7/site-
packages/gunicorn/workers/gthread.py", line 104, in init_process
super(ThreadWorker, self).init_process()    File
"/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line
129, in init_process      self.load_wsgi()    File
"/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line
138, in load_wsgi      self.wsgi = self.app.wsgi()    File
"/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in
wsgi      self.callable = self.load()    File
"/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52,
in load      return self.load_wsgiapp()    File
"/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41,
in load_wsgiapp      return util.import_app(self.app_uri)    File
"/env/lib/python3.7/site-packages/gunicorn/util.py", line 350, in
import_app      __import__(module)  ModuleNotFoundError: No module
named 'main'
2019-02-07 02:07:05 default[20190206t175104]  [2019-02-07 02:07:05
+0000] [25] [INFO] Worker exiting (pid: 25)
2019-02-07 02:07:05 default[20190206t175104]  [2019-02-07 02:07:05
+0000] [8] [INFO] Shutting down: Master
2019-02-07 02:07:05 default[20190206t175104]  [2019-02-07 02:07:05
+0000] [8] [INFO] Reason: Worker failed to boot.

And here are the contents of my app.yaml file:

runtime: python37

handlers:
 # This configures Google App Engine to serve the files in the app's
static
 # directory.
 - url: /static
 static_dir: static

- url: /.*
  script: auto

I expected it to show my website, but it didn't. Can anyone help?


问:
Pandas Mask query
I have a query in masks - My X is defined as below

```<code>X = pd.DataFrame({'a':[1,250,480],
               'b':[60,51,101],
               'c':[15,689,1],
               'd':[1,1,1],
               'e':[2,2,2]})
</code>```

which gives my X as below

```<code>    a   b   c   d   e
0   1   60  15  1   2
1   250 51  689 1   2
2   480 101 1   1   2
</code>```

When I create a mask as
 x['d'] =x.mask(x['c'] >100, "b")

I get the below output..

```<code>    a   b   c   d   e
0   1   60  15  1   2
1   250 51  689 b   2
2   480 101 1   480 2
</code>```

I don't understand where the 480 in column d is coming from.

Specifically x['d'] is now [1 b 480]
The b is clear, but where is 480 coming from ?? I think i am missing something about how masks work

Thanks.

答:
It looks like it is by design if assign DataFrame to one column it assign first column of DataFrame.

It use first column like if not specified columns - here is used DataFrame.mask, because x is passed to mask (not specified column name after x):

```<code>#replaced to `b` value all columns in df by mask x['c'] >100
print (x.mask(x['c'] >100, "b"))
      ^^^
     a    b   c  d  e
0    1   60  15  1  2
1    b    b   b  b  b
2  480  101   1  1  2
</code>```

And if assign to some column is used first column:

```<code>x['d'] = x.mask(x['c'] >100, "b")
        ^^^
print (x)
     a    b    c    d  e
0    1   60   15    1  2
1  250   51  689    b  2
2  480  101    1  480  2
</code>```

Test with removed first column a, then is assigned first column,  here b:

```<code>x = pd.DataFrame({ 'b':[60,51,101],
               'c':[15,689,1],
               'd':[1,1,1],
               'e':[2,2,2]})

print (x.mask(x['c'] >100, "b"))
      ^^^
     b   c  d  e
0   60  15  1  2
1    b   b  b  b
2  101   1  1  2

x['d'] = x.mask(x['c'] >100, "b")
        ^^^
print (x)
     b    c    d  e
0   60   15   60  2
1   51  689    b  2
2  101    1  101  2
</code>```

If assign DataFrame to column without condition, same behaviour:

```<code>x['d'] = x
        ^^^
print (x)
     a    b    c    d  e
0    1   60   15    1  2
1  250   51  689  250  2
2  480  101    1  480  2
</code>```

If want assign to 2 columns it correctly raise error:

```<code>x[['d','e']] = x.mask(x['c'] >100, "b")
              ^^^
print (x)
</code>```

ValueError: Columns must be same length as key

Correct way with specified column with Series.mask - Series, (column) are assigned, because specified column name after x is passed Series, here x['d'], x['b']:

```<code>#replaced to `b` value only column `d` in df by mask x['c'] >100
print (x['d'].mask(x['c'] >100, "b"))
        ^^^
0    1
1    b
2    1
Name: d, dtype: object

#replaced to `b` value only column `b` in df by mask x['c'] >100
print (x['b'].mask(x['c'] >100, "b"))
         ^^^
0     60
1      b
2    101
Name: b, dtype: object

x['d'] = x['d'].mask(x['c'] >100, "b")
           ^^^
x['e'] = x['b'].mask(x['c'] >100, "b")
           ^^^
print (x)
     a    b    c  d    e
0    1   60   15  1   60
1  250   51  689  b    b
2  480  101    1  1  101
</code>```

Title: Pandas Mask query

Body:
I have a query in masks - My X is defined as below

X = pd.DataFrame({'a':[1,250,480],
               'b':[60,51,101],
               'c':[15,689,1],
               'd':[1,1,1],
               'e':[2,2,2]})

which gives my X as below

    a   b   c   d   e
0   1   60  15  1   2
1   250 51  689 1   2
2   480 101 1   1   2

When I create a mask as
 x['d'] =x.mask(x['c'] >100, "b")

I get the below output..

    a   b   c   d   e
0   1   60  15  1   2
1   250 51  689 b   2
2   480 101 1   480 2

I don't understand where the 480 in column d is coming from.

Specifically x['d'] is now [1 b 480]
The b is clear, but where is 480 coming from ?? I think i am missing something about how masks work

Thanks.

Body:
It looks like it is by design if assign DataFrame to one column it assign first column of DataFrame.

It use first column like if not specified columns - here is used DataFrame.mask, because x is passed to mask (not specified column name after x):

#replaced to `b` value all columns in df by mask x['c'] >100
print (x.mask(x['c'] >100, "b"))
      ^^^
     a    b   c  d  e
0    1   60  15  1  2
1    b    b   b  b  b
2  480  101   1  1  2

And if assign to some column is used first column:

x['d'] = x.mask(x['c'] >100, "b")
        ^^^
print (x)
     a    b    c    d  e
0    1   60   15    1  2
1  250   51  689    b  2
2  480  101    1  480  2

Test with removed first column a, then is assigned first column,  here b:

x = pd.DataFrame({ 'b':[60,51,101],
               'c':[15,689,1],
               'd':[1,1,1],
               'e':[2,2,2]})

print (x.mask(x['c'] >100, "b"))
      ^^^
     b   c  d  e
0   60  15  1  2
1    b   b  b  b
2  101   1  1  2

x['d'] = x.mask(x['c'] >100, "b")
        ^^^
print (x)
     b    c    d  e
0   60   15   60  2
1   51  689    b  2
2  101    1  101  2

If assign DataFrame to column without condition, same behaviour:

x['d'] = x
        ^^^
print (x)
     a    b    c    d  e
0    1   60   15    1  2
1  250   51  689  250  2
2  480  101    1  480  2

If want assign to 2 columns it correctly raise error:

x[['d','e']] = x.mask(x['c'] >100, "b")
              ^^^
print (x)

ValueError: Columns must be same length as key

Correct way with specified column with Series.mask - Series, (column) are assigned, because specified column name after x is passed Series, here x['d'], x['b']:

#replaced to `b` value only column `d` in df by mask x['c'] >100
print (x['d'].mask(x['c'] >100, "b"))
        ^^^
0    1
1    b
2    1
Name: d, dtype: object

#replaced to `b` value only column `b` in df by mask x['c'] >100
print (x['b'].mask(x['c'] >100, "b"))
         ^^^
0     60
1      b
2    101
Name: b, dtype: object

x['d'] = x['d'].mask(x['c'] >100, "b")
           ^^^
x['e'] = x['b'].mask(x['c'] >100, "b")
           ^^^
print (x)
     a    b    c  d    e
0    1   60   15  1   60
1  250   51  689  b    b
2  480  101    1  1  101


问:
how to compare an objects array and a nested objects array?
I have only been programming for a short time and I am faced with a data structure that is difficult to understand.I have a function where I get an array of objects, representing products added to a cart.

```<code>  getAllAddedItems(addedItems) {

    this.fullInfoAddedItems.push(addedItems);
    const filtered = this.fullInfoAddedItems.reduce((filtered, item) => {
      if ( !filtered.some(filteredItem => JSON.stringify(filteredItem) === JSON.stringify(item)) ) {
        filtered.push(item);
      }
      return filtered;
    }, []);
    this.fullInfoAddedItems = filtered;
}

</code>```

As a result I get the following array of objects

```<code>[
  {
    "price": 0,
    "functional_id": "carnet_de_conventions",
    "quantity": 3
  },
  {
    "price": 0,
    "functional_id": "depliants_services_incinération",
    "quantity": 4
  }
]
</code>```

The problem is that I need a data "name" that is in an array of nested objects to complete the view information.

This would be the structure of the array

```<code>[

{
  "name": "Articles funeraires",
  "functional_id": "funeral",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Boîte de sympathie",
      "id": 27,
      "path": "",
      "items": [
        {
          "name": "1 boîte",
          "price": 0,
          "functional_id": "boite_de_sympathie_1_boite"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Coffret empreinte rouge",
      "id": 8,
      "path": "",
      "items": [
        {
          "name": "Carton de 10 coffrets",
          "price": 140,
          "functional_id": "carton_de_10_coffrets_2_recharges_argile_offertes_coloris_rouge"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "AfuBOX",
      "id": 10,
      "path": "",
      "items": [
        {
          "name" : "PACK N°1 comprenant :",
          "price": 30,
          "functional_id": "afubox_6_petits_modeles_4_moyens_modeles",
          "quantity": 4
        },
        {
          "name" : "PACK N°2 comprenant :",
          "price": 70,
          "functional_id": "afubox_6_petits_modeles_4_moyens_modeles",
          "quantity": 6
        }

      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue d'urnes décoratives",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue_urnes_decoratives"
        }
      ]
    }
  ],
  "sorting": 2200
},
  {
  "name": "Documents",
  "functional_id": "incineris_doc",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Carnet de conventions",
      "id": 17,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "carnet_de_conventions",
          "quantity": 3
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Affiches procédure",
      "description": "De prise en charge et de crémation des animaux",
      "id": 18,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "affiches_procedure_de_prise_en_charge_et_de_cremation_des_animaux"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Dépliants services de crémation",
      "description": "Pour animaux de compagnie",
      "id": 19,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "depliants_services_incinération",
          "quantity": 4
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue d'urnes décoratives",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue_urnes_decoratives"
        }
      ]
    }
  ],
  "sorting": 2400
},
{
  "name": "Matériel crémation",
  "functional_id": "furniture",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Sacs blancs",
      "description": "Pour les crémations Plurielles",
      "id": 11,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_petit_modele_par_25"
        },
        {
          "name": "Moyen modèle",
          "description": "Par 20",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_moyen_modele_par_20"
        },
        {
          "name": "Grand modèle",
          "description": "Par 10",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_grand_modele_par_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs bordeaux",
      "description": "Pour les crémations Référence",
      "id": 12,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_bordeaux_pour_les_cremations_reference_petit_modele_par_10"
        },
        {
          "name": "Grand modèle",
          "description": "Par 10",
          "price": 0,
          "functional_id": "sacs_bordeaux_pour_les_cremations_reference_grand_modele_par_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs verts",
      "description": "Pour les crémations Privées",
      "id": 13,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_petit_modele_unite"
        },
        {
          "name": "Moyen modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_moyen_modele_unite"
        },
        {
          "name": "Grand modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_grand_modele_unite"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs bleus",
      "description": "Pour pièces anatomiques",
      "id": 14,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_bleus_pour_pieces_anatomiques_standard_par_25"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Etiquettes d'identification",
      "id": 15,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 50",
          "price": 0,
          "functional_id": "etiquettes_identification_et_colliers_de_serrages_standard_par_50"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Colliers de serrages",
      "id": 16,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 50",
          "price": 0,
          "functional_id": "distributeurs_pour_sacs_housse_par_5"
        }
      ]
    }
  ],
  "sorting": 2300
}
]
</code>```

```<code>[
  {
    "price": 0,
    "functional_id": "carnet_de_conventions",
    "quantity": 3,
    "name": "Carnet de conventions"
  },
  {
    "price": 0,
    "functional_id": "depliants_services_incinération",
    "quantity": 4,
    "name": "Dépliants services de crémation"
  }
]

</code>```

I attach a stacblitz link simulating what I'm trying to do to compare by "functional_id" to get "name" from the array of nested objects and push to the first array

https://stackblitz.com/edit/angular-ivy-3wfgme

Someone to give me an effective option to get it.
Thank you in advance.

what I try to do is go through the second array to compare the "functional_id" of the original product with the "functional_id" of the product added to the first array, so I can extract the "name" in the first array and push it into the first array

```<code>this.market.forEach(function(item: any, i) {
      item.products.forEach(function(products: any, i) {
      products.items.forEach(function(sale: any, i) {
        let saleId = sale.functional_id;
        console.log(sale);
        console.log(saleId);

      });

      });
    });
</code>```

This is what I'm trying to do, but I don't see how I can compare the two arrays

答:
```<code>for (var j = 0; j <= nestedArray.length - 1; j++) {
  for (var k = 0; k <= nestedArray[j]['products'].length - 1; k++) {
    for (var i = 0; i <= inputArray.length - 1; i++) {
      let pos = nestedArray[j]['products'][k]['items'].map(ele => ele.functional_id).indexOf(inputArray[i]['functional_id']);
      if (pos != -1) {
        inputArray[i]['name'] = nestedArray[j]['products'][k]['name'];
      }
    }
  }
}
</code>```

Body:
I have only been programming for a short time and I am faced with a data structure that is difficult to understand.I have a function where I get an array of objects, representing products added to a cart.

  getAllAddedItems(addedItems) {

    this.fullInfoAddedItems.push(addedItems);
    const filtered = this.fullInfoAddedItems.reduce((filtered, item) => {
      if ( !filtered.some(filteredItem => JSON.stringify(filteredItem) === JSON.stringify(item)) ) {
        filtered.push(item);
      }
      return filtered;
    }, []);
    this.fullInfoAddedItems = filtered;
}

As a result I get the following array of objects

[
  {
    "price": 0,
    "functional_id": "carnet_de_conventions",
    "quantity": 3
  },
  {
    "price": 0,
    "functional_id": "depliants_services_incinération",
    "quantity": 4
  }
]

The problem is that I need a data "name" that is in an array of nested objects to complete the view information.

This would be the structure of the array

[

{
  "name": "Articles funeraires",
  "functional_id": "funeral",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Boîte de sympathie",
      "id": 27,
      "path": "",
      "items": [
        {
          "name": "1 boîte",
          "price": 0,
          "functional_id": "boite_de_sympathie_1_boite"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Coffret empreinte rouge",
      "id": 8,
      "path": "",
      "items": [
        {
          "name": "Carton de 10 coffrets",
          "price": 140,
          "functional_id": "carton_de_10_coffrets_2_recharges_argile_offertes_coloris_rouge"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "AfuBOX",
      "id": 10,
      "path": "",
      "items": [
        {
          "name" : "PACK N°1 comprenant :",
          "price": 30,
          "functional_id": "afubox_6_petits_modeles_4_moyens_modeles",
          "quantity": 4
        },
        {
          "name" : "PACK N°2 comprenant :",
          "price": 70,
          "functional_id": "afubox_6_petits_modeles_4_moyens_modeles",
          "quantity": 6
        }

      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue d'urnes décoratives",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue_urnes_decoratives"
        }
      ]
    }
  ],
  "sorting": 2200
},
  {
  "name": "Documents",
  "functional_id": "incineris_doc",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Carnet de conventions",
      "id": 17,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "carnet_de_conventions",
          "quantity": 3
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Affiches procédure",
      "description": "De prise en charge et de crémation des animaux",
      "id": 18,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "affiches_procedure_de_prise_en_charge_et_de_cremation_des_animaux"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Dépliants services de crémation",
      "description": "Pour animaux de compagnie",
      "id": 19,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "depliants_services_incinération",
          "quantity": 4
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue d'urnes décoratives",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue_urnes_decoratives"
        }
      ]
    }
  ],
  "sorting": 2400
},
{
  "name": "Matériel crémation",
  "functional_id": "furniture",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Sacs blancs",
      "description": "Pour les crémations Plurielles",
      "id": 11,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_petit_modele_par_25"
        },
        {
          "name": "Moyen modèle",
          "description": "Par 20",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_moyen_modele_par_20"
        },
        {
          "name": "Grand modèle",
          "description": "Par 10",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_grand_modele_par_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs bordeaux",
      "description": "Pour les crémations Référence",
      "id": 12,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_bordeaux_pour_les_cremations_reference_petit_modele_par_10"
        },
        {
          "name": "Grand modèle",
          "description": "Par 10",
          "price": 0,
          "functional_id": "sacs_bordeaux_pour_les_cremations_reference_grand_modele_par_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs verts",
      "description": "Pour les crémations Privées",
      "id": 13,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_petit_modele_unite"
        },
        {
          "name": "Moyen modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_moyen_modele_unite"
        },
        {
          "name": "Grand modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_grand_modele_unite"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs bleus",
      "description": "Pour pièces anatomiques",
      "id": 14,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_bleus_pour_pieces_anatomiques_standard_par_25"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Etiquettes d'identification",
      "id": 15,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 50",
          "price": 0,
          "functional_id": "etiquettes_identification_et_colliers_de_serrages_standard_par_50"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Colliers de serrages",
      "id": 16,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 50",
          "price": 0,
          "functional_id": "distributeurs_pour_sacs_housse_par_5"
        }
      ]
    }
  ],
  "sorting": 2300
}
]

[
  {
    "price": 0,
    "functional_id": "carnet_de_conventions",
    "quantity": 3,
    "name": "Carnet de conventions"
  },
  {
    "price": 0,
    "functional_id": "depliants_services_incinération",
    "quantity": 4,
    "name": "Dépliants services de crémation"
  }
]

I attach a stacblitz link simulating what I'm trying to do to compare by "functional_id" to get "name" from the array of nested objects and push to the first array

https://stackblitz.com/edit/angular-ivy-3wfgme

Someone to give me an effective option to get it.
Thank you in advance.

what I try to do is go through the second array to compare the "functional_id" of the original product with the "functional_id" of the product added to the first array, so I can extract the "name" in the first array and push it into the first array

this.market.forEach(function(item: any, i) {
      item.products.forEach(function(products: any, i) {
      products.items.forEach(function(sale: any, i) {
        let saleId = sale.functional_id;
        console.log(sale);
        console.log(saleId);

      });

      });
    });

This is what I'm trying to do, but I don't see how I can compare the two arrays


问:
Why the Create button in the main form does not work?

When I click on the "Attach PDF" button, the list form opens, but the
  "Create" button does not work. But when I go to the list form from the
  main menu, then everything is fine. What is the problem?

model.py

```<code>from odoo import models, fields, api

class AttachPDF(models.Model):
    _name = 'attach.pdf'

    product_id = fields.Many2one('product.template', string='Product', required=True)
    product_attribute_value_id = fields.Many2one('product.attribute.value', string='Attribute Value',
                                                 required=True, ondelete='cascade', index=True)
    file = fields.Binary(string="Upload file")
    file_name = fields.Char("File Name")
</code>```

views.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
  <data>
    <record id="attach_pdf_view_form" model="ir.ui.view">
      <field name="name">Attach PDF Form</field>
      <field name="model">attach.pdf</field>
      <field name="arch" type="xml">
        <form>
          <group>
            <field name="product_id"/>
            <field name="product_attribute_value_id"/>
          </group>
          <group>
            <field name="file" widget="binary" filename="file_name" string="Binary"/>
          </group>
        </form>
      </field>
    </record>

    <record id="attach_pdf_view_tree" model="ir.ui.view">
      <field name="name">Attach PDF List</field>
      <field name="model">attach.pdf</field>
      <field name="arch" type="xml">
        <tree>
          <field name="product_id"/>
          <field name="product_attribute_value_id"/>
          <field name="file_name" readonly="1"/>
        </tree>
      </field>
    </record>

    <record id="attach_file_wizard" model="ir.actions.act_window">
      <field name="name">Attach PDF</field>
      <field name="type">ir.actions.act_window</field>
      <field name="res_model">attach.pdf</field>
      <field name="view_type">form</field>
      <field name="view_mode">tree,form</field>
      <field name="domain" > [('product_id', '=', context.get('product_name'))]</field>
      <field name="view_id" ref="attach_pdf_view_tree"/>

    </record>

    <record id="view_form_product_attr_pdf" model="ir.ui.view">
      <field name="name">attach_pdf_attribute_product_product_template_only_form_view</field>
      <field name="model">product.template</field>
      <field name="inherit_id" ref="product.product_template_form_view"/>
      <field name="arch" type="xml">
        <xpath expr="//header/button[@name='121']" position="after">
          <button name="%(attach_pdf_attribute.attach_file_wizard)d" context="{'product_name': name}" string="Attach PDF" type="action" class="oe_highlight"/>
        </xpath>
      </field>
    </record>

  </data>
</odoo>
</code>```

**I am superuser rights
Odoo 12*

thanks for your answers***

答:
The create button should work. all records which have product_id different from the current product id should be filtered.

The records are filtered using the action domain, if you do not see records in the tree view, it means that they are hidden.

If you need to fill product_id with the current product pass default values in the button context:

```<code>context="{'default_product_id': active_id}"
</code>```

To filter records in the tree view and show only records related to the current product, you can use values from context as you did but it is not necessary since you can use active_id in the action domain:

```<code><field name="domain"> [('product_id', '=', active_id)]</field>
</code>```

Edit:

When you click on the create button Odoo will try to switch to the form view only if the controller that triggered the request is the current controller.

The current controller is the last controller in the controller stack, i.e. the currently displayed controller in the main window (not in a dialog), and null if there is no controller in the stack.

Try to set the target to current, which will let you create, edit, and delete easily.

```<code><field name="target">current</field>
</code>```

Or you can add One2many relation (inverse_name==product_id) to add documents to the product template.

Example:

Add the One2many relation:

```<code>class ProductTemplate(models.Model):
    _inherit = "product.template"

    document_ids = fields.One2many('attach.pdf', 'product_id', 'Documents')
</code>```

Add the following code after XPath expression.

```<code><notebook>
    <page string="Documents">
        <field name="document_ids" widget="one2many_list">
            <tree editable="bottom">
                <field name="product_attribute_value_id"/>
                <field name="file_name" invisible="1"/>
                <field name="file" widget="binary" filename="file_name"/>
            </tree>
        </field>
    </page>
</notebook>
</code>```

Body:
When I click on the "Attach PDF" button, the list form opens, but the
  "Create" button does not work. But when I go to the list form from the
  main menu, then everything is fine. What is the problem?

model.py

from odoo import models, fields, api

class AttachPDF(models.Model):
    _name = 'attach.pdf'

    product_id = fields.Many2one('product.template', string='Product', required=True)
    product_attribute_value_id = fields.Many2one('product.attribute.value', string='Attribute Value',
                                                 required=True, ondelete='cascade', index=True)
    file = fields.Binary(string="Upload file")
    file_name = fields.Char("File Name")

views.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
  <data>
    <record id="attach_pdf_view_form" model="ir.ui.view">
      <field name="name">Attach PDF Form</field>
      <field name="model">attach.pdf</field>
      <field name="arch" type="xml">
        <form>
          <group>
            <field name="product_id"/>
            <field name="product_attribute_value_id"/>
          </group>
          <group>
            <field name="file" widget="binary" filename="file_name" string="Binary"/>
          </group>
        </form>
      </field>
    </record>

    <record id="attach_pdf_view_tree" model="ir.ui.view">
      <field name="name">Attach PDF List</field>
      <field name="model">attach.pdf</field>
      <field name="arch" type="xml">
        <tree>
          <field name="product_id"/>
          <field name="product_attribute_value_id"/>
          <field name="file_name" readonly="1"/>
        </tree>
      </field>
    </record>

    <record id="attach_file_wizard" model="ir.actions.act_window">
      <field name="name">Attach PDF</field>
      <field name="type">ir.actions.act_window</field>
      <field name="res_model">attach.pdf</field>
      <field name="view_type">form</field>
      <field name="view_mode">tree,form</field>
      <field name="domain" > [('product_id', '=', context.get('product_name'))]</field>
      <field name="view_id" ref="attach_pdf_view_tree"/>

    </record>

    <record id="view_form_product_attr_pdf" model="ir.ui.view">
      <field name="name">attach_pdf_attribute_product_product_template_only_form_view</field>
      <field name="model">product.template</field>
      <field name="inherit_id" ref="product.product_template_form_view"/>
      <field name="arch" type="xml">
        <xpath expr="//header/button[@name='121']" position="after">
          <button name="%(attach_pdf_attribute.attach_file_wizard)d" context="{'product_name': name}" string="Attach PDF" type="action" class="oe_highlight"/>
        </xpath>
      </field>
    </record>

  </data>
</odoo>

**I am superuser rights
Odoo 12*

thanks for your answers***

Body:
The create button should work. all records which have product_id different from the current product id should be filtered.

The records are filtered using the action domain, if you do not see records in the tree view, it means that they are hidden.

If you need to fill product_id with the current product pass default values in the button context:

context="{'default_product_id': active_id}"

To filter records in the tree view and show only records related to the current product, you can use values from context as you did but it is not necessary since you can use active_id in the action domain:

<field name="domain"> [('product_id', '=', active_id)]</field>

Edit:

When you click on the create button Odoo will try to switch to the form view only if the controller that triggered the request is the current controller.

The current controller is the last controller in the controller stack, i.e. the currently displayed controller in the main window (not in a dialog), and null if there is no controller in the stack.

Try to set the target to current, which will let you create, edit, and delete easily.

<field name="target">current</field>

Or you can add One2many relation (inverse_name==product_id) to add documents to the product template.

Example:

Add the One2many relation:

class ProductTemplate(models.Model):
    _inherit = "product.template"

    document_ids = fields.One2many('attach.pdf', 'product_id', 'Documents')

Add the following code after XPath expression.

<notebook>
    <page string="Documents">
        <field name="document_ids" widget="one2many_list">
            <tree editable="bottom">
                <field name="product_attribute_value_id"/>
                <field name="file_name" invisible="1"/>
                <field name="file" widget="binary" filename="file_name"/>
            </tree>
        </field>
    </page>
</notebook>


问:
How to add another name in existing index with scores?
I created a datafame as shown below. I have to add another name in index and update scores; how to append it to existing. data? I have to add 'Pandey' in index and Test1 = 56 and Test2 = 76

```<code>test_score = pd.DataFrame(
                    {'Test1':[82,75,83,92,85],

                     'Test2':[85,81,75,85,91]},

                      index = ['Sachin','Dravid','virat','Rohith','Dhawan'])
</code>```

My result should be

```<code>       Test1    Test2

Sachin  82       85

Dravid  75       81

virat   83       75

Rohith  92       85

Dhawan  85       91

Pandey  56       76
</code>```

答:
```<code>row = pd.Series({'Test1':56, 'Test2' : 76},index='pandey')
test_score= test_score.append(row)
</code>```

Body:
I created a datafame as shown below. I have to add another name in index and update scores; how to append it to existing. data? I have to add 'Pandey' in index and Test1 = 56 and Test2 = 76

test_score = pd.DataFrame(
                    {'Test1':[82,75,83,92,85],

                     'Test2':[85,81,75,85,91]},

                      index = ['Sachin','Dravid','virat','Rohith','Dhawan'])

My result should be

       Test1    Test2

Sachin  82       85

Dravid  75       81

virat   83       75

Rohith  92       85

Dhawan  85       91

Pandey  56       76


答:
Looking at the source of Async pipe, you can see inside transform() function:

```<code>if (obj !== this._obj) {
  this._dispose();
  return this.transform(obj as any);
}
</code>```

Which unsubscribes previous Observable if there is one, if it is a new object. So you are safe to use it in that way.

Title: How to combine a pagination with Observables and the AsyncPipe in Angular 9?

Body:
Looking at the source of Async pipe, you can see inside transform() function:

if (obj !== this._obj) {
  this._dispose();
  return this.transform(obj as any);
}

Which unsubscribes previous Observable if there is one, if it is a new object. So you are safe to use it in that way.


问:
Is it possible to declare the type with 'this' keyword like that in typescript?
Example:

```<code>// ===== Declaration ===== //
class A {
  CONSTS_TYPE: { [key: string]: [any] }
  CONSTS: { [key in keyof this['CONSTS_TYPE']]: key }
  foo<T extends keyof this['CONSTS_TYPE'] | string>(
    type: T,
    callback: (...args: T extends keyof this['CONSTS_TYPE'] ? this['CONSTS_TYPE'][T] : any) => any
  ) { /** some implementation*/ }
}
class B extends A {
  CONSTS_TYPE: {
    aa: [number],
    bb: [string]
  }
  // Here is the problem
  // Type '{ aa: "aa"; bb: "bb"; }' is not assignable to type '{ [key in keyof this["CONSTS_TYPE"]]: key; }'.(2322)
  CONSTS: { [key in keyof this['CONSTS_TYPE']]: key } = {
    aa: 'aa',
    bb: 'bb'
  }
}

// ===== Call ===== //
const b = new B;
b.foo(b.CONSTS.aa, (arg) => {
  // so that i can know 'arg' is a 'number' type
  arg // number type
});
</code>```

it works well, but not too well.

i know '// @ts-ignore' will work really well

but I think there may be other solutions

[Playground Link]

答:
Isn't a generic class what you're actually looking for instead?</p>

```<code>declare class Foo<T extends Record<string, [any]>> {
  CONST_TYPES: T;
  CONSTS: {
    [K in keyof T]: K
  }

  constructor(types: T);

  foo<U extends keyof T>(type: U, callback: (value: T[U]) => any): any;
}

const foo = new Foo({ aa: [42], bb: ['foo'] });

foo.foo(foo.CONSTS.bb, (arg) => {
  arg // [string]
})
</code>```

Body:
Example:

// ===== Declaration ===== //
class A {
  CONSTS_TYPE: { [key: string]: [any] }
  CONSTS: { [key in keyof this['CONSTS_TYPE']]: key }
  foo<T extends keyof this['CONSTS_TYPE'] | string>(
    type: T,
    callback: (...args: T extends keyof this['CONSTS_TYPE'] ? this['CONSTS_TYPE'][T] : any) => any
  ) { /** some implementation*/ }
}
class B extends A {
  CONSTS_TYPE: {
    aa: [number],
    bb: [string]
  }
  // Here is the problem
  // Type '{ aa: "aa"; bb: "bb"; }' is not assignable to type '{ [key in keyof this["CONSTS_TYPE"]]: key; }'.(2322)
  CONSTS: { [key in keyof this['CONSTS_TYPE']]: key } = {
    aa: 'aa',
    bb: 'bb'
  }
}

// ===== Call ===== //
const b = new B;
b.foo(b.CONSTS.aa, (arg) => {
  // so that i can know 'arg' is a 'number' type
  arg // number type
});

it works well, but not too well.

i know '// @ts-ignore' will work really well

but I think there may be other solutions

<a href="https://www.typescriptlang.org/play/index.html?ssl=28&ssc=4&pln=7&pc=1#code/PTAEF5M0BEFMDGAbAhgJxQFwJYHsB2EU4oIAUMigM5WgCCoA3maKAMIDyAcgMoAqPAPp8AmgAUAogC4moANoBrOAE8ZVTGmz4A5gF0ZclPmW7QAXxbtu-HjMbyly0FtCPcAM1CYAFtipyAck5eAWFxCQDdfVcVc0t3XFwAHj5QOAAPTDh8ABNaN08fP0DgmzDJSNAAH1B1TR0APgAKS1ZMZQAHOBk+ABpW0AQUJCQAIxQEBRkmgDo59G0qHrTM7LyY5Q8vX38g61DRCtMAfm3ivZChQ4jdOT5TGSNlAEoIBtAny1f7YAAqX9quAAtnBnECOkg4CD8JgsHh8L8wBYLJQaKAAEIrLK5WgMZisUoHcJ2AYoFAGfAAVyBozgaF0-VYrFGowMdS0eksFlYIFAAAk6aC-NtQR00LhRpCgZZeXxOqCAvYyTIAERklUAblALNVLM15gCzlo+FwmA+NGw2nwKEloMwuC88tAiocsRcBTO-hVhKu4RVURkji1ZgCMyaACYAMzh8PPSw+uyupzulRbIq7H3lG7RRzmCBMUnk51kgKMpk650sgJcsgWMi84gkNjDJBEKCkYAUAjqbX5-BwADuGI1ZFGMwSuCaY59MxZvVATQWr3A73xHcB2ywzkGRlcJqHAQWhuFKGdVJpdMN7S6lgW6-PtLQjpvZmeGqAA" rel="nofollow noreferrer">[Playground Link]

Body:
Isn't a generic class what you're actually looking for instead?

declare class Foo<T extends Record<string, [any]>> {
  CONST_TYPES: T;
  CONSTS: {
    [K in keyof T]: K
  }

  constructor(types: T);

  foo<U extends keyof T>(type: U, callback: (value: T[U]) => any): any;
}

const foo = new Foo({ aa: [42], bb: ['foo'] });

foo.foo(foo.CONSTS.bb, (arg) => {
  arg // [string]
})


问:
how could set content-type in magento web api?
I build simple web api and it returns  the error "message": "Content-Type header is invalid." how could I resolve it please guide me.
under Magento/SamplePaymentGateway/etc my webapi is

```<code><?xml version="1.0" ?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route method="GET" url="/V1/cevnn/post">
        <service class="Magento\SamplePaymentGateway\Api\PostManagementInterface" method="getPost"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>
</code>```

Magento/SamplePaymentGateway/Api is PostManagementInterface.php file

```<code><?php
namespace Magento\SamplePaymentGateway\Api;
interface PostManagementInterface {
    public function getPost($param);
}
</code>```

and under Mangento/SamplePaymentGateway/Model there is PostManagement.php file

```<code><?php
namespace Magento\SamplePaymentGateway\Model;
class PostManagement {
    public function getPost($param)
    {
        return 'api GET return the $param ' . $param;
    }
}
</code>```

when I call it through this url http://127.0.0.1/project-community-edition/rest/V1/cevnn/post?param=ali.
it returns the following error {
    "message": "Content-Type header is invalid."
}
please guide me how could I fix it.

答:
Dependency Injection configuration is missing.

In order to tell Magento which class to use for interface Magento\SamplePaymentGateway\Api\PostManagementInterface, you must add it in your di.xml file :

```<code><preference for="Magento\SamplePaymentGateway\Api\PostManagementInterface" type="Magento\SamplePaymentGateway\Model\PostManagement"/>
</code>```

Body:
I build simple web api and it returns  the error "message": "Content-Type header is invalid." how could I resolve it please guide me.
under Magento/SamplePaymentGateway/etc my webapi is

<?xml version="1.0" ?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route method="GET" url="/V1/cevnn/post">
        <service class="Magento\SamplePaymentGateway\Api\PostManagementInterface" method="getPost"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Magento/SamplePaymentGateway/Api is PostManagementInterface.php file

<?php
namespace Magento\SamplePaymentGateway\Api;
interface PostManagementInterface {
    public function getPost($param);
}

and under Mangento/SamplePaymentGateway/Model there is PostManagement.php file

<?php
namespace Magento\SamplePaymentGateway\Model;
class PostManagement {
    public function getPost($param)
    {
        return 'api GET return the $param ' . $param;
    }
}

when I call it through this url http://127.0.0.1/project-community-edition/rest/V1/cevnn/post?param=ali.
it returns the following error {
    "message": "Content-Type header is invalid."
}
please guide me how could I fix it.

Body:
Dependency Injection configuration is missing.

In order to tell Magento which class to use for interface Magento\SamplePaymentGateway\Api\PostManagementInterface, you must add it in your di.xml file :

<preference for="Magento\SamplePaymentGateway\Api\PostManagementInterface" type="Magento\SamplePaymentGateway\Model\PostManagement"/>


答:
You could make the space or hyphen optional [-\s]? and make 1+ word chars together in an optional group.

If the housenumber can not start with a zero, you could start the match with [1-9]

```<code>^[1-9]\d*(?:[-\s]?\w+)?$
</code>```

Regex demo

Matching only a-z or 0-9 or A-Z if 25 A is also valid

```<code>^[1-9]\d*(?:[-\s]?[a-zA-Z0-9]+)?$
</code>```

Regex demo

Title: Regex for German house number

Body:
Looking for a regex that specifies a German house number:

Valid house number:

25

25 a

25b

25-ab

12-14

1

9

21

1a

121 b

25A

25 a

Not valid house number:

1 a1

1a1

12ab12

0

b

0a

00a

a a

00 a

13àâäèéêë

The last example excludes every non Latin character

My regex doesn't match the way it should:

\d+(\s|-)?\w*$

EDIT: Sorry, I had to change the examples above! Please have a look!

Body:
You could make the space or hyphen optional [-\s]? and make 1+ word chars together in an optional group.

If the housenumber can not start with a zero, you could start the match with [1-9]

^[1-9]\d*(?:[-\s]?\w+)?$

Regex demo

Matching only a-z or 0-9 or A-Z if 25 A is also valid

^[1-9]\d*(?:[-\s]?[a-zA-Z0-9]+)?$

Regex demo


问:
Popup Issue in the Firefox browser only
When I call API with Async Await function. And then after I open the link in the new tab that time gave alert.

Firefox prevented this site from opening a pop-up window.

my code is in Javascript.

How to bypass this alert or how to remove this alert ?

This is the demo :

$("a#link").click(function (e) {
  e.preventDefault();

  var url = this.href;

  // this will not be blocked
  var w0 = window.open(url);
  console.log("w0: " + !!w0); // w0: true

  window.setTimeout(function () {
    // this will be blocked
    var w1 = window.open(url);
    console.log("w1: " + !!w1); // w1: false
  }, 5000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
StackOverflow</code>```

Anyone can help me for this ?

Thank You in Advance.

答:
How to bypass this alert or how to remove this alert ?

There's no way to do that. It's by design.

from Firefox 65 release notes

Going forward, only one Window.open() call is allowed per event (bug 675574).

and an official blog post

Lastly, to avoid popup spam, Window.open() may now only be called once per user interaction event.

Here's a Minimal, Reproducible Example

document.onclick = function() {
  window.open("https://stackoverflow.com") // a click opens this
  window.open("https://superuser.com")     // but not this, one-action, one-window
}
```

Title: Popup Issue in the Firefox browser only

Body:
When I call API with Async Await function. And then after I open the link in the new tab that time gave alert.

Firefox prevented this site from opening a pop-up window.

my code is in Javascript.

How to bypass this alert or how to remove this alert ?

This is the demo :

$("a#link").click(function (e) {
  e.preventDefault();

  var url = this.href;

  // this will not be blocked
  var w0 = window.open(url);
  console.log("w0: " + !!w0); // w0: true

  window.setTimeout(function () {
    // this will be blocked
    var w1 = window.open(url);
    console.log("w1: " + !!w1); // w1: false
  }, 5000);
});

StackOverflow

Anyone can help me for this ?

Thank You in Advance.


问:
Python telegram bot 2 or more arguments
I have python telegram-bot and try to search table for 2 columns.

How to make bot accept 2 arguments, right now if I use /char 1 2 (or /char 1 2 3 4 5 etc will send 5 query results for every level).

It sends me 2 different messages, one with Character lvl 1 and second with Character level 2.

But I would like to search from DB for example: "Class and Level" /char warrior 1

```<code>WHERE Class='arg1' and level='arg2'
</code>```

Or maybe is possible to put results into a string and read from there, just that bot read next argument as new command.

Thanks.

```<code>/char 3 1

[Character] [Class] [Level]
["Char6","tank",3]

[Character] [Class] [Level]
["Char1","warrior",1]
</code>```

```<code>def char(bot, update,args):
  for arg in args:
       print(arg)
       cursor.execute("SELECT name,Class,level users where level="+arg)
       row = cursor.fetchone()
       if row == None:
           chat_id = update.message.chat_id
           bot.sendMessage(chat_id=chat_id, text=('No Character found '+arg))

       else:
           data = row[0],row[1],row[2]
           print(data)
           #cursor.close()
           #conn.close()
           chat_id = update.message.chat_id
           bot.sendMessage(chat_id=chat_id, text=('[Character] [Class] [Level]'))
           bot.sendMessage(chat_id=chat_id, text=(data))
</code>```

答:
Forgot to answer my own question, it's easy to do it in the end.</p>

```<code>def char(update, context):
    create=update.message.text[6:] #6 because your command is /char (+space) = 6 chars
    create = create.split()        #create split
    Class = create[0]              #first from split is class to search
    Level= create[1]               #second for level
</code>```

Title: Python telegram bot 2 or more arguments

Body:
I have python telegram-bot and try to search table for 2 columns.

How to make bot accept 2 arguments, right now if I use /char 1 2 (or /char 1 2 3 4 5 etc will send 5 query results for every level).

It sends me 2 different messages, one with Character lvl 1 and second with Character level 2.

But I would like to search from DB for example: "Class and Level" /char warrior 1

WHERE Class='arg1' and level='arg2'

Or maybe is possible to put results into a string and read from there, just that bot read next argument as new command.

Thanks.

/char 3 1

[Character] [Class] [Level]
["Char6","tank",3]

[Character] [Class] [Level]
["Char1","warrior",1]

def char(bot, update,args):
  for arg in args:
       print(arg)
       cursor.execute("SELECT name,Class,level users where level="+arg)
       row = cursor.fetchone()
       if row == None:
           chat_id = update.message.chat_id
           bot.sendMessage(chat_id=chat_id, text=('No Character found '+arg))

       else:
           data = row[0],row[1],row[2]
           print(data)
           #cursor.close()
           #conn.close()
           chat_id = update.message.chat_id
           bot.sendMessage(chat_id=chat_id, text=('[Character] [Class] [Level]'))
           bot.sendMessage(chat_id=chat_id, text=(data))

Body:
Forgot to answer my own question, it's easy to do it in the end.

def char(update, context):
    create=update.message.text[6:] #6 because your command is /char (+space) = 6 chars
    create = create.split()        #create split
    Class = create[0]              #first from split is class to search
    Level= create[1]               #second for level