问:
How to insert rows of information into different rows in a mysql database?
I don't know how to insert a list of info into a mysql database.

I'm trying to insert rows data into a database but it is simply inserting the last row three times.  The list is named "t" and it is a tuple .

Data:

```<code>11/04/19,17:33,33.4,55
11/04/19,17:34,22.9,57
11/04/19,17:35,11.9,81
</code>```

Code:

```<code>import mysql.connector

sql = mysql.connector.connect(
    host='    ',
    user='    ',
    password='    ',
    db="     "
    )
cursor = sql.cursor()

f = open("C:\Cumulus\data\Apr19log.txt","r")

while True:
    s = f.readline()
    list=[]
    if (s != ""):
        t=s.split(',')
        for item in t:
            list.append(item)
    else:
        break;

sqllist =    """INSERT INTO station_fenelon (variable, date,
time,outside_temp, outside_humidity)
                VALUES (%s, %s, %s, %s, %s)"""

record =[(1, t[0], t[1], t[2],t[3]),
         (2, t[0], t[1], t[2],t[3]),
         (3, t[0], t[1], t[2],t[3])]

cursor.executemany(sqllist, record)
sql.commit()
</code>```

I want to create three rows in the database with this list of information but is is only showing the last row of information in the database.

答:
Try this.</p>

```<code>import mysql.connector
sql = mysql.connector.connect(host='',user='',password='',db='')
cursor = sql.cursor()
f = open("C:\Cumulus\data\Apr19log.txt","r")
st=[i.strip().split(',') for i in f.readlines()]

sqllist = """INSERT INTO station_fenelon (variable, date, time, outside_temp, outside_humidity) VALUES (%s, %s, %s, %s, %s)"""

record = [(i+1, j[0], j[1], j[2], j[3]) for i, j in enumerate(st)]

cursor.executemany(sqllist, record)
sql.commit()
</code>```

Body:
I don't know how to insert a list of info into a mysql database.

I'm trying to insert rows data into a database but it is simply inserting the last row three times.  The list is named "t" and it is a tuple .

Data:

11/04/19,17:33,33.4,55
11/04/19,17:34,22.9,57
11/04/19,17:35,11.9,81

Code:

import mysql.connector

sql = mysql.connector.connect(
    host='    ',
    user='    ',
    password='    ',
    db="     "
    )
cursor = sql.cursor()

f = open("C:\Cumulus\data\Apr19log.txt","r")

while True:
    s = f.readline()
    list=[]
    if (s != ""):
        t=s.split(',')
        for item in t:
            list.append(item)
    else:
        break;

sqllist =    """INSERT INTO station_fenelon (variable, date,
time,outside_temp, outside_humidity)
                VALUES (%s, %s, %s, %s, %s)"""

record =[(1, t[0], t[1], t[2],t[3]),
         (2, t[0], t[1], t[2],t[3]),
         (3, t[0], t[1], t[2],t[3])]

cursor.executemany(sqllist, record)
sql.commit()

I want to create three rows in the database with this list of information but is is only showing the last row of information in the database.

Body:
Try this.

import mysql.connector
sql = mysql.connector.connect(host='',user='',password='',db='')
cursor = sql.cursor()
f = open("C:\Cumulus\data\Apr19log.txt","r")
st=[i.strip().split(',') for i in f.readlines()]

sqllist = """INSERT INTO station_fenelon (variable, date, time, outside_temp, outside_humidity) VALUES (%s, %s, %s, %s, %s)"""

record = [(i+1, j[0], j[1], j[2], j[3]) for i, j in enumerate(st)]

cursor.executemany(sqllist, record)
sql.commit()


来源: stackexchange

问:
Cordova SSL Handshake failed error on Android 7.0
I am using Cordova Android platform 5.2.2. Whenever I am performing SSL Checking on my Android N device I am facing the below error:

CONNECTION_FAILED. Details: Handshake failed.

From server side we are using TLS 1.0.
And in the app SSL Certificate Checker plugin version is 5.0.0.
Cordova version is 6.3.0

I think the issue is related to Android N network security configuration changes(Because I am getting the error in Android N devices only). I have added the certificates as per the changes in Android N behavioral changes. But getting the same error.

I have updated the Cordova Android platform to 6.1.2. But getting the same error.

In Android studio after running the application, after 1 minute later the below error is raised:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

As the app is developed using Apache Cordova, it does not follow the Java coding. We can not apply the changes mentioned in few blogs.

Can you please help me in this regard.
Thanks in advance.

答: Upgrading the TLS from 1.0 to 2.0 resolves the issue.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to vectorize this for loops in python?
Code is as below

import numpy as np

data = np.random.randint(0, 10, 12).reshape(3, 4)
print(data)

h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)

r = 2

for i in range(h):
    for j in range(w):
        for ir in range(i - r, i + r):
            for jr in range(j - r, j + r):
                if ir >= 0 and ir < h and jr >= 0 and jr < w:
                    dataMask[i, j, data[ir, jr]] += 1

print(dataMask)
```

I have a numpy array "data" with shape (h, w). Its elements is int number ∈[0, 10).

I create a array dataMask with shape (h, w, 10). dataMask[i, j, k] indicats the number of points whose value is k within an area in data. This area in data has center (i,j) and r = 2, and is a square.

How to vectorize those for loops in the code? Thank you!

答:
This is a "partially vectorized" solution that just iterates over the window size.

```<code>import numpy as np
from itertools import product

# Input data
np.random.seed(0)
data = np.random.randint(0, 10, 12).reshape(3, 4)
h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)
r = 2

# Original solution
for i in range(h):
    for j in range(w):
        for ir in range(i - r, i + r):
            for jr in range(j - r, j + r):
                if ir >= 0 and ir < h and jr >= 0 and jr < w:
                    dataMask[i, j, data[ir, jr]] += 1

# Partially vectorized solution
idx_i, idx_j = np.meshgrid(np.arange(h), np.arange(w), indexing='ij')
idx_i = idx_i.ravel()
idx_j = idx_j.ravel()
idx_k = data.ravel()
dataMask2 = np.zeros((h, w, 10), np.int)
for i, j in product(range(-r + 1, r + 1), repeat=2):
    ii = idx_i + i
    jj = idx_j + j
    m = (ii >= 0) & (ii < h) & (jj >= 0) & (jj < w)
    ii = ii[m]
    jj = jj[m]
    kk = idx_k[m]
    np.add.at(dataMask2, (ii, jj, kk), 1)

print(np.all(dataMask == dataMask2))
# True
</code>```

You can actually make this fully vectorized by just tiling the data more (which uses more memory):

```<code>import numpy as np

# Fully vectorized
idx_i, idx_j = np.meshgrid(np.arange(h), np.arange(w), indexing='ij')
w_i, w_j = np.meshgrid(np.arange(-r + 1, r + 1), np.arange(-r + 1, r + 1), indexing='ij')
ii = (idx_i[:, :, np.newaxis, np.newaxis] + w_i).ravel()
jj = (idx_j[:, :, np.newaxis, np.newaxis] + w_j).ravel()
kk = np.tile(data[:, :, np.newaxis, np.newaxis], (1, 1, 2 * r, 2 * r)).ravel()
m = (ii >= 0) & (ii < h) & (jj >= 0) & (jj < w)
ii = ii[m]
jj = jj[m]
kk = kk[m]
dataMask3 = np.zeros((h, w, 10), np.int)
np.add.at(dataMask3, (ii, jj, kk), 1)
print(np.all(dataMask == dataMask3))
# True
</code>```

Body:
Code is as below

import numpy as np

data = np.random.randint(0, 10, 12).reshape(3, 4)
print(data)

h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)

r = 2

for i in range(h):
    for j in range(w):
        for ir in range(i - r, i + r):
            for jr in range(j - r, j + r):
                if ir >= 0 and ir < h and jr >= 0 and jr < w:
                    dataMask[i, j, data[ir, jr]] += 1

print(dataMask)

I have a numpy array "data" with shape (h, w). Its elements is int number ∈[0, 10).

I create a array dataMask with shape (h, w, 10). dataMask[i, j, k] indicats the number of points whose value is k within an area in data. This area in data has center (i,j) and r = 2, and is a square.

How to vectorize those for loops in the code? Thank you!

Body:
This is a "partially vectorized" solution that just iterates over the window size.

import numpy as np
from itertools import product

# Input data
np.random.seed(0)
data = np.random.randint(0, 10, 12).reshape(3, 4)
h, w = data.shape[:2]
dataMask = np.zeros((h, w, 10), np.int)
r = 2

# Original solution
for i in range(h):
    for j in range(w):
        for ir in range(i - r, i + r):
            for jr in range(j - r, j + r):
                if ir >= 0 and ir < h and jr >= 0 and jr < w:
                    dataMask[i, j, data[ir, jr]] += 1

# Partially vectorized solution
idx_i, idx_j = np.meshgrid(np.arange(h), np.arange(w), indexing='ij')
idx_i = idx_i.ravel()
idx_j = idx_j.ravel()
idx_k = data.ravel()
dataMask2 = np.zeros((h, w, 10), np.int)
for i, j in product(range(-r + 1, r + 1), repeat=2):
    ii = idx_i + i
    jj = idx_j + j
    m = (ii >= 0) & (ii < h) & (jj >= 0) & (jj < w)
    ii = ii[m]
    jj = jj[m]
    kk = idx_k[m]
    np.add.at(dataMask2, (ii, jj, kk), 1)

print(np.all(dataMask == dataMask2))
# True

You can actually make this fully vectorized by just tiling the data more (which uses more memory):

import numpy as np

# Fully vectorized
idx_i, idx_j = np.meshgrid(np.arange(h), np.arange(w), indexing='ij')
w_i, w_j = np.meshgrid(np.arange(-r + 1, r + 1), np.arange(-r + 1, r + 1), indexing='ij')
ii = (idx_i[:, :, np.newaxis, np.newaxis] + w_i).ravel()
jj = (idx_j[:, :, np.newaxis, np.newaxis] + w_j).ravel()
kk = np.tile(data[:, :, np.newaxis, np.newaxis], (1, 1, 2 * r, 2 * r)).ravel()
m = (ii >= 0) & (ii < h) & (jj >= 0) & (jj < w)
ii = ii[m]
jj = jj[m]
kk = kk[m]
dataMask3 = np.zeros((h, w, 10), np.int)
np.add.at(dataMask3, (ii, jj, kk), 1)
print(np.all(dataMask == dataMask3))
# True


问:
Button styles are are not possible to change in ionic 3 project
When I try to change ionic button styles on these components even by using !important or using new custom classes it doesn't change anything. Here is the code:

```<code><ion-content padding>
    <ion-list>
        <button ion-button block class=" custbtnnew" (click)=" SelectImage()">
            Select
        </button>
        <br>
        <button style="margin-top:20px;" ion-button block class="custbtnnew" (click)="UploadImage()">
            Upload
        </button>
    </ion-list>
    <div *ngIf="images" class="group">
        <ion-grid>
            <ion-row>
                <ion-col col-6 col-md-4 col-lg-3 col-xl-2 class="created_group" *ngFor="let image of images">
                    <div class="container">
                        <div class="imgs">
                            <img class="imgBg"
                                src="URL">
                            <button *ngIf="images" ion-button clear (click)="SetProfileImage(image)" class="imgBtn">
                                Set As Default
                            </button>
                            <button *ngIf="images" ion-button clear (click)="Delete(image)" class="imgBtn">
                                Delete Image
                            </button>
                        </div>
                    </div>
                </ion-col>
            </ion-row>
        </ion-grid>
    </div>
</ion-content>
</code>```

CSS

```<code> .custbtnnew {
    border-radius: 40px !important;
    background: -webkit-gradient(linear, left top, right top, from(#DD2476), to(#FF512F));
    background: linear-gradient(to right, #DD2476, #FF512F);
  }
</code>```

What can cause such an issue and how can be it get changed?

答:
you may need a page declaration around your .scss

```<code>page-home {
 .custbtnnew {
    border-radius: 40px !important;
    background: -webkit-gradient(linear, left top, right top, from(#DD2476), to(#FF512F));
    background: linear-gradient(to right, #DD2476, #FF512F);
  }
}
</code>```

Body:
When I try to change ionic button styles on these components even by using !important or using new custom classes it doesn't change anything. Here is the code:

<ion-content padding>
    <ion-list>
        <button ion-button block class=" custbtnnew" (click)=" SelectImage()">
            Select
        </button>

        <button style="margin-top:20px;" ion-button block class="custbtnnew" (click)="UploadImage()">
            Upload
        </button>
    </ion-list>

        <ion-grid>
            <ion-row>
                <ion-col col-6 col-md-4 col-lg-3 col-xl-2 class="created_group" *ngFor="let image of images">

                            <button *ngIf="images" ion-button clear (click)="SetProfileImage(image)" class="imgBtn">
                                Set As Default
                            </button>
                            <button *ngIf="images" ion-button clear (click)="Delete(image)" class="imgBtn">
                                Delete Image
                            </button>

                </ion-col>
            </ion-row>
        </ion-grid>

</ion-content>

CSS

 .custbtnnew {
    border-radius: 40px !important;
    background: -webkit-gradient(linear, left top, right top, from(#DD2476), to(#FF512F));
    background: linear-gradient(to right, #DD2476, #FF512F);
  }

What can cause such an issue and how can be it get changed?

Body:
you may need a page declaration around your .scss

page-home {
 .custbtnnew {
    border-radius: 40px !important;
    background: -webkit-gradient(linear, left top, right top, from(#DD2476), to(#FF512F));
    background: linear-gradient(to right, #DD2476, #FF512F);
  }
}


问:
Wordpress: Custom post type single page shows index page instead
I've have tried to make my first wordpress theme and I have some trouble with my single pages for my blog.
[my blog page][1]

It is a custom post type, that I created called blog_post.
The weird this seems to happen only when it is on a sublayer of my site ex. {url}/blog_post/ here the page looks just like my index page.

But on my work page there isn't any problem with my single pages, and their permalink doesn't have a {url}/work_post/ attach to them.
[my work page][2]

I created the special styling of my single pages with functions.php file

```<code>define(SINGLE_PATH, TEMPLATEPATH . '/single');

/**
* Filter the single_template with our custom function
*/
add_filter('single_template', 'my_single_template');

/**
* Single template function which will choose our template
*/
function my_single_template($single) {
global $wp_query, $post;

/**
* Checks for single template by category
* Check by category slug and ID
*/
foreach((array)get_the_category() as $cat) :

if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';

elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';
/*                                                                                <-------- if no single-cat page is found the return the single.php file
*/
elseif(file_exists(SINGLE_PATH . '/single.php'))
return SINGLE_PATH . '/single.php';

endforeach;
}
</code>```

I hope someone can make sense of my mess :D

答: For me it worked to add 'publicly_queryable' => true to the arguments of registering the post_type. I originally had to setting set to false.

Body:
I've have tried to make my first wordpress theme and I have some trouble with my single pages for my blog.
[my blog page][1]

It is a custom post type, that I created called blog_post.
The weird this seems to happen only when it is on a sublayer of my site ex. {url}/blog_post/ here the page looks just like my index page.

But on my work page there isn't any problem with my single pages, and their permalink doesn't have a {url}/work_post/ attach to them.
[my work page][2]

I created the special styling of my single pages with functions.php file

define(SINGLE_PATH, TEMPLATEPATH . '/single');

/**
* Filter the single_template with our custom function
*/
add_filter('single_template', 'my_single_template');

/**
* Single template function which will choose our template
*/
function my_single_template($single) {
global $wp_query, $post;

/**
* Checks for single template by category
* Check by category slug and ID
*/
foreach((array)get_the_category() as $cat) :

if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';

elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';
/*                                                                                <-------- if no single-cat page is found the return the single.php file
*/
elseif(file_exists(SINGLE_PATH . '/single.php'))
return SINGLE_PATH . '/single.php';

endforeach;
}

I hope someone can make sense of my mess :D


问:
Making an Angular Material data table rows scroll while maintaining a sticky a header
Stack Blitz Demo

I am having trouble figuring out how to get my code to behave as needed.

As the demo shows I have a table that when the add button is clicked a new row is added. Once the table rows reach a certain height (say for example after adding 5 rows) I need a vertical scroll bar to display and at the same time I need to maintain a sticky header. Basically I need to set the table rows to a fixed height.

The attached screen shot shows where I would like the scroll bar to display. Apologies for the shaky highlight.

The HTML looks looks like this

```<code><div class="table-container">
  <table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="category">
      <th mat-header-cell *matHeaderCellDef >Category</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="code">
          <mat-select>
            <mat-option *ngFor=" let category of categories" [value]="category.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{category.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef>Type</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="type">
          <mat-select >
            <mat-option *ngFor=" let type of types" [value]="type.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{type.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="additionalCode" class="parent" >
      <th mat-header-cell *matHeaderCellDef>Additional Code</th>
      <td mat-cell *matCellDef="let element" class="parent" >
        <mat-form-field class="type">
          <input matInput (keyup)="toggleLookup($event)" autocomplete="off" (keydown.ArrowDown)="onDown()">
        </mat-form-field>
        <div *ngIf="expanded" class="child">Yah it expanded
          <button (click)="expanded = false">Close</button>
        </div>
      </td>
    </ng-container>
    <ng-container matColumnDef="ref">
      <th mat-header-cell *matHeaderCellDef>Reference</th>
      <td mat-cell *matCellDef="let element" >
        <mat-form-field>
          <input matInput [(ngModel)]="element.type"  (keydown.ArrowDown)="onDown()" autocomplete="off">
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="add">
      <th mat-header-cell *matHeaderCellDef>
        <button mat-icon-button (click)="addRow()" matTooltip="Add Row">
          <mat-icon>add</mat-icon>
        </button>
      </th>
      <td mat-cell *matCellDef="let code; let i = index;">
        <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove Row">
          <mat-icon>clear</mat-icon>
        </button>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="columns"></tr>
    <tr mat-row *matRowDef="let rows; columns: columns;"></tr>
  </table>
   <div *ngIf="dataSource.filteredData.length > 0" > <mat-paginator [pageSizeOptions]="[5]" showFirstLastButtons class="paginator"></mat-paginator></div>
</div>
</code>```

Component Add Function

```<code>addRow() {
    this.doAddRow();
    this.expanded = false;
  }
  private doAddRow() {
    ELEMENT_DATA.push({ code: '', type: '', reference: '' });
    this.dataSource = new MatTableDataSource(ELEMENT_DATA);
  }
</code>```

答:
Actually, Angular Material documentation has covered that.

By using position: sticky styling, the table's rows and columns can be
  fixed so that they do not leave the viewport even when scrolled. The
  table provides inputs that will automatically apply the correct CSS
  styling so that the rows and columns become sticky.

You just need to make the following changes to your
 tag with the mat-header-row directive.

```<code><tr mat-header-row *matHeaderRowDef="columns; sticky: true"></tr>
</code>```

In addition, you will need to edit your container class around your table to include the following properties:

```<code>.table-container {
  height: 400px;
  overflow: auto;
  /*
  other CSS properties
   */
}
</code>```

This will allow your material datatable to have a sticky header. Here is the demo provided by the official documentation.

Body:
Stack Blitz Demo

I am having trouble figuring out how to get my code to behave as needed.

As the demo shows I have a table that when the add button is clicked a new row is added. Once the table rows reach a certain height (say for example after adding 5 rows) I need a vertical scroll bar to display and at the same time I need to maintain a sticky header. Basically I need to set the table rows to a fixed height.

The attached screen shot shows where I would like the scroll bar to display. Apologies for the shaky highlight.

The HTML looks looks like this

    <ng-container matColumnDef="category">
      Category

        <mat-form-field class="code">
          <mat-select>
            <mat-option *ngFor=" let category of categories" [value]="category.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{category.code}}</mat-option>
          </mat-select>
        </mat-form-field>

    </ng-container>
    <ng-container matColumnDef="type">
      Type

        <mat-form-field class="type">
          <mat-select >
            <mat-option *ngFor=" let type of types" [value]="type.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{type.code}}</mat-option>
          </mat-select>
        </mat-form-field>

    </ng-container>
    <ng-container matColumnDef="additionalCode" class="parent" >
      Additional Code

        <mat-form-field class="type">
          <input matInput (keyup)="toggleLookup($event)" autocomplete="off" (keydown.ArrowDown)="onDown()">
        </mat-form-field>

Yah it expanded
          <button (click)="expanded = false">Close</button>

    </ng-container>
    <ng-container matColumnDef="ref">
      Reference

        <mat-form-field>
          <input matInput [(ngModel)]="element.type"  (keydown.ArrowDown)="onDown()" autocomplete="off">
        </mat-form-field>

    </ng-container>
    <ng-container matColumnDef="add">

        <button mat-icon-button (click)="addRow()" matTooltip="Add Row">
          <mat-icon>add</mat-icon>
        </button>

        <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove Row">
          <mat-icon>clear</mat-icon>
        </button>

    </ng-container>

 0" > <mat-paginator [pageSizeOptions]="[5]" showFirstLastButtons class="paginator"></mat-paginator>

Component Add Function

addRow() {
    this.doAddRow();
    this.expanded = false;
  }
  private doAddRow() {
    ELEMENT_DATA.push({ code: '', type: '', reference: '' });
    this.dataSource = new MatTableDataSource(ELEMENT_DATA);
  }

Body:
Actually, Angular Material documentation has covered that.

By using position: sticky styling, the table's rows and columns can be
  fixed so that they do not leave the viewport even when scrolled. The
  table provides inputs that will automatically apply the correct CSS
  styling so that the rows and columns become sticky.

You just need to make the following changes to your <tr> tag with the mat-header-row directive.

<tr mat-header-row *matHeaderRowDef="columns; sticky: true"></tr>

In addition, you will need to edit your container class around your table to include the following properties:

.table-container {
  height: 400px;
  overflow: auto;
  /*
  other CSS properties
   */
}

This will allow your material datatable to have a sticky header. Here is the demo provided by the official documentation.


问:
Get count of array objects belonging to a partical ID in JavaScript/Node js
I have an array of arrays like this:

```<code>var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]
</code>```

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

```<code>[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]
</code>```

Note that the output is in the ascending order of the Count.

This is what I tried :

```<code>var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)
</code>```

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?

答:
You can try this.

var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
];

var y = {};
var z = [];
array.forEach(x=>{      //creating object which will store freq of Id
  if(!y[x[0]]){
    y[x[0]] = 0;
  }
  y[x[0]]++;
});
Object.keys(y).forEach(x=>{   //converting above object to array
  z.push({'ID': x, 'Count':y[x]});
});
console.log(z.sort((a,b) => a.Count - b.Count))//sorting array as per requirement```

Body:
I have an array of arrays like this:

var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]

Note that the output is in the ascending order of the Count.

This is what I tried :

var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?


问:
How do I setState id when name is selected in the picker dropdown?
I have a json array in the below format

```<code>  this.state = {
    allTeachers: [
        {
            "id": "qKUd5GoBwpolnxM4upjo",
            "name": "XYZ",
            "subject": "Science"
        },
        {
            "id": "qaUe5GoBwkrtnxM4kOip",
            "name": "Vidya",
            "subject": "Mathematics"
        }
    ]
  }
</code>```

And I am using the below code for dropdown. Now I am able to setState the name, but I want to show name in dropdown, and setstate the respective id of the name selected. I am using react-native picker. How can I do this?

```<code><View style ={styles.dropdownInput}>
{
    <Picker
        selectedValue={this.state.teacher_name}
        style={styles.pickerCss}
        onValueChange={(itemValue, itemIndex) => this.setState({teacher_name: itemValue})}
    >
    <Picker.Item label='Select Teacher' value='0' />
    {
        this.state.allteachers ?
            this.state.allteachers.map((item,key) => (
                <Picker.Item label={item.name} value={item.name} />
            ))
        :
        false
    }
    </Picker>
}
</View>
</code>```

答:
You just need to set the PickerItem's value to the respective id.
That means change:

```<code><Picker.Item label={item.name} value={item.name} />
</code>```

to

```<code><Picker.Item label={item.name} value={item.id} />
</code>```

Now

```<code>onValueChange={(itemValue, itemIndex) => this.setState({teacher_name: itemValue})}
</code>```

stores the teacher_id in the teacher_name state variable. You could create a new state variable called teacher_id in your constructor and store the id there.

In addition, I would recommend a small refactoring.
Instead of:

```<code>{
    // btw here is a typo your array is called allTeachers
    this.state.allteachers ?
        this.state.allteachers.map((item,key) => (
            <Picker.Item label={item.name} value={item.name} />
        ))
    :
    false
}
</code>```

I would create a renderPickterItems function:

```<code>renderPickerItems(allTeachers){
    if (allTeachers) {
       return(
        allTeachers.map((item,key) => (
        <Picker.Item label={item.name} value={item.id} />
        ))
    );
    }
  }
</code>```

which you can call with:

```<code> <Picker.Item label='Select Teacher' value='0' />
    {this.renderPickerItems(this.state.allTeachers)}
 </Picker>
</code>```

Complete Working Example:

https://snack.expo.io/HJwLcXT6E

Body:
I have a json array in the below format

  this.state = {
    allTeachers: [
        {
            "id": "qKUd5GoBwpolnxM4upjo",
            "name": "XYZ",
            "subject": "Science"
        },
        {
            "id": "qaUe5GoBwkrtnxM4kOip",
            "name": "Vidya",
            "subject": "Mathematics"
        }
    ]
  }

And I am using the below code for dropdown. Now I am able to setState the name, but I want to show name in dropdown, and setstate the respective id of the name selected. I am using react-native picker. How can I do this?

<View style ={styles.dropdownInput}>
{
    <Picker
        selectedValue={this.state.teacher_name}
        style={styles.pickerCss}
        onValueChange={(itemValue, itemIndex) => this.setState({teacher_name: itemValue})}
    >
    <Picker.Item label='Select Teacher' value='0' />
    {
        this.state.allteachers ?
            this.state.allteachers.map((item,key) => (
                <Picker.Item label={item.name} value={item.name} />
            ))
        :
        false
    }
    </Picker>
}
</View>

Body:
You just need to set the PickerItem's value to the respective id.
That means change:

<Picker.Item label={item.name} value={item.name} />

to

<Picker.Item label={item.name} value={item.id} />

Now

onValueChange={(itemValue, itemIndex) => this.setState({teacher_name: itemValue})}

stores the teacher_id in the teacher_name state variable. You could create a new state variable called teacher_id in your constructor and store the id there.

In addition, I would recommend a small refactoring.
Instead of:

{
    // btw here is a typo your array is called allTeachers
    this.state.allteachers ?
        this.state.allteachers.map((item,key) => (
            <Picker.Item label={item.name} value={item.name} />
        ))
    :
    false
}

I would create a renderPickterItems function:

renderPickerItems(allTeachers){
    if (allTeachers) {
       return(
        allTeachers.map((item,key) => (
        <Picker.Item label={item.name} value={item.id} />
        ))
    );
    }
  }

which you can call with:

 <Picker.Item label='Select Teacher' value='0' />
    {this.renderPickerItems(this.state.allTeachers)}
 </Picker>

Complete Working Example:

https://snack.expo.io/HJwLcXT6E


问:
Toast in OnPostExecute() once the fragment changes
I have two fragments in my Activity : Fragment_A and Fragment_B.

In Fragment A, I created an AsyncTask (when the user "swipeRefreshes" the screen). In the onPostExecute() of this task, I want to display a Toast :

```<code>private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
    private Exception mLastError = null;

    MakeRequestTask() {
        //Some stuff
    }

    @Override
    protected List<String> doInBackground(Void... params) {
        //Some stuff
    }

    @Override
    protected void onPreExecute() {
        //Some stuff
    }

    @Override
    protected void onPostExecute(List<String> output) {
        swipeRefreshLayout.setRefreshing(false);
        Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCancelled() {
        swipeRefreshLayout.setRefreshing(false);
        //Some stuff
    }
}
</code>```

If the user changes from Fragment_A to Fragment_B before the AsyncTask finishes, I get a crash:

java.lang.IllegalStateException: Fragment Fragment_A not attached to a context.

I know how to avoid the crash (by adding the condition isAdded()), but I want my Toast to be displayed no matter which Fragment is displayed/alive on top of my Activity.

答:
1stly I would like to suggest you, please make your MakeRequestTask inner class as static as this can be a memory leak.
For your question, You need to pass the context to the class like below:</p>

```<code>    private static class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
        private Exception mLastError = null;
        private WeakReference<Context> weakReference;

        MakeRequestTask(Context context) {
            //Some stuff
            weakReference = new WeakReference<>(context);
        }

        @Override
        protected List<String> doInBackground(Void... params) {
            //Some stuff
        }

        @Override
        protected void onPreExecute() {
            //Some stuff
        }

        @Override
        protected void onPostExecute(List<String> output) {
// swipe layout will not be shown if fragment is not visible or destroyed
            if (isFragmentVisible) {
                swipeRefreshLayout.setRefreshing(false);
            }
// toast will be shown no matter what fragment is visible
            if (weakReference != null) {
                Context context = weakReference.get();
                if (context != null) {
                    Toast.makeText(context, "TO_DISPLAY", Toast.LENGTH_SHORT).show();
                }
            }
        }

        @Override
        protected void onCancelled() {
            if (isFragmentVisible) {
                swipeRefreshLayout.setRefreshing(false);
            }
            //Some stuff
        }
    }
</code>```

Body:
I have two fragments in my Activity : Fragment_A and Fragment_B.

In Fragment A, I created an AsyncTask (when the user "swipeRefreshes" the screen). In the onPostExecute() of this task, I want to display a Toast :

private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
    private Exception mLastError = null;

    MakeRequestTask() {
        //Some stuff
    }

    @Override
    protected List<String> doInBackground(Void... params) {
        //Some stuff
    }

    @Override
    protected void onPreExecute() {
        //Some stuff
    }

    @Override
    protected void onPostExecute(List<String> output) {
        swipeRefreshLayout.setRefreshing(false);
        Toast.makeText(getActivity(), "TO_DISPLAY", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCancelled() {
        swipeRefreshLayout.setRefreshing(false);
        //Some stuff
    }
}

If the user changes from Fragment_A to Fragment_B before the AsyncTask finishes, I get a crash:

java.lang.IllegalStateException: Fragment Fragment_A not attached to a context.

I know how to avoid the crash (by adding the condition isAdded()), but I want my Toast to be displayed no matter which Fragment is displayed/alive on top of my Activity.

Body:
1stly I would like to suggest you, please make your MakeRequestTask inner class as static as this can be a memory leak.
For your question, You need to pass the context to the class like below:

    private static class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
        private Exception mLastError = null;
        private WeakReference<Context> weakReference;

        MakeRequestTask(Context context) {
            //Some stuff
            weakReference = new WeakReference<>(context);
        }

        @Override
        protected List<String> doInBackground(Void... params) {
            //Some stuff
        }

        @Override
        protected void onPreExecute() {
            //Some stuff
        }

        @Override
        protected void onPostExecute(List<String> output) {
// swipe layout will not be shown if fragment is not visible or destroyed
            if (isFragmentVisible) {
                swipeRefreshLayout.setRefreshing(false);
            }
// toast will be shown no matter what fragment is visible
            if (weakReference != null) {
                Context context = weakReference.get();
                if (context != null) {
                    Toast.makeText(context, "TO_DISPLAY", Toast.LENGTH_SHORT).show();
                }
            }
        }

        @Override
        protected void onCancelled() {
            if (isFragmentVisible) {
                swipeRefreshLayout.setRefreshing(false);
            }
            //Some stuff
        }
    }


问:
Gradle .execute method showing error after gradle update
My project was running perfect with gradle plugin version 3.0.1 after updating to version 3.4.1 I am going through sync failure.

Previously I was using wrapper 4.10.1 which is now updated to 5.1.1.

```<code>afterEvaluate(new Action<Project>() {

@Override
void execute(Project project) {
    tasks.getByName("assembleRelease").doLast {
        tasks.copyReleaseBuild.execute() //error is here
        tasks.copyReleaseBuildToXX.execute()
        tasks.copyReleaseBuildToXXXX.execute()
    }
}
</code>```

copyReleaseBuild task is written something like below...

```<code>task copyReleaseBuild(type: Copy) {
    def releaseDir = getProjectProperty('releaseDir')
    if (releaseDir?.trim()) {
    //if release folder is provided
    def releaseAarFile =
            getProjectProperty('sourceCodeDir') + "/android-corekit/kit/build/outputs/aar/kit-release.aar"
    from releaseAarFile
    into releaseDir
    }

task copyReleaseBuildToXX(type: Copy) {
        from "./build/outputs/aar/kit-release.aar"
        into "../kitwrapper/libs"
    }

task copyReleaseBuildToXXXX(type: Copy) {
        from "./build/outputs/aar/kit-release.aar"
        into "../kitwrapperapp/libs"
    }
}
</code>```

I have been trying to resolve from last two days but nothing is working as I lack knowledge of groovy.

Please check error log I am getting while building the project...

答:
Upgrading your build from Gradle 4.x to 5.0

The following properties and methods of TaskInternal have been removed — use task dependencies, task rules, reusable utility methods, or the Worker API in place of executing a task directly.

execute()

executer

getValidators()

addValidator()

in your case seems you have dependency between tasks: copyReleaseBuild must run after assembleRelease

so, this simple build.gradle represents this dependency:

```<code>task copyReleaseBuild {
    dependsOn 'assembleRelease'
    doLast {
        println 'run copyReleaseBuild'
    }
}
task assembleRelease {
    doLast {
        println 'run assembleRelease'
    }
}
</code>```

and the command gradle copyReleaseBuild
runs both tasks:

# gradle copyReleaseBuild

> Task :assembleRelease
run assembleRelease

> Task :copyReleaseBuild
run copyReleaseBuild

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed
```

Body:
My project was running perfect with gradle plugin version 3.0.1 after updating to version 3.4.1 I am going through sync failure.

Previously I was using wrapper 4.10.1 which is now updated to 5.1.1.

afterEvaluate(new Action<Project>() {

@Override
void execute(Project project) {
    tasks.getByName("assembleRelease").doLast {
        tasks.copyReleaseBuild.execute() //error is here
        tasks.copyReleaseBuildToXX.execute()
        tasks.copyReleaseBuildToXXXX.execute()
    }
}

copyReleaseBuild task is written something like below...

task copyReleaseBuild(type: Copy) {
    def releaseDir = getProjectProperty('releaseDir')
    if (releaseDir?.trim()) {
    //if release folder is provided
    def releaseAarFile =
            getProjectProperty('sourceCodeDir') + "/android-corekit/kit/build/outputs/aar/kit-release.aar"
    from releaseAarFile
    into releaseDir
    }

task copyReleaseBuildToXX(type: Copy) {
        from "./build/outputs/aar/kit-release.aar"
        into "../kitwrapper/libs"
    }

task copyReleaseBuildToXXXX(type: Copy) {
        from "./build/outputs/aar/kit-release.aar"
        into "../kitwrapperapp/libs"
    }
}

I have been trying to resolve from last two days but nothing is working as I lack knowledge of groovy.

Please check error log I am getting while building the project...

Body:
Upgrading your build from Gradle 4.x to 5.0

The following properties and methods of TaskInternal have been removed — use task dependencies, task rules, reusable utility methods, or the Worker API in place of executing a task directly.

execute()

executer

getValidators()

addValidator()

in your case seems you have dependency between tasks: copyReleaseBuild must run after assembleRelease

so, this simple build.gradle represents this dependency:

task copyReleaseBuild {
    dependsOn 'assembleRelease'
    doLast {
        println 'run copyReleaseBuild'
    }
}
task assembleRelease {
    doLast {
        println 'run assembleRelease'
    }
}

and the command gradle copyReleaseBuild
runs both tasks:

# gradle copyReleaseBuild

> Task :assembleRelease
run assembleRelease

> Task :copyReleaseBuild
run copyReleaseBuild

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed


问:
How to send data to Stripe nodejs express backend
I tried integrating Stripe into my React app using the official doc at https://stripe.com/docs/recipes/elements-react. If you could go through this doc, you'll find out they're using a static value as amount (2000).

```<code>// server.js

const app = require("express")();
const stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7dc");

app.use(require("body-parser").text());

 app.post("/charge", async (req, res) => {
  try {
    let {status} = await stripe.charges.create({
      amount: 2000,
      currency: "usd",
      description: "An example charge",
      source: req.body
    });

    res.json({status});
  } catch (err) {
    res.status(500).end();
  }
});

</code>```

The post API from frontend using fetch is:

```<code>async submit(ev) {
  let {token} = await this.props.stripe.createToken({name: "Name"});
  let response = await fetch("/charge", {
    method: "POST",
    headers: {"Content-Type": "text/plain"},
    body: token.id
  });

  if (response.ok) console.log("Purchase Complete!")
}
</code>```

Here, they're sending the token ID and referencing it in the backend as source:req.body.

Now I have tried to send amount from the frontend through the POST request as follows:

```<code>body:{
  amount: 2000,
  tokenId: token.Id
}
</code>```

and then referencing it in backend as

```<code>...
amount: req.body.amount,
source: req.body.tokenid
...
</code>```

It doesn't work. And consoling both returns undefined

I have tried many things like removing content-type header and pretty little things. Someone pointed out that I should change content-type to application/json and I've thought of setting
app.use(require("body-parser").text()) to app.use(require("body-parser").json()) but decided to consult you guys first.

答:
If I understand you correctly, you want to post a json from client to express server. If so:

Client

fetch({
  method: 'POST',
  body: JSON.stringify({
    amount: 2000,
    tokenId: token.Id
  }),
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
});
```

<p><strong>Server</strong></p>

<pre class="lang-js prettyprint-override"><code>const app = express();
// if express >= 4
app.use(express.json());

app.post("/charge", async (req, res) => {
  console.log(req.body);
});
</code>```

Any by the way tokenId !== tokenid (in req.body.tokenid)

Body:
I tried integrating Stripe into my React app using the official doc at https://stripe.com/docs/recipes/elements-react. If you could go through this doc, you'll find out they're using a static value as amount (2000).

// server.js

const app = require("express")();
const stripe = require("stripe")("sk_test_4eC39HqLyjWDarjtT1zdp7dc");

app.use(require("body-parser").text());

 app.post("/charge", async (req, res) => {
  try {
    let {status} = await stripe.charges.create({
      amount: 2000,
      currency: "usd",
      description: "An example charge",
      source: req.body
    });

    res.json({status});
  } catch (err) {
    res.status(500).end();
  }
});

The post API from frontend using fetch is:

async submit(ev) {
  let {token} = await this.props.stripe.createToken({name: "Name"});
  let response = await fetch("/charge", {
    method: "POST",
    headers: {"Content-Type": "text/plain"},
    body: token.id
  });

  if (response.ok) console.log("Purchase Complete!")
}

Here, they're sending the token ID and referencing it in the backend as source:req.body.

Now I have tried to send amount from the frontend through the POST request as follows:

body:{
  amount: 2000,
  tokenId: token.Id
}

and then referencing it in backend as

...
amount: req.body.amount,
source: req.body.tokenid
...

It doesn't work. And consoling both returns undefined

I have tried many things like removing content-type header and pretty little things. Someone pointed out that I should change content-type to application/json and I've thought of setting
app.use(require("body-parser").text()) to app.use(require("body-parser").json()) but decided to consult you guys first.

Body:
If I understand you correctly, you want to post a json from client to express server. If so:

Client

fetch({
  method: 'POST',
  body: JSON.stringify({
    amount: 2000,
    tokenId: token.Id
  }),
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
});

Server

const app = express();
// if express >= 4
app.use(express.json());

app.post("/charge", async (req, res) => {
  console.log(req.body);
});

Any by the way tokenId !== tokenid (in req.body.tokenid)


问:
Conda does not work anymore after installing Jupyter Hub
I've installed jupyter-hub on my machine that was running smoothly with jupyter-lab, conda and python3.6.

```<code>conda install -c conda-forge jupyterhub
</code>```

Now conda seems to not work anymore giving this error:

```<code>[pas.datascience_dev@devrmdatasci01 site-packages]$ conda
Traceback (most recent call last):
  File "/data/pyconda3/bin/conda", line 12, in <module>
    from conda.cli import main
ModuleNotFoundError: No module named 'conda'
</code>```

Now if i run python, it seems to use python3.7 packaged by conda-forge

```<code>[pas.datascience_dev@devrmdatasci01 python3.6]$ python
Python 3.7.3 | packaged by conda-forge | (default, Mar 27 2019, 23:01:00)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code>```

If i go to my python installation path i can see both a directory python3.6 and a directory python3.7, the first contain correctly conda and all other packages i was using, the other none

How can i revert, disintall python3.7 or stop using it and recode all to use the old python3.6 that was working correctly?

答:
I'm no expert in this, but you can always uninstall python and reinstall it, although I don't know if it keeps the libraries you've downloaded.

my suggestion is run pip install conda, although I'm not sure how it works on Linux.

Body:
I've installed jupyter-hub on my machine that was running smoothly with jupyter-lab, conda and python3.6.

conda install -c conda-forge jupyterhub

Now conda seems to not work anymore giving this error:

[pas.datascience_dev@devrmdatasci01 site-packages]$ conda
Traceback (most recent call last):
  File "/data/pyconda3/bin/conda", line 12, in <module>
    from conda.cli import main
ModuleNotFoundError: No module named 'conda'

Now if i run python, it seems to use python3.7 packaged by conda-forge

[pas.datascience_dev@devrmdatasci01 python3.6]$ python
Python 3.7.3 | packaged by conda-forge | (default, Mar 27 2019, 23:01:00)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

If i go to my python installation path i can see both a directory python3.6 and a directory python3.7, the first contain correctly conda and all other packages i was using, the other none

How can i revert, disintall python3.7 or stop using it and recode all to use the old python3.6 that was working correctly?


问:
Qt - Why won't my widgets line up using a vertical layout inside a splitter?
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

```<code>/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H
</code>```

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.

答:
make sure verticalLayout has no margin (which it has by default).

verticalLayout->setContentsMargins(0, 0, 0, 0);

Body:
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.


问:
Angular child form control/group values and errors bubbling up to parent
My requirement: A single FormControl must contain the answer of multiple inputs (multiple child FormControls or FormGroups).

That is because multiple controls must feed into the top level (parent) FormControl, and the value of the parent level FormControl must be filtered/manipulated to fit the required format.

A good example would be a split up phone input, with a Country code dropdown, phone number input, and extension input, all being separate from one another, but together in a FormGroup. As any of those input values change, the parent level FormControl value must change as well.

In addition to the values bubbling up, the errors of the child controls must bubble up to the parent FormControl too.

Right now I have the parent FormControl listening to the value changes of a FormGroup with the country code, phone number, and extension inputs. Then, using ControlValueAccessor on a component, that writes the value of the parent FormControl when FormGroup ValueChanges.

I need a way to achieve the desired outcome, but also a way to do even more complex controls and FormGroups. Think multiple degrees of nested FormControls and/or FormGroups.

Environment

Angular 7

Material 7

NGRX 6

答:
Initially trying to come up with a nice solution to handle breaking down huge forms into sub forms (sub components...), we came up with a solution for that but also to have access to nested errors.

We've build a library for that https://github.com/cloudnc/ngx-sub-form that will give you way more than just access to nested errors and you can check the official demo here: https://cloudnc.github.io/ngx-sub-form/listings/new (edit the form and see the errors displayed)

I've also replied to a similar SO question here https://stackoverflow.com/a/56375605/2398593 and built a demo for that question here (which also showcase the nested errors functionality) https://stackblitz.com/edit/so-question-angular-2-large-scale-application-forms-handling

Hope it helps!

Edit:

If you want to go further, I've just published a blog post to explain a lot of things about forms and ngx-sub-form here https://dev.to/maxime1992/building-scalable-robust-and-type-safe-forms-with-angular-3nf9


问:
How do i display data passed from viewbag in controller to view
I have tried to display using @(foreach var x in viewbag.data2) loop in view

```<code> var data = from c in _context.Posts
                       join p in _context.PostViewCount on c.Id equals p.PostId
                       select new
                       {
                           posts = c,
                           p.Count,
                           c.Title,
                           p.PostId

                       };
            var dat = data.OrderByDescending(x=>x.Count).ToList();
            ViewBag.data2 = dat;
</code>```

I m getting invalid operation exception

答:
You got your syntax a little wrong.

it should be:

```<code>@foreach(var x in ViewBag.data2){

    @x.Count
    @x.Title

}
</code>```

Edit: As there seems to be a little bit of confusion with dynamic types. This example shows how to use a defined model..

Create a class for your data rather than using an anonymous object.

```<code>public class PostsModel
{
    public string Title { get; set; }
    public int Count { get; set; }
    // etc...
}
</code>```

Modify your query...

```<code>var data = from c in _context.Posts
                   join p in _context.PostViewCount on c.Id equals p.PostId
                   select new PostsModel
                   {
                       Count = p.Count,
                       Title = c.Title,
                       // etc...
                   };
        var dat = data.OrderByDescending(x=>x.Count).ToList();
        ViewBag.data2 = dat;
</code>```

Then just cast your Viewbag variable to the right type...

```<code>@foreach(PostsModel x in ((IEnumerable<PostsModel>)ViewBag.data2)){

    @x.Count
    @x.Title

}
</code>```

You might have to import the right namespace to your view by using: @using <namespace>

Body:
I have tried to display using @(foreach var x in viewbag.data2) loop in view

 var data = from c in _context.Posts
                       join p in _context.PostViewCount on c.Id equals p.PostId
                       select new
                       {
                           posts = c,
                           p.Count,
                           c.Title,
                           p.PostId

                       };
            var dat = data.OrderByDescending(x=>x.Count).ToList();
            ViewBag.data2 = dat;

I m getting invalid operation exception

Body:
You got your syntax a little wrong.

it should be:

@foreach(var x in ViewBag.data2){

    @x.Count
    @x.Title

}

Edit: As there seems to be a little bit of confusion with dynamic types. This example shows how to use a defined model..

Create a class for your data rather than using an anonymous object.

public class PostsModel
{
    public string Title { get; set; }
    public int Count { get; set; }
    // etc...
}

Modify your query...

var data = from c in _context.Posts
                   join p in _context.PostViewCount on c.Id equals p.PostId
                   select new PostsModel
                   {
                       Count = p.Count,
                       Title = c.Title,
                       // etc...
                   };
        var dat = data.OrderByDescending(x=>x.Count).ToList();
        ViewBag.data2 = dat;

Then just cast your Viewbag variable to the right type...

@foreach(PostsModel x in ((IEnumerable<PostsModel>)ViewBag.data2)){

    @x.Count
    @x.Title

}

You might have to import the right namespace to your view by using: @using <namespace>


问:
How can I implement pagination in symfony2?
I am working on a project using Symfony2 framework. I am using XAMPP with PHP version 5.5.19. I have table and what I want to do is to put pagination for easy navigation and so on... I am new to symfony that I don't know how to implement it?

Can somebody help me?

答:
//Twig file code</p>

```<code><nav>
        <ul class="pagination">
            <li {% if page_no <= 1 %} class='disabled' {% endif %}>
            <a {% if page_no > 1 %} href='{{ path('pagination', {'page':previous_page}) }}' {% endif %}>Previous</a>
            </li>

        {% if total_no_of_pages <= 10 %}
            {% set counter = 1 %}
            {% for counter in counter..total_no_of_pages %}
                {% if counter == page_no %}
               <li class='active'><a>{{ counter }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page':counter}) }}'>{{ counter }}</a></li>
                {% endif %}
            {% set counter = counter + 1 %}
            {% endfor %}
        {% endif %}

        {% if total_no_of_pages > 10 %}
        {% if page_no <= 4 %}
            {% for counter in 1..7 %}
                {% if counter == page_no %}
               <li class='active'><a>{{ counter }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page':counter}) }}'>{{ counter }}</a></li>
                {% endif %}
            {% set counter = counter + 1 %}
            {% endfor %}
            <li><a>...</a></li>
            <li><a href='{{ path('pagination', {'page': second_last }) }}'>{{ second_last }}</a></li>
            <li><a href='{{ path('pagination', {'page': total_no_of_pages }) }}'>{{ total_no_of_pages }}</a></li>
        {% endif %}

        {% if ( page_no > 4 ) and ( page_no < total_no_of_pages - 4 ) %}
            {% set counterMinus = page_no - adjacents %}
            {% set counterPlus = page_no + adjacents %}
            <li><a href='{{ path('pagination', {'page': 1 }) }}'>1</a></li>
            <li><a href='{{ path('pagination', {'page': 2 }) }}'>2</a></li>
            <li><a>...</a></li>
            {% for counters in counterMinus..counterPlus %}
               {% if counters == page_no %}
               <li class='active'><a>{{ counters }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page': counters }) }}'>{{ counters }}</a></li>
                {% endif %}
                {% set counters = counters + 1 %}
           {% endfor %}
           <li><a>...</a></li>
           <li><a href='{{ path('pagination', {'page': second_last }) }}'>{{ second_last }}</a></li>
           <li><a href='{{ path('pagination', {'page': total_no_of_pages }) }}'>{{ total_no_of_pages }}</a></li>
        {% endif %}

            {% else %}
            <li><a href='{{ path('pagination', {'page': 1 }) }}'>1</a></li>
            <li><a href='{{ path('pagination', {'page': 2 }) }}'>2</a></li>
            <li><a>...</a></li>

            {% set counterMin = total_no_of_pages - 6 %}
            {% for counterss in counterMin..total_no_of_pages %}
                {% if counterss == page_no %}
               <li class='active'><a>{{ counterss }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page': counterss }) }}'>{{ counterss }}</a></li>
                {% endif %}
                {% set counterss = counterss + 1 %}
            {% endfor %}
        {% endif %}

        {% if page_no >= total_no_of_pages - 4 %}
            <li><a href='{{ path('pagination', {'page': 1 }) }}'>1</a></li>
            <li><a href='{{ path('pagination', {'page': 2 }) }}'>2</a></li>
            <li><a>...</a></li>

            {% set lastCount = page_no %}
                {% for lastCount in page_no..total_no_of_pages %}
                {% if lastCount == page_no %}
                <li class='active'><a>{{ lastCount }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page': lastCount }) }}'>{{ lastCount }}</a></li>
               {% endif %}
                {% set lastCount = lastCount + 1 %}
                {% endfor %}
        {% endif%}

        <li {% if page_no >= total_no_of_pages %} class='disabled' {% endif %}>
        <a {% if page_no < total_no_of_pages %} href='{{ path('pagination', {'page': next_page }) }}' {% endif %}>Next</a>
        </li>
        {% if page_no < total_no_of_pages %}
            <li><a href='{{ path('pagination', {'page': total_no_of_pages }) }}'>Last ››</a></li>
        {% endif %}
        </ul>
        </nav>
</code>```

Body:
//Twig file code

<nav>
        <ul class="pagination">
            <li {% if page_no <= 1 %} class='disabled' {% endif %}>
            <a {% if page_no > 1 %} href='{{ path('pagination', {'page':previous_page}) }}' {% endif %}>Previous</a>
            </li>

        {% if total_no_of_pages <= 10 %}
            {% set counter = 1 %}
            {% for counter in counter..total_no_of_pages %}
                {% if counter == page_no %}
               <li class='active'><a>{{ counter }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page':counter}) }}'>{{ counter }}</a></li>
                {% endif %}
            {% set counter = counter + 1 %}
            {% endfor %}
        {% endif %}

        {% if total_no_of_pages > 10 %}
        {% if page_no <= 4 %}
            {% for counter in 1..7 %}
                {% if counter == page_no %}
               <li class='active'><a>{{ counter }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page':counter}) }}'>{{ counter }}</a></li>
                {% endif %}
            {% set counter = counter + 1 %}
            {% endfor %}
            <li><a>...</a></li>
            <li><a href='{{ path('pagination', {'page': second_last }) }}'>{{ second_last }}</a></li>
            <li><a href='{{ path('pagination', {'page': total_no_of_pages }) }}'>{{ total_no_of_pages }}</a></li>
        {% endif %}

        {% if ( page_no > 4 ) and ( page_no < total_no_of_pages - 4 ) %}
            {% set counterMinus = page_no - adjacents %}
            {% set counterPlus = page_no + adjacents %}
            <li><a href='{{ path('pagination', {'page': 1 }) }}'>1</a></li>
            <li><a href='{{ path('pagination', {'page': 2 }) }}'>2</a></li>
            <li><a>...</a></li>
            {% for counters in counterMinus..counterPlus %}
               {% if counters == page_no %}
               <li class='active'><a>{{ counters }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page': counters }) }}'>{{ counters }}</a></li>
                {% endif %}
                {% set counters = counters + 1 %}
           {% endfor %}
           <li><a>...</a></li>
           <li><a href='{{ path('pagination', {'page': second_last }) }}'>{{ second_last }}</a></li>
           <li><a href='{{ path('pagination', {'page': total_no_of_pages }) }}'>{{ total_no_of_pages }}</a></li>
        {% endif %}

            {% else %}
            <li><a href='{{ path('pagination', {'page': 1 }) }}'>1</a></li>
            <li><a href='{{ path('pagination', {'page': 2 }) }}'>2</a></li>
            <li><a>...</a></li>

            {% set counterMin = total_no_of_pages - 6 %}
            {% for counterss in counterMin..total_no_of_pages %}
                {% if counterss == page_no %}
               <li class='active'><a>{{ counterss }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page': counterss }) }}'>{{ counterss }}</a></li>
                {% endif %}
                {% set counterss = counterss + 1 %}
            {% endfor %}
        {% endif %}

        {% if page_no >= total_no_of_pages - 4 %}
            <li><a href='{{ path('pagination', {'page': 1 }) }}'>1</a></li>
            <li><a href='{{ path('pagination', {'page': 2 }) }}'>2</a></li>
            <li><a>...</a></li>

            {% set lastCount = page_no %}
                {% for lastCount in page_no..total_no_of_pages %}
                {% if lastCount == page_no %}
                <li class='active'><a>{{ lastCount }}</a></li>
                {% else %}
               <li><a href='{{ path('pagination', {'page': lastCount }) }}'>{{ lastCount }}</a></li>
               {% endif %}
                {% set lastCount = lastCount + 1 %}
                {% endfor %}
        {% endif%}

        <li {% if page_no >= total_no_of_pages %} class='disabled' {% endif %}>
        <a {% if page_no < total_no_of_pages %} href='{{ path('pagination', {'page': next_page }) }}' {% endif %}>Next</a>
        </li>
        {% if page_no < total_no_of_pages %}
            <li><a href='{{ path('pagination', {'page': total_no_of_pages }) }}'>Last &rsaquo;&rsaquo;</a></li>
        {% endif %}
        </ul>
        </nav>


问:
Shade section between two curves in JSXGraph
How can I shade the section between two curves in JSXGraph
Curves Screenshot

```<code>let board = JSXGraph.createPlot({boundingbox: [-5,5,8,-2], axis: true, grid: true, zoom: {needShift: true}, pan: {needTwoFingers: true}});
let func1 = board.create('functiongraph', [(x) => {return 2 * x**2}, -5, 5], {name: 'f1'});
let func2 = board.create('functiongraph', [(x) => {return 3 + x**2}, -5, 5], {name: 'f2'});
</code>```

What I know is possible:

generate then shade a polygon that approximates the curve

https://groups.google.com/forum/#!searchin/jsxgraph/shade%7Csort:date/jsxgraph/h8yC0qSG3UE/ayGGps1JBgAJ

shade the area between a function and the x-axis using integral

https://jsxgraph.uni-bayreuth.de/docs/symbols/Integral.html

the shade circle intersections (but I don't understand how it works)

https://jsxgraph.uni-bayreuth.de/wiki/index.php/Fill_the_intersection_area_of_two_circles

答:
I also find that frustrating to deal with this. Well, I realized that closed curve can apply fillColor. So, I created arrays by functions and join them together and create a closed curve. Here is my little trick. Feel free
bounded regions</p>

```<code>                                        <div id="jxgbox2" class="jxgbox" style="width:500px; height:500px; margin:auto;"></div>
                                    <script type="text/javascript">
                                    var brd2 = JXG.JSXGraph.initBoard('jxgbox2', {boundingbox:[-1,14,14,-1], axis:true, keepaspectratio:true, showcopyright:false, shownavigation:false});
                                    var pA=[], pB=[], pC=[], fA=[], gA=[], polyA=[];
                                    gA[0]=brd2.create('curve', [function(x){return x;},function(x){return x*x;},0,14]);
                                    gA[1]=brd2.create('curve', [function(x){return x;},function(x){return 24/x +1;},0,14]);
                                    pA[0]=brd2.create('glider', [1,1,gA[0]],{name:"$$P(1,1)$$",fixed:true});
                                    pA[1]=brd2.create('intersection', [gA[0],gA[1]],{name:"Q"});
                                    for(i=0; i<2; i++){gA[i].setProperty({strokeWidth:2,strokeColor:'#E8981D'})};
                                    gA[2]=brd2.create('tangent', [pA[0]],{visible:false});
                                    pA[2]=brd2.create('intersection', [gA[2],gA[1]],{name:"R"});
                                    for(i=0; i<3; i++){pA[i].setProperty({size:2,color:'#555555'})};
                                    gA[3]=brd2.create('curve',[function(x){return x;},function(x){return gA[2].getSlope()*x+gA[2].getRise();},0,14]);
                                    fA[0]=function(x){return x*x;};
                                    fA[1]=function(x){return 24/x +1;};
                                    fA[2]=function(x){return gA[2].getSlope()*x+gA[2].getRise();};
                                    for(i=0; i<pA[1].X()*2; i++)
                                    {pB.push(brd2.create('point',[i*0.5,fA[0](i*0.5)]))};
                                    for(i=0; i<(pA[2].X()*1-pA[1].X())*2; i++)
                                    {pB.push(brd2.create('point',[pA[1].X()+i*0.5,fA[1](pA[1].X()+i*0.5)]))};
                                    for(i=0; i<(pA[2].X()*1-pA[0].X())*2; i++)
                                    {pB.push(brd2.create('point',[pA[2].X()-i*0.5,fA[2](pA[2].X()-i*0.5)]))};
                                    for(i=0; i<pB.length; i++){pB[i].setProperty({visible:false})};
                                    pC=pB.slice(3,pB.length);
                                    gA[4] = brd2.create('curve', JXG.Math.Numerics.bezier(pC),{fillColor:'red', strokeWidth:0.5, fixed:true, fillOpacity:0.5});

                                    </script><br><br>
</code>```

Body:
How can I shade the section between two curves in JSXGraph
Curves Screenshot

let board = JSXGraph.createPlot({boundingbox: [-5,5,8,-2], axis: true, grid: true, zoom: {needShift: true}, pan: {needTwoFingers: true}});
let func1 = board.create('functiongraph', [(x) => {return 2 * x**2}, -5, 5], {name: 'f1'});
let func2 = board.create('functiongraph', [(x) => {return 3 + x**2}, -5, 5], {name: 'f2'});

What I know is possible:

generate then shade a polygon that approximates the curve

https://groups.google.com/forum/#!searchin/jsxgraph/shade%7Csort:date/jsxgraph/h8yC0qSG3UE/ayGGps1JBgAJ

shade the area between a function and the x-axis using integral

https://jsxgraph.uni-bayreuth.de/docs/symbols/Integral.html

the shade circle intersections (but I don't understand how it works)

https://jsxgraph.uni-bayreuth.de/wiki/index.php/Fill_the_intersection_area_of_two_circles

Body:
I also find that frustrating to deal with this. Well, I realized that closed curve can apply fillColor. So, I created arrays by functions and join them together and create a closed curve. Here is my little trick. Feel free
bounded regions

                                        <div id="jxgbox2" class="jxgbox" style="width:500px; height:500px; margin:auto;"></div>
                                    <script type="text/javascript">
                                    var brd2 = JXG.JSXGraph.initBoard('jxgbox2', {boundingbox:[-1,14,14,-1], axis:true, keepaspectratio:true, showcopyright:false, shownavigation:false});
                                    var pA=[], pB=[], pC=[], fA=[], gA=[], polyA=[];
                                    gA[0]=brd2.create('curve', [function(x){return x;},function(x){return x*x;},0,14]);
                                    gA[1]=brd2.create('curve', [function(x){return x;},function(x){return 24/x +1;},0,14]);
                                    pA[0]=brd2.create('glider', [1,1,gA[0]],{name:"$$P(1,1)$$",fixed:true});
                                    pA[1]=brd2.create('intersection', [gA[0],gA[1]],{name:"Q"});
                                    for(i=0; i<2; i++){gA[i].setProperty({strokeWidth:2,strokeColor:'#E8981D'})};
                                    gA[2]=brd2.create('tangent', [pA[0]],{visible:false});
                                    pA[2]=brd2.create('intersection', [gA[2],gA[1]],{name:"R"});
                                    for(i=0; i<3; i++){pA[i].setProperty({size:2,color:'#555555'})};
                                    gA[3]=brd2.create('curve',[function(x){return x;},function(x){return gA[2].getSlope()*x+gA[2].getRise();},0,14]);
                                    fA[0]=function(x){return x*x;};
                                    fA[1]=function(x){return 24/x +1;};
                                    fA[2]=function(x){return gA[2].getSlope()*x+gA[2].getRise();};
                                    for(i=0; i<pA[1].X()*2; i++)
                                    {pB.push(brd2.create('point',[i*0.5,fA[0](i*0.5)]))};
                                    for(i=0; i<(pA[2].X()*1-pA[1].X())*2; i++)
                                    {pB.push(brd2.create('point',[pA[1].X()+i*0.5,fA[1](pA[1].X()+i*0.5)]))};
                                    for(i=0; i<(pA[2].X()*1-pA[0].X())*2; i++)
                                    {pB.push(brd2.create('point',[pA[2].X()-i*0.5,fA[2](pA[2].X()-i*0.5)]))};
                                    for(i=0; i<pB.length; i++){pB[i].setProperty({visible:false})};
                                    pC=pB.slice(3,pB.length);
                                    gA[4] = brd2.create('curve', JXG.Math.Numerics.bezier(pC),{fillColor:'red', strokeWidth:0.5, fixed:true, fillOpacity:0.5});

                                    </script><br><br>


问:
willPresent and didReceive Notification delegate not get called when user in foreground and app is installed fresh
I have implemented FirebaseCloudMessaging, getting notifications when the app is in Background but when I install the fresh app willPresent and didReceive Notification delegate not get called after 30 to 35 minute it will start calling.

It happens only when I install the app by removing the old one.

Here is my code, you can check where I did mistake

```<code>import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Register for push notification
        self.registerForNotification()
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        return true
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {

    //MARK: - Register For RemoteNotification
    func registerForNotification() {
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { granted, error in }
        UIApplication.shared.registerForRemoteNotifications()
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        #if DEVELOPMENT
            Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
        #else
            Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
        #endif
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        debugPrint("Unable to register for remote notifications: \(error.localizedDescription)")
    }

    //MARK: - UNUserNotificationCenterDelegate
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        debugPrint(userInfo)
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo
        debugPrint(userInfo)
        completionHandler([.badge, .alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print(userInfo)
        completionHandler()
    }
}

extension AppDelegate: MessagingDelegate {

    //MARK: - MessagingDelegate
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print(fcmToken)
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print(remoteMessage.appData)
    }
}
</code>```

Thanks for help

答:
Replace registerForNotification function code with this one. May be it will help

```<code>UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (isAllow, error) in

            if isAllow {

                Messaging.messaging().delegate = self

            }

        }

        UIApplication.shared.registerForRemoteNotifications()
</code>```

When user allow the notification then this delegate method will be called

```<code> func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

        print(fcmToken)

    }
</code>```

when notification is tapped

```<code>  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        //when notification is tapped

    }
</code>```

This method will be called when app is in foreground

```<code>  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        //this method is called when notification is about to appear in foreground

        completionHandler([.alert, .badge, .sound]) // Display notification as

    }
</code>```

Body:
I have implemented FirebaseCloudMessaging, getting notifications when the app is in Background but when I install the fresh app willPresent and didReceive Notification delegate not get called after 30 to 35 minute it will start calling.

It happens only when I install the app by removing the old one.

Here is my code, you can check where I did mistake

import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Register for push notification
        self.registerForNotification()
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        return true
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {

    //MARK: - Register For RemoteNotification
    func registerForNotification() {
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { granted, error in }
        UIApplication.shared.registerForRemoteNotifications()
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        #if DEVELOPMENT
            Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
        #else
            Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
        #endif
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        debugPrint("Unable to register for remote notifications: \(error.localizedDescription)")
    }

    //MARK: - UNUserNotificationCenterDelegate
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        debugPrint(userInfo)
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo
        debugPrint(userInfo)
        completionHandler([.badge, .alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print(userInfo)
        completionHandler()
    }
}

extension AppDelegate: MessagingDelegate {

    //MARK: - MessagingDelegate
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print(fcmToken)
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print(remoteMessage.appData)
    }
}

Thanks for help

Body:
Replace registerForNotification function code with this one. May be it will help

UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (isAllow, error) in

            if isAllow {

                Messaging.messaging().delegate = self

            }

        }

        UIApplication.shared.registerForRemoteNotifications()

When user allow the notification then this delegate method will be called

 func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

        print(fcmToken)

    }

when notification is tapped

  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        //when notification is tapped

    }

This method will be called when app is in foreground

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        //this method is called when notification is about to appear in foreground

        completionHandler([.alert, .badge, .sound]) // Display notification as

    }


问:
Extra select when persisting an entity
When i try to save a entity

```<code>@Autowired
private GenericDao<ProfileRoles, Integer> gProfileRolesDao;
...
gProfileRolesDao.create(new ProfileRoles(new Profile(idProfile), new Role(role)));
</code>```

With create

```<code>@Repository
public class GenericDao<T, PK extends Serializable>  {

    @PersistenceContext
    private EntityManager entityManager;
    ...
    public T create(T t) {
        this.entityManager.persist(t);
        return t;
    }
</code>```

And ProfileRoles entity

```<code>@Entity
@Table(name="profile_roles")
public class ProfileRoles {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "profile")
    private Profile profile;

    @ManyToOne
    @JoinColumn(name = "role")
    private Role role;
</code>```

Everything is fine but i get an extra select

```<code>Hibernate: select role_.id, role_.label as label2_22_ from role role_ where role_.id=?
Hibernate: insert into profile_roles (profile, role) values (?, ?)
</code>```

How can I optimize this ?

答:
In general, to avoid extra selects when creating an entity that has many-to-one associated entities, first, you should obtain references for them.

So in your case you should take references of Profile and Role (if you don't have them already), and then create ProfileRoles with them, for example:

// begin transaction
Profile profile = entityManager.getReference(Profile.class, profileId);
Role role = entityManager.getReference(Role.class, roleId);
entityManager.persist(new ProfileRoles(profile, role))
// commit
```

More info: How do find and getReference EntityManager methods work when using JPA and Hibernate

Title: Extra select when persisting an entity

Body:
When i try to save a entity

@Autowired
private GenericDao<ProfileRoles, Integer> gProfileRolesDao;
...
gProfileRolesDao.create(new ProfileRoles(new Profile(idProfile), new Role(role)));

With create

@Repository
public class GenericDao<T, PK extends Serializable>  {

    @PersistenceContext
    private EntityManager entityManager;
    ...
    public T create(T t) {
        this.entityManager.persist(t);
        return t;
    }

And ProfileRoles entity

@Entity
@Table(name="profile_roles")
public class ProfileRoles {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "profile")
    private Profile profile;

    @ManyToOne
    @JoinColumn(name = "role")
    private Role role;

Everything is fine but i get an extra select

Hibernate: select role_.id, role_.label as label2_22_ from role role_ where role_.id=?
Hibernate: insert into profile_roles (profile, role) values (?, ?)

How can I optimize this ?

Body:
In general, to avoid extra selects when creating an entity that has many-to-one associated entities, first, you should obtain references for them.

So in your case you should take references of Profile and Role (if you don't have them already), and then create ProfileRoles with them, for example:

// begin transaction
Profile profile = entityManager.getReference(Profile.class, profileId);
Role role = entityManager.getReference(Role.class, roleId);
entityManager.persist(new ProfileRoles(profile, role))
// commit

More info: How do find and getReference EntityManager methods work when using JPA and Hibernate


问:
Several containers on same host addressed with similar port
I have a client which uses hard coded port 8090.
I would like a machine A to run 3 instances of this client, so each client address different server.
Each of the 3 servers is hosted in a dedicated container, and the 3 containers are hosted on machine B with IP 8.8.4.4.
The problem is that each client addresses to 8.8.4.4:8090, but I would like to route each client to the specific container.

I think that the solution should be something as follows:
Each client will use a specific IP address e.g 8.8.4.1, 8.8.4.2, 8.8.4.3.
Somehow I will map on machine A IPs 8.8.4.1, 8.8.4.2, 8.8.4.3 should be mapped to localhost.
Have a proxy server that will forward from 8.8.4.1:8090 to 8.8.4.4:1000.
Port forward at container c1 from port 1000 to 8090.
Do the same for the other 2 IPs.

My main gap is how to map from IP 8.8.4.1 back to the localhost so that the proxy server will understand that it should forward it to 8.8.4.4:1000.

A diagram. A, B are both windows machines.
c1, c2, c3 are the containers.

         A                                              B
+--------------------+                          +--------------------+
|                    |                          |       1000:8090    |
|                    |                          |    +----------+    |
|                    |                          |    |   c1     |    |
|               +----------------------------------->+          |    |
|                    |                          |    +----------+    |
|                    |                          |       2000:8090    |
|                    |                          |    +----------+    |
|               +----------------------------------->+   c2     |    |
|                    |                          |    |          |    |
|                    |                          |    +----------+    |
|                    |                          |       3000:8090    |
|                    |                          |    +----------+    |
|               +----------------------------------->+    c3    |    |
|                    |                          |    |          |    |
|                    |                          |    +----------+    |
+--------------------+                          +--------------------+
``

Your thoughts and ideas are welcome!

答:
I suggest you have a look for nginx, next is sample configure for routing.

Let's suppose client all run on machineA, and machineA has the ip 8.8.4.5, also nginx run on machineA:

Part of nginx.conf:

```<code>stream {
    upstream server1 {
        server 8.8.4.4:1000;
    }

    upstream server2 {
        server 8.8.4.4:2000;
    }

    upstream server3 {
        server 8.8.4.4:3000;
    }

    server {
        listen 8090;
        server_name nginx1;
        proxy_pass server1;
    }

    server {
        listen 8090;
        server_name nginx2;
        proxy_pass server2;
    }

    server {
        listen 8090;
        server_name nginx3;
        proxy_pass server3;
    }
}
</code>```

Then add next to hosts file:

```<code>8.8.4.5 nginx1
8.8.4.5 nginx2
8.8.4.5 nginx3
</code>```

And clients use next to connect:

client1: nginx1:8090

client2: nginx2:8090

client3: nginx3:8090

If you do not want to use vhost of nginx, you can directly use multiple ip on one network card, then you do not need set hosts file. See this.

PS: Of course if your clients have ability to bind to different ips just as I thought at first, something like this:

```<code>tcp_client.bind(('8.8.4.1', xxx))
tcp_client.connect((server_ip, server_port))
</code>```

Then it's also ok to use remote_addr to distinguish connection, like next:

```<code>stream {
    upstream server1 {
        server 8.8.4.4:1000;
    }

    upstream server2 {
        server 8.8.4.4:2000;
    }

    upstream server3 {
        server 8.8.4.4:3000;
    }

    server {
        listen 8090;

        if ($remote_addr ~* "8.8.4.1")
        {
            proxy_pass server1;
        }

        if ($remote_addr ~* "8.8.4.2")
        {
            proxy_pass server2;
        }

        if ($remote_addr ~* "8.8.4.3")
        {
            proxy_pass server3;
        }
     }
}
</code>```

Body:
I suggest you have a look for nginx, next is sample configure for routing.

Let's suppose client all run on machineA, and machineA has the ip 8.8.4.5, also nginx run on machineA:

Part of nginx.conf:

stream {
    upstream server1 {
        server 8.8.4.4:1000;
    }

    upstream server2 {
        server 8.8.4.4:2000;
    }

    upstream server3 {
        server 8.8.4.4:3000;
    }

    server {
        listen 8090;
        server_name nginx1;
        proxy_pass server1;
    }

    server {
        listen 8090;
        server_name nginx2;
        proxy_pass server2;
    }

    server {
        listen 8090;
        server_name nginx3;
        proxy_pass server3;
    }
}

Then add next to hosts file:

8.8.4.5 nginx1
8.8.4.5 nginx2
8.8.4.5 nginx3

And clients use next to connect:

client1: nginx1:8090

client2: nginx2:8090

client3: nginx3:8090

If you do not want to use vhost of nginx, you can directly use multiple ip on one network card, then you do not need set hosts file. See this.

PS: Of course if your clients have ability to bind to different ips just as I thought at first, something like this:

tcp_client.bind(('8.8.4.1', xxx))
tcp_client.connect((server_ip, server_port))

Then it's also ok to use remote_addr to distinguish connection, like next:

stream {
    upstream server1 {
        server 8.8.4.4:1000;
    }

    upstream server2 {
        server 8.8.4.4:2000;
    }

    upstream server3 {
        server 8.8.4.4:3000;
    }

    server {
        listen 8090;

        if ($remote_addr ~* "8.8.4.1")
        {
            proxy_pass server1;
        }

        if ($remote_addr ~* "8.8.4.2")
        {
            proxy_pass server2;
        }

        if ($remote_addr ~* "8.8.4.3")
        {
            proxy_pass server3;
        }
     }
}


问:
Returning distinct rows while treating NULLs as distinct
I have a table:

I need a SELECT statement which will return the following: for rows with the same phoneNumber, I want to only return the first row. For rows that are NULL, I want to return all of these. Tried using DISTINCT but that obviously doesn't work in the case of NULL as it will only return 1 NULL row. So the data I need would look like:

答:
You can use the UNION operator to combine the result sets of two queries.

In the first query you will fetch only the rows that
have a phone number and you will use GROUP BY to get distinct phone numbers.

In the second query you will fetch all the rows that do not have a phone number.

Something like this should work:

```<code>SELECT * FROM `table`
WHERE `phoneNumber` IS NOT NULL
GROUP BY phoneNumber
UNION ALL
SELECT * FROM `table`
WHERE `phoneNumber` IS NULL
</code>```

Body:
You can use the UNION operator to combine the result sets of two queries.

In the first query you will fetch only the rows that
have a phone number and you will use GROUP BY to get distinct phone numbers.

In the second query you will fetch all the rows that do not have a phone number.

Something like this should work:

SELECT * FROM `table`
WHERE `phoneNumber` IS NOT NULL
GROUP BY phoneNumber
UNION ALL
SELECT * FROM `table`
WHERE `phoneNumber` IS NULL