问:
Product of two matrices with pthreads in C
i have a problem with a C Pthreaded program. I have to do the product of two matrices m1 (nr1 rows and nc1 columns) and m2 (nr2 rows and nc2 columns).
I create nr1 * nc2 threads run time passing to each thread the number of row of m1 and the number of column of m2 to multiply. The thread, save the result in another matrice. The code is this:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"

struct prodmat{
int  row;
int  col;
};

int number;
double **dmat1;
double **dmat2;
double **dmatprod;

void ** allocaM2d (int nr, int nc, int dim);
void prodmat(double ** a,  double ** b, double ** c, int nr1, int nc1nr2,
               int nc2);

void * prodthread(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,k;
 r = prod->row;
 c = prod->col;

 printf("Thread for product of row = %i, column = %i and number = %i\n",r,c,number);

      for (k=0; k<number; k++){
        //dmatprod[r][c] += dmat1[r][k]*dmat2[k][c];
        printf("product of dmat1[%i][%i]=%i * dmat2[%i][%i] = %i\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);

         }

}

int main(void) {

int  nr1, nc1, nr2, nc2, dim, i, j, k,r,c;

printf("Rows and Columns of the first matrix: ");
scanf ("%d%d",&nr1,  &nc1);
do {
  printf("Rows and Columns of the second matrix\n");
  printf("The number of rows must be equal to nc1 ");
  scanf ("%d%d",&nr2,  &nc2);
} while (nr2 != nc1);

number = nr2;
//  dynamic allocation

dim = sizeof(double);

dmat1 = (double **) allocaM2d(nr1,  nc1, dim);
dmat2 = (double **) allocaM2d(nr2,  nc2, dim);
dmatprod = (double **) allocaM2d(nr1, nc2, dim);

// in this for i create m1 and m2 and then i print these
k=0;
for(i=0;i<nr1;i++)
  for(j=0;j<nc1;j++)
    dmat1[i][j] = k++;

for(i=0;i<nr1;i++){
  for(j=0;j<nc1;j++)
    printf("%lf ", dmat1[i][j]);
  printf("\n");
}

printf("\n");
k=0;
for(i=0;i<nr2;i++)
  for(j=0;j<nc2;j++)
    dmat2[i][j] = k++;

for(i=0;i<nr2;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmat2[i][j]);
  printf("\n");
}

//This is the cycle where i create the threads
r=0; c=0;
for(r=0; r<nr1 ; r++)
{

  for(c=0; c<nc2; c++){

   struct prodmat * prod; prod= malloc(sizeof(struct prodmat *));
   pthread_t * th; th= malloc(sizeof(pthread_t *));

   prod->row = r;
   prod->col = c;

   pthread_create(th,NULL,prodthread,prod);
  }

}
/*
prodmat( dmat1, dmat2, dmatprod, nr1, nc1, nc2);

printf("\n");
for(i=0;i<nr1;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmatprod[i][j]);
  printf("\n");
}
*/

//is not important this sleep(100). I will replace in future.
sleep(100);
}

/************************************************************/

void ** allocaM2d (int nr, int nc, int dim){
int i;
void ** m;
char * vd;  //  byte pointer

m = (void **) malloc(nr * sizeof(void *));
vd = (char *) malloc(nr * nc * dim);

for(i=0;i<nr;i++)
  m[i] = &vd[i * nc * dim];

return (void **) m; // return matrix pointer
}
</code>```

Then i receive the print of the m1 and m2 and the print of the product, something like this:

```<code>   0.000000 1.000000 2.000000 3.000000 4.000000
   5.000000 6.000000 7.000000 8.000000 9.000000
   10.000000 11.000000 12.000000 13.000000 14.000000
   15.000000 16.000000 17.000000 18.000000 19.000000

   0.000000 1.000000 2.000000 3.000000
   4.000000 5.000000 6.000000 7.000000
   8.000000 9.000000 10.000000 11.000000
   12.000000 13.000000 14.000000 15.000000
   16.000000 17.000000 18.000000 19.000000

    Thread for product of row = 3, column = 2 and number = 5
    product of dmat1[3][0]=0 * dmat2[2][0] = 0
    product of dmat1[3][1]=1 * dmat2[2][0] = 0
    product of dmat1[3][2]=2 * dmat2[2][0] = 0
    product of dmat1[3][3]=3 * dmat2[2][0] = 0
    product of dmat1[3][4]=4 * dmat2[2][0] = 0
</code>```

But, in the second part seems like if the m2 is never been initialized (even if in the 1 part the print tells different).

SOLVED:
The correct code is this:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"

struct prodmat{
int  row;
int  col;
};

int number;
double **dmat1;
double **dmat2;
double **dmatprod;

void ** allocaM2d (int nr, int nc, int dim);
void prodmat(double ** a,  double ** b, double ** c, int nr1, int nc1nr2,
               int nc2);

void * prodthread(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,k;
 r = prod->row;
 c = prod->col;

 //printf("Thread for product of row = %i, column = %i \n",r,c);

      for (k=0; k<number; k++){
        dmatprod[r][c] += dmat1[r][k]*dmat2[k][c];
        //printf("product of dmat1[%i][%i]=%lf * dmat2[%i][%i] = %lf\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);

         }

  pthread_exit(pthread_self ());

}

void * printer(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,i,j;
 r = prod->row;
 c = prod->col;

 //printf("Thread for product of row = %i, column = %i \n",r,c);

    printf("\n\n --> PRODUCT: \n\n");
      for(i=0;i<r;i++){
         for(j=0;j<c;j++)
          printf("%lf ", dmatprod[i][j]);
          printf("\n");
         }

  printf("\n\n ");
  pthread_exit(pthread_self ());

}

int main(void) {

int  nr1, nc1, nr2, nc2, dim, i, j, k,r,c;

printf("Rows and Columns of the first matrix: ");
scanf ("%d%d",&nr1,  &nc1);
do {
  printf("Rows and Columns of the second matrix\n");
  printf("The number of rows must be equal to nc1 ");
  scanf ("%d%d",&nr2,  &nc2);
} while (nr2 != nc1);

number = nr2;
//  dynamic allocation

dim = sizeof(double);

dmat1 = (double **) allocaM2d(nr1,  nc1, dim);
dmat2 = (double **) allocaM2d(nr2,  nc2, dim);
dmatprod = (double **) allocaM2d(nr1, nc2, dim);

k=0;
for(i=0;i<nr1;i++)
  for(j=0;j<nc1;j++)
    dmat1[i][j] = k++;

for(i=0;i<nr1;i++){
  for(j=0;j<nc1;j++)
    printf("%lf ", dmat1[i][j]);
  printf("\n");
}

printf("\n");
k=0;
for(i=0;i<nr2;i++)
  for(j=0;j<nc2;j++)
    dmat2[i][j] = k++;

for(i=0;i<nr2;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmat2[i][j]);
  printf("\n");
}

r=0; c=0;
for(r=0; r<nr1 ; r++)
{

  for(c=0; c<nc2; c++){

   struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
   pthread_t * th; th= malloc(sizeof(pthread_t ));

   prod->row = r;
   prod->col = c;

   pthread_create(th,NULL,prodthread,prod);
  }

}

sleep(1);
 struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
 pthread_t * th; th= malloc(sizeof(pthread_t ));

 prod->row = nr1;
 prod->col = nc2;

 pthread_create(th,NULL,printer,prod);

/*
prodmat( dmat1, dmat2, dmatprod, nr1, nc1, nc2);

printf("\n");
for(i=0;i<nr1;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmatprod[i][j]);
  printf("\n");
}
*/

pthread_exit(pthread_self ());

}

/************************************************************/

void ** allocaM2d (int nr, int nc, int dim){
int i;
void ** m;
char * vd;  //  byte pointer

m = (void **) malloc(nr * sizeof(void *));
vd = (char *) malloc(nr * nc * dim);

for(i=0;i<nr;i++)
  m[i] = &vd[i * nc * dim];

return (void **) m; // return matrix pointer
}
</code>```

That produces, for an input of 5x5 and 5x5 for ex, this:

```<code>0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
10.000000 11.000000 12.000000 13.000000 14.000000
15.000000 16.000000 17.000000 18.000000 19.000000
20.000000 21.000000 22.000000 23.000000 24.000000

0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
10.000000 11.000000 12.000000 13.000000 14.000000
15.000000 16.000000 17.000000 18.000000 19.000000
20.000000 21.000000 22.000000 23.000000 24.000000

 --> PRODUCT:

150.000000 160.000000 170.000000 180.000000 190.000000
400.000000 435.000000 470.000000 505.000000 540.000000
650.000000 710.000000 770.000000 830.000000 890.000000
900.000000 985.000000 1070.000000 1155.000000 1240.000000
1150.000000 1260.000000 1370.000000 1480.000000 1590.000000
</code>```

答:
A big problem is your dynamic memory allocations, as it seems you don't understand what malloc does: The malloc function allocates a number of bytes.

For example (from your code):

```<code>struct prodmat * prod; prod= malloc(sizeof(struct prodmat *));
</code>```

Here you allocate enough memory for a pointer to a prodmat structure, not memory for an actual prodmat structure. To allocate memory for a prodmat structure you should do

```<code>struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
</code>```

Notice the difference between the malloc calls?

More of your calls to malloc follow the same wrong pattern.

If the size of a pointer does not match what you intend to allocate you might allocate to little memory, and have undefined behavior.

As for the problem with the output being wrong, it's because you use the wrong printf format to print the values. The format "%i" is for printing int, but the values in the arrays are double.

Using the wrong printf format leads to undefined behavior.

Body:
i have a problem with a C Pthreaded program. I have to do the product of two matrices m1 (nr1 rows and nc1 columns) and m2 (nr2 rows and nc2 columns).
I create nr1 * nc2 threads run time passing to each thread the number of row of m1 and the number of column of m2 to multiply. The thread, save the result in another matrice. The code is this:

#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"

struct prodmat{
int  row;
int  col;
};

int number;
double **dmat1;
double **dmat2;
double **dmatprod;

void ** allocaM2d (int nr, int nc, int dim);
void prodmat(double ** a,  double ** b, double ** c, int nr1, int nc1nr2,
               int nc2);

void * prodthread(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,k;
 r = prod->row;
 c = prod->col;

 printf("Thread for product of row = %i, column = %i and number = %i\n",r,c,number);

      for (k=0; k<number; k++){
        //dmatprod[r][c] += dmat1[r][k]*dmat2[k][c];
        printf("product of dmat1[%i][%i]=%i * dmat2[%i][%i] = %i\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);

         }

}

int main(void) {

int  nr1, nc1, nr2, nc2, dim, i, j, k,r,c;

printf("Rows and Columns of the first matrix: ");
scanf ("%d%d",&nr1,  &nc1);
do {
  printf("Rows and Columns of the second matrix\n");
  printf("The number of rows must be equal to nc1 ");
  scanf ("%d%d",&nr2,  &nc2);
} while (nr2 != nc1);

number = nr2;
//  dynamic allocation

dim = sizeof(double);

dmat1 = (double **) allocaM2d(nr1,  nc1, dim);
dmat2 = (double **) allocaM2d(nr2,  nc2, dim);
dmatprod = (double **) allocaM2d(nr1, nc2, dim);

// in this for i create m1 and m2 and then i print these
k=0;
for(i=0;i<nr1;i++)
  for(j=0;j<nc1;j++)
    dmat1[i][j] = k++;

for(i=0;i<nr1;i++){
  for(j=0;j<nc1;j++)
    printf("%lf ", dmat1[i][j]);
  printf("\n");
}

printf("\n");
k=0;
for(i=0;i<nr2;i++)
  for(j=0;j<nc2;j++)
    dmat2[i][j] = k++;

for(i=0;i<nr2;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmat2[i][j]);
  printf("\n");
}

//This is the cycle where i create the threads
r=0; c=0;
for(r=0; r<nr1 ; r++)
{

  for(c=0; c<nc2; c++){

   struct prodmat * prod; prod= malloc(sizeof(struct prodmat *));
   pthread_t * th; th= malloc(sizeof(pthread_t *));

   prod->row = r;
   prod->col = c;

   pthread_create(th,NULL,prodthread,prod);
  }

}
/*
prodmat( dmat1, dmat2, dmatprod, nr1, nc1, nc2);

printf("\n");
for(i=0;i<nr1;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmatprod[i][j]);
  printf("\n");
}
*/

//is not important this sleep(100). I will replace in future.
sleep(100);
}

/************************************************************/

void ** allocaM2d (int nr, int nc, int dim){
int i;
void ** m;
char * vd;  //  byte pointer

m = (void **) malloc(nr * sizeof(void *));
vd = (char *) malloc(nr * nc * dim);

for(i=0;i<nr;i++)
  m[i] = &vd[i * nc * dim];

return (void **) m; // return matrix pointer
}

Then i receive the print of the m1 and m2 and the print of the product, something like this:

   0.000000 1.000000 2.000000 3.000000 4.000000
   5.000000 6.000000 7.000000 8.000000 9.000000
   10.000000 11.000000 12.000000 13.000000 14.000000
   15.000000 16.000000 17.000000 18.000000 19.000000

   0.000000 1.000000 2.000000 3.000000
   4.000000 5.000000 6.000000 7.000000
   8.000000 9.000000 10.000000 11.000000
   12.000000 13.000000 14.000000 15.000000
   16.000000 17.000000 18.000000 19.000000

    Thread for product of row = 3, column = 2 and number = 5
    product of dmat1[3][0]=0 * dmat2[2][0] = 0
    product of dmat1[3][1]=1 * dmat2[2][0] = 0
    product of dmat1[3][2]=2 * dmat2[2][0] = 0
    product of dmat1[3][3]=3 * dmat2[2][0] = 0
    product of dmat1[3][4]=4 * dmat2[2][0] = 0

But, in the second part seems like if the m2 is never been initialized (even if in the 1 part the print tells different).

SOLVED:
The correct code is this:

#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"

struct prodmat{
int  row;
int  col;
};

int number;
double **dmat1;
double **dmat2;
double **dmatprod;

void ** allocaM2d (int nr, int nc, int dim);
void prodmat(double ** a,  double ** b, double ** c, int nr1, int nc1nr2,
               int nc2);

void * prodthread(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,k;
 r = prod->row;
 c = prod->col;

 //printf("Thread for product of row = %i, column = %i \n",r,c);

      for (k=0; k<number; k++){
        dmatprod[r][c] += dmat1[r][k]*dmat2[k][c];
        //printf("product of dmat1[%i][%i]=%lf * dmat2[%i][%i] = %lf\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);

         }

  pthread_exit(pthread_self ());

}

void * printer(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,i,j;
 r = prod->row;
 c = prod->col;

 //printf("Thread for product of row = %i, column = %i \n",r,c);

    printf("\n\n --> PRODUCT: \n\n");
      for(i=0;i<r;i++){
         for(j=0;j<c;j++)
          printf("%lf ", dmatprod[i][j]);
          printf("\n");
         }

  printf("\n\n ");
  pthread_exit(pthread_self ());

}

int main(void) {

int  nr1, nc1, nr2, nc2, dim, i, j, k,r,c;

printf("Rows and Columns of the first matrix: ");
scanf ("%d%d",&nr1,  &nc1);
do {
  printf("Rows and Columns of the second matrix\n");
  printf("The number of rows must be equal to nc1 ");
  scanf ("%d%d",&nr2,  &nc2);
} while (nr2 != nc1);

number = nr2;
//  dynamic allocation

dim = sizeof(double);

dmat1 = (double **) allocaM2d(nr1,  nc1, dim);
dmat2 = (double **) allocaM2d(nr2,  nc2, dim);
dmatprod = (double **) allocaM2d(nr1, nc2, dim);

k=0;
for(i=0;i<nr1;i++)
  for(j=0;j<nc1;j++)
    dmat1[i][j] = k++;

for(i=0;i<nr1;i++){
  for(j=0;j<nc1;j++)
    printf("%lf ", dmat1[i][j]);
  printf("\n");
}

printf("\n");
k=0;
for(i=0;i<nr2;i++)
  for(j=0;j<nc2;j++)
    dmat2[i][j] = k++;

for(i=0;i<nr2;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmat2[i][j]);
  printf("\n");
}

r=0; c=0;
for(r=0; r<nr1 ; r++)
{

  for(c=0; c<nc2; c++){

   struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
   pthread_t * th; th= malloc(sizeof(pthread_t ));

   prod->row = r;
   prod->col = c;

   pthread_create(th,NULL,prodthread,prod);
  }

}

sleep(1);
 struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
 pthread_t * th; th= malloc(sizeof(pthread_t ));

 prod->row = nr1;
 prod->col = nc2;

 pthread_create(th,NULL,printer,prod);

/*
prodmat( dmat1, dmat2, dmatprod, nr1, nc1, nc2);

printf("\n");
for(i=0;i<nr1;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmatprod[i][j]);
  printf("\n");
}
*/

pthread_exit(pthread_self ());

}

/************************************************************/

void ** allocaM2d (int nr, int nc, int dim){
int i;
void ** m;
char * vd;  //  byte pointer

m = (void **) malloc(nr * sizeof(void *));
vd = (char *) malloc(nr * nc * dim);

for(i=0;i<nr;i++)
  m[i] = &vd[i * nc * dim];

return (void **) m; // return matrix pointer
}

That produces, for an input of 5x5 and 5x5 for ex, this:

0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
10.000000 11.000000 12.000000 13.000000 14.000000
15.000000 16.000000 17.000000 18.000000 19.000000
20.000000 21.000000 22.000000 23.000000 24.000000

0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
10.000000 11.000000 12.000000 13.000000 14.000000
15.000000 16.000000 17.000000 18.000000 19.000000
20.000000 21.000000 22.000000 23.000000 24.000000

 --> PRODUCT:

150.000000 160.000000 170.000000 180.000000 190.000000
400.000000 435.000000 470.000000 505.000000 540.000000
650.000000 710.000000 770.000000 830.000000 890.000000
900.000000 985.000000 1070.000000 1155.000000 1240.000000
1150.000000 1260.000000 1370.000000 1480.000000 1590.000000

Body:
A big problem is your dynamic memory allocations, as it seems you don't understand what malloc does: The malloc function allocates a number of bytes.

For example (from your code):

struct prodmat * prod; prod= malloc(sizeof(struct prodmat *));

Here you allocate enough memory for a pointer to a prodmat structure, not memory for an actual prodmat structure. To allocate memory for a prodmat structure you should do

struct prodmat * prod; prod= malloc(sizeof(struct prodmat));

Notice the difference between the malloc calls?

More of your calls to malloc follow the same wrong pattern.

If the size of a pointer does not match what you intend to allocate you might allocate to little memory, and have undefined behavior.

As for the problem with the output being wrong, it's because you use the wrong printf format to print the values. The format "%i" is for printing int, but the values in the arrays are double.

Using the wrong printf format leads to undefined behavior.


来源: stackexchange

问:
Cannot change search bar background color
I have a search bar:

```<code>let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))
</code>```

and I want to change text input part background color. For this I've tried:

```<code>searchBar.barTintColor = UIColor(red: 0/255, green: 74/255, blue: 103/255, alpha: 1)

searchBar.backgroundColor = UIColor.redColor()
</code>```

but these both variants do not work. How can I change background color of my UISearchBar textInput part and what I did wrong?

答:
For Swift 3+, use this:

```<code>for subView in searchController.searchBar.subviews {

    for subViewOne in subView.subviews {

        if let textField = subViewOne as? UITextField {

           subViewOne.backgroundColor = UIColor.red

           //use the code below if you want to change the color of placeholder
           let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel
                textFieldInsideUISearchBarLabel?.textColor = UIColor.blue
        }
     }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a search bar:

let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))

and I want to change text input part background color. For this I've tried:

searchBar.barTintColor = UIColor(red: 0/255, green: 74/255, blue: 103/255, alpha: 1)

searchBar.backgroundColor = UIColor.redColor()

but these both variants do not work. How can I change background color of my UISearchBar textInput part and what I did wrong?

Body:
For Swift 3+, use this:

for subView in searchController.searchBar.subviews {

    for subViewOne in subView.subviews {

        if let textField = subViewOne as? UITextField {

           subViewOne.backgroundColor = UIColor.red

           //use the code below if you want to change the color of placeholder
           let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel
                textFieldInsideUISearchBarLabel?.textColor = UIColor.blue
        }
     }
}


问:
Create a CardView with a semicircle on top
I am very much into designing a login screen.

Something like this:

How Do I actually cut the card from the top so as to fill the drawable on top of it? Any help would be of great value.

[Source: https://www.uplabs.com/posts/login-android-app/]

答:
A bit update from Ferdous Ahamed's answer. you need to make your image circular.

just add this to your gradle

```<code>compile 'de.hdodenhof:circleimageview:2.2.0'
</code>```

then in your xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f36121">

    <RelativeLayout
        android:id="@+id/card_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:layout_centerInParent="true">

        <android.support.v7.widget.CardView
            android:id="@+id/card_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:foreground="?android:attr/selectableItemBackground"
            card_view:cardBackgroundColor="#ffffff"
            card_view:cardCornerRadius="4dp"
            card_view:cardElevation="0dp"
            card_view:cardUseCompatPadding="false" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_marginTop="50dp"
                android:padding="24dp">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Login"/>

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:hint="Password"
                    android:inputType="textPassword"/>

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="Sign In"
                    android:background="@android:color/holo_blue_dark"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <de.hdodenhof.circleimageview.CircleImageView
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:id="@+id/profile_image"
         android:layout_width="96dp"
         android:layout_height="96dp"
         android:src="@drawable/profile"
         app:civ_border_width="2dp"
         app:civ_border_color="#FF000000"/>

    </RelativeLayout>
</RelativeLayout>
</code>```

all you need to do is use same color. in your parent background and in your imageview use same color for border.

```<code>app:civ_border_color="#f36121"
</code>```

OUTPUT

Refer Github link.

Body:
A bit update from Ferdous Ahamed's answer. you need to make your image circular.

just add this to your gradle

compile 'de.hdodenhof:circleimageview:2.2.0'

then in your xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f36121">

    <RelativeLayout
        android:id="@+id/card_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:layout_centerInParent="true">

        <android.support.v7.widget.CardView
            android:id="@+id/card_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:foreground="?android:attr/selectableItemBackground"
            card_view:cardBackgroundColor="#ffffff"
            card_view:cardCornerRadius="4dp"
            card_view:cardElevation="0dp"
            card_view:cardUseCompatPadding="false" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_marginTop="50dp"
                android:padding="24dp">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Login"/>

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:hint="Password"
                    android:inputType="textPassword"/>

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="Sign In"
                    android:background="@android:color/holo_blue_dark"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <de.hdodenhof.circleimageview.CircleImageView
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:id="@+id/profile_image"
         android:layout_width="96dp"
         android:layout_height="96dp"
         android:src="@drawable/profile"
         app:civ_border_width="2dp"
         app:civ_border_color="#FF000000"/>

    </RelativeLayout>
</RelativeLayout>

all you need to do is use same color. in your parent background and in your imageview use same color for border.

app:civ_border_color="#f36121"

OUTPUT

Refer Github link.


问:
Setting the day of the date to the 1st with moment.js
I am looking through the moment documentation and can't find the the method required. In my solution I am getting today's date then getting the month before and the month after, but wish to get the very first day of the month and the very last day of the month ahead.

In brief this should be the out come:

today's date: 21/05/2017

startDate = 01/04/2017

endDate = 30/06/2017

My code:

```<code>var startDate = moment(date).subtract(1,'months')
var endDate = moment(date).add(1,'months');
</code>```

答: You can use moment().startOf('month') and moment().endOf('month') methods

Body:
I am looking through the moment documentation and can't find the the method required. In my solution I am getting today's date then getting the month before and the month after, but wish to get the very first day of the month and the very last day of the month ahead.

In brief this should be the out come:

today's date: 21/05/2017

startDate = 01/04/2017

endDate = 30/06/2017

My code:

var startDate = moment(date).subtract(1,'months')
var endDate = moment(date).add(1,'months');


问:
C# multiple string match
I need C# string search algorithm which can match multiple occurance of pattern. For example, if pattern is 'AA' and string is 'BAAABBB' Regex produce match result Index = 1, but I need result Index = 1,2. Can I force Regex to give such result? </p>

答:
Are you really looking for substrings that are only two characters long?  If so, searching a 20-million character string is going to be slow no matter what regex you use (or any non-regex technique, for that matter).  If the search string is longer, the regex engine can employ a search algorithm like Boyer-Moore or Knuth-Morris-Pratt to speed up the search--the longer the better, in fact.

By the way, the kind of search you're talking about is called overlapping matches; I'll add that to the tags.

OwnerDisplayName: matko

LastEditorDisplayName: Alan M

ContentLicense: CC BY-SA 2.5

Title: C# multiple string match

OwnerDisplayName: Alan M


问:
Javascript SRC is not working in IPhone Safari and Android
As per the requirement i need to change the image src dynamically, hence i using JavaScript to accomplish this.

I am accessing the image with id and adding new src depending on the user click, below is the code where i am getting the problem. Through out the process i am getting the updated SRC Data of image, but its looks strange that i could see updated image in desktop browser but not in Mobile safari and Andriod.

Please help

```<code>//This is id for fetching the user data
var text_food=document.getElementById("plateText_food");

//User Data
var currentFoodName=text_food.innerHTML;

//as per the requirement removing space and adding "-"
var regExp = /\s+/g;
var foodName=currentFoodName.replace(regExp,'-');

//Detail URL
var detailURL_food01 = 'img/beer_images_png/' + foodName + '.png';

//id FOR ACCESSING IMAGE
var updateFoodImage=document.getElementById("detailURL_food");

//adding updated src
updateFoodImage.src = detailURL_food01;
</code>```

答:
This should work, provided it's run at the right time.  Both the browsers you're having issues when render and load content much slower...nature of working on mobile, that means you need to be sure that your code runs after the DOM is loaded, on window.onload for example, otherwise when you execute document.getElementById("plateText_food")...that id="plateText_food" element may not be in the DOM ready to find yet.

Try a simple alert() to test this, at the end (you won't get the alert if it errors before, another indicator):

```<code>alert(detailURL_food01);
updateFoodImage.src = detailURL_food01;
</code>```

Body:
As per the requirement i need to change the image src dynamically, hence i using JavaScript to accomplish this.

I am accessing the image with id and adding new src depending on the user click, below is the code where i am getting the problem. Through out the process i am getting the updated SRC Data of image, but its looks strange that i could see updated image in desktop browser but not in Mobile safari and Andriod.

Please help

//This is id for fetching the user data
var text_food=document.getElementById("plateText_food");

//User Data
var currentFoodName=text_food.innerHTML;

//as per the requirement removing space and adding "-"
var regExp = /\s+/g;
var foodName=currentFoodName.replace(regExp,'-');

//Detail URL
var detailURL_food01 = 'img/beer_images_png/' + foodName + '.png';

//id FOR ACCESSING IMAGE
var updateFoodImage=document.getElementById("detailURL_food");

//adding updated src
updateFoodImage.src = detailURL_food01;

Body:
This should work, provided it's run at the right time.  Both the browsers you're having issues when render and load content much slower...nature of working on mobile, that means you need to be sure that your code runs after the DOM is loaded, on window.onload for example, otherwise when you execute document.getElementById("plateText_food")...that id="plateText_food" element may not be in the DOM ready to find yet.

Try a simple alert() to test this, at the end (you won't get the alert if it errors before, another indicator):

alert(detailURL_food01);
updateFoodImage.src = detailURL_food01;


问:
VS Team Services - Security Report Extract Displaying Users In Role Per Project
Is there a way to run a report against the security setup in Team Services that would display all users grouped by roles and project?</p>

答:
There is not the report to display users/groups in Team Services. You can refer to this code below to retrieve necessary information.

```<code>NetworkCredential cred = new NetworkCredential("XX", "XX");
 string url = "https://XX.visualstudio.com/DefaultCollection";
TfsTeamProjectCollection collection = new TfsTeamProjectCollection(new Uri(url), cred);
collection.EnsureAuthenticated();

           var structureService= collection.GetService<ICommonStructureService>();
            var teamprojects = structureService.ListAllProjects();
            TfsTeamService teamService = collection.GetService<TfsTeamService>();
            IGroupSecurityService gss = collection.GetService<IGroupSecurityService>();
foreach (var tp in teamprojects)
            {
                var teamList = teamService.QueryTeams(tp.Uri);
                foreach (var currentTeam in teamList)
                {
                    Identity[] appGroups = gss.ListApplicationGroups(currentTeam.Project);
                    foreach (var g in appGroups)
                    {
                        Identity[] groupMembers = gss.ReadIdentities(SearchFactor.Sid, new string[] { g.Sid }, QueryMembership.Expanded);
                   }
                }
  }
</code>```

On the other hand, there is the REST API about security that may help you.

Body:
There is not the report to display users/groups in Team Services. You can refer to this code below to retrieve necessary information.

NetworkCredential cred = new NetworkCredential("XX", "XX");
 string url = "https://XX.visualstudio.com/DefaultCollection";
TfsTeamProjectCollection collection = new TfsTeamProjectCollection(new Uri(url), cred);
collection.EnsureAuthenticated();

           var structureService= collection.GetService<ICommonStructureService>();
            var teamprojects = structureService.ListAllProjects();
            TfsTeamService teamService = collection.GetService<TfsTeamService>();
            IGroupSecurityService gss = collection.GetService<IGroupSecurityService>();
foreach (var tp in teamprojects)
            {
                var teamList = teamService.QueryTeams(tp.Uri);
                foreach (var currentTeam in teamList)
                {
                    Identity[] appGroups = gss.ListApplicationGroups(currentTeam.Project);
                    foreach (var g in appGroups)
                    {
                        Identity[] groupMembers = gss.ReadIdentities(SearchFactor.Sid, new string[] { g.Sid }, QueryMembership.Expanded);
                   }
                }
  }

On the other hand, there is the REST API about security that may help you.


问:
Accessing type parameters of outer type
In Kotlin, we can define nested interfaces. If the outer interface is generic (here just to simulate a proper Self meta-type, but one can imagine other uses), can I refer to its type parameter from the inner type?

That is, I want to achieve (an equivalent of) this:

```<code>interface JsonRepresentable<Self: JsonRepresentable<Self>> {
    fun toJson(): String

    interface Companion {
        operator fun invoke(json:String): Self?
    }
}
</code>```

答:
No, you can't. An interface can't be a non-static inner class, which is a platform constrain that can't be overcame by Kotlin.
I know it would be pretty useful to constrain how the companion object should be, but this haven't been considered yet. I don't know if JetBrains will ever take this suggestion seriously.

In your attempt, those two interfaces are NOT related at all, except that you can find KClass<Compaion> in JsonRepresentable::class.nestedClasses. The relationship between these interfaces can be compared to the relationship between a Java static inner class and its declaring class.

Title: Accessing type parameters of outer type

Body:
In Kotlin, we can define nested interfaces. If the outer interface is generic (here just to simulate a proper Self meta-type, but one can imagine other uses), can I refer to its type parameter from the inner type?

That is, I want to achieve (an equivalent of) this:

interface JsonRepresentable<Self: JsonRepresentable<Self>> {
    fun toJson(): String

    interface Companion {
        operator fun invoke(json:String): Self?
    }
}


问:
Problems reading xml file with Chinese characters using UTF-8 encoding in RStudio
I want to read a .xml file which looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<province name="北京市" id="11">
  <city name="市辖区" id="110100000000">
    <county name="东城区" id="110101000000">
      <town name="珍珠泉乡" id="110229214000">
        <village name="珍珠泉乡社区居委会" id="110229214001" type="220"/>
        <village name="珍珠泉村委会" id="110229214200" type="210"/>
        <village name="称沟湾村委会" id="110229214201" type="220"/>
        <village name="庙梁村委会" id="110229214202" type="220"/>
        <village name="下水沟村委会" id="110229214203" type="220"/>
        <village name="上水沟村委会" id="110229214204" type="220"/>
        <village name="下花楼村委会" id="110229214205" type="220"/>
        <village name="八亩地村委会" id="110229214206" type="220"/>
        <village name="转山子村委会" id="110229214207" type="220"/>
        <village name="水泉子村委会" id="110229214208" type="220"/>
        <village name="双金草村委会" id="110229214209" type="220"/>
        <village name="小川村委会" id="110229214210" type="220"/>
        <village name="小铺村委会" id="110229214211" type="220"/>
        <village name="仓米道村委会" id="110229214212" type="220"/>
        <village name="南天门村委会" id="110229214213" type="220"/>
        <village name="桃条沟村委会" id="110229214214" type="220"/>
      </town>
    </county>
  </city>
</province>
</code>```

I set the system locale to be simplified Chinese using Sys.setlocale("LC_ALL", locale="Chinese (Simplified)"), and read the document using XML package with UTF-8 encoding doc = xmlParse(files[i], encoding = "UTF-8", useInternalNodes = TRUE), but when I look at doc, the Chinese characters are not properly displayed:

```<code><village id="110229214001" type="220" name="鐝嶇彔娉変埂绀惧尯灞呭浼?/>
        <village id="110229214200" type="210" name="鐝嶇彔娉夋潙濮斾細"/>
        <village id="110229214201" type="220" name="绉版矡婀炬潙濮斾細"/>
        <village id="110229214202" type="220" name="搴欐鏉戝浼?/>
        <village id="110229214203" type="220" name="涓嬫按娌熸潙濮斾細"/>
        <village id="110229214204" type="220" name="涓婃按娌熸潙濮斾細"/>
        <village id="110229214205" type="220" name="涓嬭姳妤兼潙濮斾細"/>
        <village id="110229214206" type="220" name="鍏憨鍦版潙濮斾細"/>
        <village id="110229214207" type="220" name="杞北瀛愭潙濮斾細"/>
        <village id="110229214208" type="220" name="姘存硥瀛愭潙濮斾細"/>
        <village id="110229214209" type="220" name="鍙岄噾鑽夋潙濮斾細"/>
        <village id="110229214210" type="220" name="灏忓窛鏉戝浼?/>
        <village id="110229214211" type="220" name="灏忛摵鏉戝浼?/>
        <village id="110229214212" type="220" name="浠撶背閬撴潙濮斾細"/>
        <village id="110229214213" type="220" name="鍗楀ぉ闂ㄦ潙濮斾細"/>
        <village id="110229214214" type="220" name="妗冩潯娌熸潙濮斾細"/>
</code>```

I also tried to set the system locale to English_United States.1252, but the problem remains the same.
One strange thing is that, when I use some functions over doc, for example xmlRoot(doc) or getNodeSet(doc,"//village")[1], the Chinese characters are displayed correctly. But not for all functions, if I use xmlAttrs(getNodeSet(doc,"//village")[[1]]), it has problem.

答:
It seems to be the problem with encoding. My aim is to extract the village information from the xml file. After I extracted the information, when I check the encoding of the village name column, it shows that the encoding is "unknown". So I added one command to make the encoding of that column as "UTF-8" and it works. My code is shown below.

But I still don't know why the encoding is unknown. I have already specified encoding="UTF-8 at the very beginning when I read the xml file using xmlParse(). Anyone knows why? Did I make any mistake when I read the xml file?

```<code>> village = as.data.frame(t(xmlSApply(doc["/province/city/county/town/village"],xmlAttrs)),stringsAsFactors=FALSE)
> View(village)
> Encoding(village[1,"name"])
[1] "unknown"
> Encoding(village[,"name"])="UTF-8"   #added this line and the display is fine now
</code>```

Body:
I want to read a .xml file which looks like:

<?xml version="1.0" encoding="UTF-8"?>
<province name="北京市" id="11">
  <city name="市辖区" id="110100000000">
    <county name="东城区" id="110101000000">
      <town name="珍珠泉乡" id="110229214000">
        <village name="珍珠泉乡社区居委会" id="110229214001" type="220"/>
        <village name="珍珠泉村委会" id="110229214200" type="210"/>
        <village name="称沟湾村委会" id="110229214201" type="220"/>
        <village name="庙梁村委会" id="110229214202" type="220"/>
        <village name="下水沟村委会" id="110229214203" type="220"/>
        <village name="上水沟村委会" id="110229214204" type="220"/>
        <village name="下花楼村委会" id="110229214205" type="220"/>
        <village name="八亩地村委会" id="110229214206" type="220"/>
        <village name="转山子村委会" id="110229214207" type="220"/>
        <village name="水泉子村委会" id="110229214208" type="220"/>
        <village name="双金草村委会" id="110229214209" type="220"/>
        <village name="小川村委会" id="110229214210" type="220"/>
        <village name="小铺村委会" id="110229214211" type="220"/>
        <village name="仓米道村委会" id="110229214212" type="220"/>
        <village name="南天门村委会" id="110229214213" type="220"/>
        <village name="桃条沟村委会" id="110229214214" type="220"/>
      </town>
    </county>
  </city>
</province>

I set the system locale to be simplified Chinese using Sys.setlocale("LC_ALL", locale="Chinese (Simplified)"), and read the document using XML package with UTF-8 encoding doc = xmlParse(files[i], encoding = "UTF-8", useInternalNodes = TRUE), but when I look at doc, the Chinese characters are not properly displayed:

<village id="110229214001" type="220" name="鐝嶇彔娉変埂绀惧尯灞呭浼?/>
        <village id="110229214200" type="210" name="鐝嶇彔娉夋潙濮斾細"/>
        <village id="110229214201" type="220" name="绉版矡婀炬潙濮斾細"/>
        <village id="110229214202" type="220" name="搴欐鏉戝浼?/>
        <village id="110229214203" type="220" name="涓嬫按娌熸潙濮斾細"/>
        <village id="110229214204" type="220" name="涓婃按娌熸潙濮斾細"/>
        <village id="110229214205" type="220" name="涓嬭姳妤兼潙濮斾細"/>
        <village id="110229214206" type="220" name="鍏憨鍦版潙濮斾細"/>
        <village id="110229214207" type="220" name="杞北瀛愭潙濮斾細"/>
        <village id="110229214208" type="220" name="姘存硥瀛愭潙濮斾細"/>
        <village id="110229214209" type="220" name="鍙岄噾鑽夋潙濮斾細"/>
        <village id="110229214210" type="220" name="灏忓窛鏉戝浼?/>
        <village id="110229214211" type="220" name="灏忛摵鏉戝浼?/>
        <village id="110229214212" type="220" name="浠撶背閬撴潙濮斾細"/>
        <village id="110229214213" type="220" name="鍗楀ぉ闂ㄦ潙濮斾細"/>
        <village id="110229214214" type="220" name="妗冩潯娌熸潙濮斾細"/>

I also tried to set the system locale to English_United States.1252, but the problem remains the same.
One strange thing is that, when I use some functions over doc, for example xmlRoot(doc) or getNodeSet(doc,"//village")[1], the Chinese characters are displayed correctly. But not for all functions, if I use xmlAttrs(getNodeSet(doc,"//village")[[1]]), it has problem.

Body:
It seems to be the problem with encoding. My aim is to extract the village information from the xml file. After I extracted the information, when I check the encoding of the village name column, it shows that the encoding is "unknown". So I added one command to make the encoding of that column as "UTF-8" and it works. My code is shown below.

But I still don't know why the encoding is unknown. I have already specified encoding="UTF-8 at the very beginning when I read the xml file using xmlParse(). Anyone knows why? Did I make any mistake when I read the xml file?

> village = as.data.frame(t(xmlSApply(doc["/province/city/county/town/village"],xmlAttrs)),stringsAsFactors=FALSE)
> View(village)
> Encoding(village[1,"name"])
[1] "unknown"
> Encoding(village[,"name"])="UTF-8"   #added this line and the display is fine now


问:
How to update array of object in reactjs
I can't figure out how to change state in my app correctly. For example, I want change 'modalStatus' key of a particular post to true, what should I write in my showModal function? I have the following data-structure:

```<code>class App extends React.Component {
constructor() {
super();
this.state = {
  posts: [
    {
      'author': 'Adolf Hitler',
      'img': 'http://www.jewishvirtuallibrary.org/images/hitler1.jpg',
      'content': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Iosif Stalin',
      'img': 'http://xn--h1aagokeh.xn--p1ai/wp-content/uploads/2016/07/46432404.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Napoleon Bonapard',
      'img':'http://cdn.history.com/sites/2/2015/04/hith-6-things-you-should-know-about-napoleon-E.jpeg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Vladimir Putin',
      'img':'http://realnienovosti.com/images/148795554214.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    }
  ]
};
</code>```

And function that is responsible for changing the state:

```<code>showModal () {
 this.setState(do something)
 }
</code>```

答:
Write it like this, pass a index to this function whose value you want to edit,

```<code>showModal (index) {
   var posts = JSON.parse(JSON.stringify(this.state.posts));
   posts[index].modalStatus = true;
   this.setState({posts});
}
</code>```

Check the DOC.

Or You could use the update immutability helper for this:

```<code>this.setState({
    posts: update(this.state.posts, {0: {modalStatus: {$set: true}}})
})
</code>```

Body:
I can't figure out how to change state in my app correctly. For example, I want change 'modalStatus' key of a particular post to true, what should I write in my showModal function? I have the following data-structure:

class App extends React.Component {
constructor() {
super();
this.state = {
  posts: [
    {
      'author': 'Adolf Hitler',
      'img': 'http://www.jewishvirtuallibrary.org/images/hitler1.jpg',
      'content': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Iosif Stalin',
      'img': 'http://xn--h1aagokeh.xn--p1ai/wp-content/uploads/2016/07/46432404.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Napoleon Bonapard',
      'img':'http://cdn.history.com/sites/2/2015/04/hith-6-things-you-should-know-about-napoleon-E.jpeg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Vladimir Putin',
      'img':'http://realnienovosti.com/images/148795554214.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    }
  ]
};

And function that is responsible for changing the state:

showModal () {
 this.setState(do something)
 }

Body:
Write it like this, pass a index to this function whose value you want to edit,

showModal (index) {
   var posts = JSON.parse(JSON.stringify(this.state.posts));
   posts[index].modalStatus = true;
   this.setState({posts});
}

Check the DOC.

Or You could use the update immutability helper for this:

this.setState({
    posts: update(this.state.posts, {0: {modalStatus: {$set: true}}})
})


问:
Building ViewModels based on nested Model Entities in WPF and MVVM Pattern
I have a problem understanding how to build view models based on the following models

(I simplified the models to be clearer)

```<code>public class Hit
{
   public bool On { get; set;}
   public Track Track { get; set; }
}
public class Track
{
   public ObservableCollection<Hit> Hits { get; set; }
   public LinearGradientBrush Color { get; set; }
   public Pattern Pattern { get; set; }
}
public class Pattern
{
   public string Name { get; set; }
   public ObservableCollection<Tracks> Tracks { get; set; }
}
</code>```

Now, my problem is, how to build the ViewModels..

I need to keep the original relationships through the models, beacaus i have a Serialize() method on the Pattern that serializes it to an XML file.. (with the related Tracks and Hits)

To be able to bind the pattern to the user controls and it's nested templates I should also have a PatternViewModel with an ObservableCollection<TrackViewModel> in it, same thing for the TrackViewModel and the HitViewModel.. and i neet to have custom presentation properties on the view models that aren't part of the business object (colors and more..)

It just seem not a good thing to me to duplicate all of the relationships of the models on the view models...
and keeping track of all this relations while coding the viewmodels is also much more error prone..

anyone has a better approach/solution?

答:
I ended up using part of the solution that Joe White suggested, in a slighty differ manner

The solution was to just leave the models as they were at the beginning, and attaching to the collections an eventhandler for CollectionChanged of the inner collections, for example, the PatternViewModel would be:

```<code>public class PatternViewModel : ISerializable
{
    public Pattern Pattern { get; set; }
    public ObservableCollection<TrackViewModel> Tracks { get; set; }

    public PatternViewModel(string name)
    {
        Pattern = new Pattern(name);
        Tracks = new ObservableCollection<TrackViewModel>();
        Pattern.Tracks.CollectionChanged += new NotifyCollectionChangedEventHandler(Tracks_CollectionChanged);
    }

    void Tracks_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                foreach (Track track in e.NewItems)
                {
                    var position = Pattern.Tracks.IndexOf((Track) e.NewItems[0]);
                    Tracks.Insert(position,new TrackViewModel(track, this));
                }
                break;
            case NotifyCollectionChangedAction.Remove:
                foreach (Track track in e.OldItems)
                    Tracks.Remove(Tracks.First(t => t.Track == track));
                break;
            case NotifyCollectionChangedAction.Move:
                for (int k = 0; k < e.NewItems.Count; k++)
                {
                    var oldPosition = Tracks.IndexOf(Tracks.First(t => t.Track == e.OldItems[k]));
                    var newPosition = Pattern.Tracks.IndexOf((Track) e.NewItems[k]);
                    Tracks.Move(oldPosition, newPosition);
                }
                break;
        }
    }
}
</code>```

So i can attach the new Color/Style/Command on the view models to keep my base models clean

And whenever I add/remove/move items in the base models collection, the view models collections remain in sync with each other

Luckily I don't have to manage lots of object in my application, so duplicated data and performance won't be a problem

I don't like it too much, but it works well, and it's not a huge amount of work, just an event handler for the view model that contains others view model collections (in my case, one for PatternViewModel to sync TrackViewModels and another on TrackViewModel to manage HitViewModels)

Still interested in your thoughs or better ideas =)

Body:
I have a problem understanding how to build view models based on the following models

(I simplified the models to be clearer)

public class Hit
{
   public bool On { get; set;}
   public Track Track { get; set; }
}
public class Track
{
   public ObservableCollection<Hit> Hits { get; set; }
   public LinearGradientBrush Color { get; set; }
   public Pattern Pattern { get; set; }
}
public class Pattern
{
   public string Name { get; set; }
   public ObservableCollection<Tracks> Tracks { get; set; }
}

Now, my problem is, how to build the ViewModels..

I need to keep the original relationships through the models, beacaus i have a Serialize() method on the Pattern that serializes it to an XML file.. (with the related Tracks and Hits)

To be able to bind the pattern to the user controls and it's nested templates I should also have a PatternViewModel with an ObservableCollection<TrackViewModel> in it, same thing for the TrackViewModel and the HitViewModel.. and i neet to have custom presentation properties on the view models that aren't part of the business object (colors and more..)

It just seem not a good thing to me to duplicate all of the relationships of the models on the view models...
and keeping track of all this relations while coding the viewmodels is also much more error prone..

anyone has a better approach/solution?

Body:
I ended up using part of the solution that Joe White suggested, in a slighty differ manner

The solution was to just leave the models as they were at the beginning, and attaching to the collections an eventhandler for CollectionChanged of the inner collections, for example, the PatternViewModel would be:

public class PatternViewModel : ISerializable
{
    public Pattern Pattern { get; set; }
    public ObservableCollection<TrackViewModel> Tracks { get; set; }

    public PatternViewModel(string name)
    {
        Pattern = new Pattern(name);
        Tracks = new ObservableCollection<TrackViewModel>();
        Pattern.Tracks.CollectionChanged += new NotifyCollectionChangedEventHandler(Tracks_CollectionChanged);
    }

    void Tracks_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                foreach (Track track in e.NewItems)
                {
                    var position = Pattern.Tracks.IndexOf((Track) e.NewItems[0]);
                    Tracks.Insert(position,new TrackViewModel(track, this));
                }
                break;
            case NotifyCollectionChangedAction.Remove:
                foreach (Track track in e.OldItems)
                    Tracks.Remove(Tracks.First(t => t.Track == track));
                break;
            case NotifyCollectionChangedAction.Move:
                for (int k = 0; k < e.NewItems.Count; k++)
                {
                    var oldPosition = Tracks.IndexOf(Tracks.First(t => t.Track == e.OldItems[k]));
                    var newPosition = Pattern.Tracks.IndexOf((Track) e.NewItems[k]);
                    Tracks.Move(oldPosition, newPosition);
                }
                break;
        }
    }
}

So i can attach the new Color/Style/Command on the view models to keep my base models clean

And whenever I add/remove/move items in the base models collection, the view models collections remain in sync with each other

Luckily I don't have to manage lots of object in my application, so duplicated data and performance won't be a problem

I don't like it too much, but it works well, and it's not a huge amount of work, just an event handler for the view model that contains others view model collections (in my case, one for PatternViewModel to sync TrackViewModels and another on TrackViewModel to manage HitViewModels)

Still interested in your thoughs or better ideas =)


问:
"... .exe hast stopped working" only occurs at my friend's computer but not on mine
I'm having a problem with the release version of my program. When I start it on my computer, everything works fine. There are no exceptions, no problems or any other stuff that stops me from working with the program. As soon as I zip the exe and its required DLLs and send it to a friend, he instantly receives the error ".exe has stopped working" when he tries to run the server.

By the way it's an opc server built with "open62541". When running, it retrieves values out of a PLC by the use of a library called "Snap7". And yes, he's located in the same network as I am, hence the reason cannot be the network connection.

We both are using windows and my IDE is Visual Studio 2015. Unfortunately, I cannot really post any code here because it's way too much. Moreover I wouldn't really know which code to post since I don't know where and why the error comes up.

EDIT: Here's my code where I get the exception. It's always thrown when "UA_Server_addVariableNode" is called.

```<code>for (int i = 0; i < 4; ++i)
{
    UA_VariableAttributes attrAttr;
    UA_VariableAttributes_init(&attrAttr);
    UA_QualifiedName attrBrowseName;
    UA_QualifiedName_init(&attrBrowseName);

    switch (i)
    {
    case 0: //Setting the ip-address
        UA_Variant_setScalar(&attrAttr.value, &UA_STRING(currentPlc.ip), &UA_TYPES[UA_TYPES_STRING]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "IPAddress");
        attrBrowseName = UA_QUALIFIEDNAME(1, "IPAddress");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;

    case 1: //Setting the rack
        UA_Variant_setScalar(&attrAttr.value, &currentPlc.rack, &UA_TYPES[UA_TYPES_INT32]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "Rack");
        attrBrowseName = UA_QUALIFIEDNAME(1, "Rack");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;

    case 2: //Setting the slot
        UA_Variant_setScalar(&attrAttr.value, &currentPlc.slot, &UA_TYPES[UA_TYPES_INT32]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "Slot");
        attrBrowseName = UA_QUALIFIEDNAME(1, "Slot");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;

    case 3: //Setting "isAvailable" to give information about the PLC's status
        UA_Variant_setScalar(&attrAttr.value, &isAvailable, &UA_TYPES[UA_TYPES_BOOLEAN]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "isAvailable");
        attrBrowseName = UA_QUALIFIEDNAME(1, "isAvailable");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;
    }
}
</code>```

答:
I solved the problem after doing some research inside the "open62541" header.

In case 0 I use the expression "&UA_STRING(currentPlc.ip)" in the "UA_Variant_setScalar" function which I thought returns the equivalent UA_String of "currentPlc.ip".

But it actually returns a temporary object that is deleted after the function is called. As a result, the actual address of the object is null, hence I get an access violation. I simply added one line in which I pass the returned object to a variable and then use the address of the variable.

```<code>case 0: //Setting the ip-address
        auto value = UA_STRING(currentPlc.ip);
        UA_Variant_setScalar(&attrAttr.value, &value, &UA_TYPES[UA_TYPES_STRING]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "IPAddress");
        attrBrowseName = UA_QUALIFIEDNAME(1, "IPAddress");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;
</code>```

Body:
I'm having a problem with the release version of my program. When I start it on my computer, everything works fine. There are no exceptions, no problems or any other stuff that stops me from working with the program. As soon as I zip the exe and its required DLLs and send it to a friend, he instantly receives the error ".exe has stopped working" when he tries to run the server.

By the way it's an opc server built with "open62541". When running, it retrieves values out of a PLC by the use of a library called "Snap7". And yes, he's located in the same network as I am, hence the reason cannot be the network connection.

We both are using windows and my IDE is Visual Studio 2015. Unfortunately, I cannot really post any code here because it's way too much. Moreover I wouldn't really know which code to post since I don't know where and why the error comes up.

EDIT: Here's my code where I get the exception. It's always thrown when "UA_Server_addVariableNode" is called.

for (int i = 0; i < 4; ++i)
{
    UA_VariableAttributes attrAttr;
    UA_VariableAttributes_init(&attrAttr);
    UA_QualifiedName attrBrowseName;
    UA_QualifiedName_init(&attrBrowseName);

    switch (i)
    {
    case 0: //Setting the ip-address
        UA_Variant_setScalar(&attrAttr.value, &UA_STRING(currentPlc.ip), &UA_TYPES[UA_TYPES_STRING]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "IPAddress");
        attrBrowseName = UA_QUALIFIEDNAME(1, "IPAddress");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;

    case 1: //Setting the rack
        UA_Variant_setScalar(&attrAttr.value, &currentPlc.rack, &UA_TYPES[UA_TYPES_INT32]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "Rack");
        attrBrowseName = UA_QUALIFIEDNAME(1, "Rack");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;

    case 2: //Setting the slot
        UA_Variant_setScalar(&attrAttr.value, &currentPlc.slot, &UA_TYPES[UA_TYPES_INT32]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "Slot");
        attrBrowseName = UA_QUALIFIEDNAME(1, "Slot");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;

    case 3: //Setting "isAvailable" to give information about the PLC's status
        UA_Variant_setScalar(&attrAttr.value, &isAvailable, &UA_TYPES[UA_TYPES_BOOLEAN]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "isAvailable");
        attrBrowseName = UA_QUALIFIEDNAME(1, "isAvailable");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;
    }
}

Body:
I solved the problem after doing some research inside the "open62541" header.

In case 0 I use the expression "&UA_STRING(currentPlc.ip)" in the "UA_Variant_setScalar" function which I thought returns the equivalent UA_String of "currentPlc.ip".

But it actually returns a temporary object that is deleted after the function is called. As a result, the actual address of the object is null, hence I get an access violation. I simply added one line in which I pass the returned object to a variable and then use the address of the variable.

case 0: //Setting the ip-address
        auto value = UA_STRING(currentPlc.ip);
        UA_Variant_setScalar(&attrAttr.value, &value, &UA_TYPES[UA_TYPES_STRING]);
        attrAttr.displayName = UA_LOCALIZEDTEXT("en_US", "IPAddress");
        attrBrowseName = UA_QUALIFIEDNAME(1, "IPAddress");

        //Add the PLC value to the PLC-ObjectType
        UA_Server_addVariableNode(server, UA_NODEID_NULL, newPlcId,
            UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
            attrBrowseName,
            UA_NODEID_NULL, attrAttr, NULL, &isAvailableNodeId);
        break;


问:
Error with my python code
I am new to python with great desire to learn the language. However, right now i need someone help with a code i am currently working on which keep flagging this error :
Oops, try again. get_average(alice) returned None instead of the expected 91.15

This is the question with my solution below also:
Write a function called get_average that takes a student dictionary (like lloyd, alice, or tyler) as input and returns his/her weighted average.

Define a function called get_average that takes one argument called student.
Make a variable homework that stores the average() of student["homework"].
Repeat step 2 for "quizzes" and "tests".
Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60%.

MY SOLUTION:

```<code>lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": 88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
 "homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
    total = sum(numbers)
    total = float(total)
    result = total/len(numbers)
    return result

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
    print Av
</code>```

答:
I've tested your code, fixed the missing opening bracket at line 4 (looyd quizzes) and it's working well.

```<code>    lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
    }
    alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
    }
    tyler = {
    "name": "Tyler",
     "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
    }

    # Add your function below!
    def average(numbers):
        total = sum(numbers)
        total = float(total)
        result = total/len(numbers)
        return result

    def get_average(student):
        homework = average(student["homework"])
        quizzes = average(student["quizzes"])
        tests = average(student["tests"])
        Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
        print Av

    get_average(alice)
</code>```

This code is printing 91.15 on my python 2.7

Title: Error with my python code

Body:
I am new to python with great desire to learn the language. However, right now i need someone help with a code i am currently working on which keep flagging this error :
Oops, try again. get_average(alice) returned None instead of the expected 91.15

This is the question with my solution below also:
Write a function called get_average that takes a student dictionary (like lloyd, alice, or tyler) as input and returns his/her weighted average.

Define a function called get_average that takes one argument called student.
Make a variable homework that stores the average() of student["homework"].
Repeat step 2 for "quizzes" and "tests".
Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60%.

MY SOLUTION:

lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": 88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
 "homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
    total = sum(numbers)
    total = float(total)
    result = total/len(numbers)
    return result

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
    print Av

Body:
I've tested your code, fixed the missing opening bracket at line 4 (looyd quizzes) and it's working well.

    lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
    }
    alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
    }
    tyler = {
    "name": "Tyler",
     "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
    }

    # Add your function below!
    def average(numbers):
        total = sum(numbers)
        total = float(total)
        result = total/len(numbers)
        return result

    def get_average(student):
        homework = average(student["homework"])
        quizzes = average(student["quizzes"])
        tests = average(student["tests"])
        Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
        print Av

    get_average(alice)

This code is printing 91.15 on my python 2.7


问:
Saving data to a file vs. saving it to MySQL DB
Using a PHP script I need to update a number every 5 seconds while somebody is on my page. So let's say I have 300 visitors, each one spending about 1 minute on the page and every 5 seconds they stay on the page the number will be changed...which is a total of 3600 changes per minute. I would prefer to update the number in my MySQL database, except I'm not sure if it's not too inefficient to have so many MySQL connections (just for the one number change), when I could just change the number in a file.

P.S.: I have no idea weather 3600 connections/minute is a high number or not, but what about this case in general, considering an even higher number of visitors. What is the most efficient way to do this?

答: Using a dedicated temporary file will certainly be the most efficient disk access you can have. However, you will not be protected from concurrent access to the file in case your server uses multiple threads or processes. If what you want to do is update 1 number per user, then using a $_SESSION sub-variable will work, and I believe this is stored in memory, so it shouldbe very efficient. Then you can easily store this number into your database every 5 minutes per user</p>


答:
```<code>let startDate = moment().startOf('month').subtract(1, 'months').toDate()
let endDate = moment().endOf('month').add(1, 'months').toDate()
</code>```

Title: Setting the day of the date to the 1st with moment.js


问:
The background cache eviction process was unable to free [10] percent of the cache for context
I am trying to deploy spring boot application on my server. I have kept my WAR file on webapps folder inside Tomcat.

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.privilance</groupId>
<artifactId>privilance_survey</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>privilance_survey</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.sf.barcode4j</groupId>
        <artifactId>barcode4j</artifactId>
        <version>2.1</version>
    </dependency>
    <!--
    <dependency>
        <groupId>net.sourceforge.nekohtml</groupId>
        <artifactId>nekohtml</artifactId>
        <version>1.9.21</version><!--$NO-MVN-MAN-VER$-->
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.11</version>
    </dependency>
</dependencies>
<build>
    <finalName>privilance</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

I did some search and find out some people solved their problem by adding this bean.

```<code>@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcatFactory = new TomcatEmbeddedServletContainerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            final int cacheSize = 40 * 1024;
            StandardRoot standardRoot = new StandardRoot(context);
            standardRoot.setCacheMaxSize(cacheSize);
            context.setResources(standardRoot); // This is what made it work in my case.

            logger.info(String.format("New cache size (KB): %d", context.getResources().getCacheMaxSize()));
        }
    };
    return tomcatFactory;
}
</code>```

But in my case this is also not working. Whenever I run localhost:8080/privilance on my browser says:

The origin server did not find a current representation for the target
  resource or is not willing to disclose that one exists.

and in my cmd prompt says:

the background cache eviction process was unable to free [10] percent
  of the cache for context. consider increasing maximum size of the
  cache ....approximately [9285] kb of data remained on the cache.

答: What you get in the cmd is probably warning ? I think this might be something to with the resouce configuration in web.xml. Please see Running servlet shows error. Hope it helps.</p>

Body:
I am trying to deploy spring boot application on my server. I have kept my WAR file on webapps folder inside Tomcat.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.privilance</groupId>
<artifactId>privilance_survey</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>privilance_survey</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.sf.barcode4j</groupId>
        <artifactId>barcode4j</artifactId>
        <version>2.1</version>
    </dependency>

    </dependency>

    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.0</version>
    </dependency>

    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.11</version>
    </dependency>
</dependencies>
<build>
    <finalName>privilance</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

I did some search and find out some people solved their problem by adding this bean.

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcatFactory = new TomcatEmbeddedServletContainerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            final int cacheSize = 40 * 1024;
            StandardRoot standardRoot = new StandardRoot(context);
            standardRoot.setCacheMaxSize(cacheSize);
            context.setResources(standardRoot); // This is what made it work in my case.

            logger.info(String.format("New cache size (KB): %d", context.getResources().getCacheMaxSize()));
        }
    };
    return tomcatFactory;
}

But in my case this is also not working. Whenever I run localhost:8080/privilance on my browser says:

The origin server did not find a current representation for the target
  resource or is not willing to disclose that one exists.

and in my cmd prompt says:

the background cache eviction process was unable to free [10] percent
  of the cache for context. consider increasing maximum size of the
  cache ....approximately [9285] kb of data remained on the cache.


问:
How can I avoid JS and use only CSS?
After several test, I haven't been able to do what I want to do with a pure css. How can I obtain the same result like the example below without using a javascript.

Is it possible to do that with a pure css?

Thanks.

jsfiddle Demo

var main = document.getElementsByClassName('container');
for(var i = 0; i < main.length; i++) {
 var height = main[i].childNodes[3].offsetHeight;
 main[i].style.height = height+"px";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}</code>```

```

答:
Like this?

I added height to the .container because since the children are positioned absolutely, they are out of the document's flow, meaning it's like .container doesn't have a child at all.

As for the height:100% for the .right-child, well it is so that it takes the height of the nearest relatively positioned element,which is the .container

.container {
  width: 100%;
  height: 200px;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 100%;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div>

<div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div></code>```

Title: How can I avoid JS and use only CSS?

Body:
After several test, I haven't been able to do what I want to do with a pure css. How can I obtain the same result like the example below without using a javascript.

Is it possible to do that with a pure css?

Thanks.

jsfiddle Demo

var main = document.getElementsByClassName('container');
for(var i = 0; i < main.length; i++) {
 var height = main[i].childNodes[3].offsetHeight;
 main[i].style.height = height+"px";
}

.container {
  width: 100%;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}

Body:
Like this?

I added height to the .container because since the children are positioned absolutely, they are out of the document's flow, meaning it's like .container doesn't have a child at all.

As for the height:100% for the .right-child, well it is so that it takes the height of the nearest relatively positioned element,which is the .container

.container {
  width: 100%;
  height: 200px;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 100%;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}

<div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div>

<div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div>


问:
Break statement misplaced in while-loop
I'd like to create a script that asks for the item you want from a list (array), check if the item is on stock, displays the inventory if your type "list" and quit the program (while loop) if you type "quit"

while (true) { // endless loop
  var search = prompt('Type the item you are looking for, type "list" to display the inventory, type "quit" to exit te store.');
  search = search.toLowerCase;
}
if (search = 'quit') {
  break; // if the client types quit, they exit the store, loop ends
} else if search == 'list'{
  write('
We currently have ' + inventory.join(', ') + ' in stock.
');
} else if (inventory.indexOf(search) > - 1) {
  write('
Yes, we have ' + search + ' in our stock.
');
} else {
  write('
Sorry, we don\'t have ' + search + ' in our stock
');
}```

The break statement is out of the loop but I don't really see where it should go ...

Any thoughts?

答:
There were several errors in your code, some syntactical such as missing parenthesis, or using only a single equal sign. The break keyword needs to be inside the loop, or it will have no loop to break out of.

However, if instead of the part where we say if(!search) continue; we said if(!search) break; you could break out of the loop by clicking cancel or entering an empty string, which makes more sense if you ask me.

var inventory = ['tea','sugar'];
while (true) { // endless loop
  var search = prompt('Type the item you are looking for, type "list" to display the inventory, type "quit" to exit te store.');

  if(!search) continue;

  search = search.toLowerCase();

  if (search == 'quit') {
    break; // if the client types quit, they exit the store, loop ends
  } else if (search == 'list') {
    alert('
We currently have ' + inventory.join(', ') + ' in stock.
');
  } else if (inventory.indexOf(search) > -1) {
    alert('
Yes, we have ' + search + ' in our stock.
');
  } else {
    alert('
Sorry, we don\'t have ' + search + ' in our stock
');
  }
}```

Title: Break statement misplaced in while-loop

Body:
I'd like to create a script that asks for the item you want from a list (array), check if the item is on stock, displays the inventory if your type "list" and quit the program (while loop) if you type "quit"

while (true) { // endless loop
  var search = prompt('Type the item you are looking for, type "list" to display the inventory, type "quit" to exit te store.');
  search = search.toLowerCase;
}
if (search = 'quit') {
  break; // if the client types quit, they exit the store, loop ends
} else if search == 'list'{
  write('
We currently have ' + inventory.join(', ') + ' in stock.
');
} else if (inventory.indexOf(search) > - 1) {
  write('
Yes, we have ' + search + ' in our stock.
');
} else {
  write('
Sorry, we don\'t have ' + search + ' in our stock
');
}

The break statement is out of the loop but I don't really see where it should go ...

Any thoughts?

Body:
There were several errors in your code, some syntactical such as missing parenthesis, or using only a single equal sign. The break keyword needs to be inside the loop, or it will have no loop to break out of.

However, if instead of the part where we say if(!search) continue; we said if(!search) break; you could break out of the loop by clicking cancel or entering an empty string, which makes more sense if you ask me.

var inventory = ['tea','sugar'];
while (true) { // endless loop
  var search = prompt('Type the item you are looking for, type "list" to display the inventory, type "quit" to exit te store.');

  if(!search) continue;

  search = search.toLowerCase();

  if (search == 'quit') {
    break; // if the client types quit, they exit the store, loop ends
  } else if (search == 'list') {
    alert('<p>We currently have ' + inventory.join(', ') + ' in stock.</p>');
  } else if (inventory.indexOf(search) > -1) {
    alert('<p>Yes, we have ' + search + ' in our stock.</p>');
  } else {
    alert('<p>Sorry, we don\'t have ' + search + ' in our stock</p>');
  }
}


问:
PHP vprintf in magic method
My PHP contains translatable values as constants. By calling the class with the name of the constant, the formatted value should be returned.

```<code>class Test {
    const translation_value = 'Foo %s, bar %s';
    public static function __callStatic($string, $args) {
        return vsprintf(constant("self::" . $string), $args);
    }
}
</code>```

If I call the class via Test::{"translation_value"}(["test", "test2"]); PHP show two errors:

Notice: Array to string conversion [...] on line 4

  PHP Warning:  vsprintf(): Too few arguments [...] on line 4

What am I doing wrong?

If I test the vprintf function by calling it manually (vsprintf("Foo %s, bar %s", ["val1", "val2"]);) PHP creates the expected output: Foo val1, bar val2

答:
The second parameter of __callStatic($string, $args) is a list of arguments. You have 1 argument, so you need either to use first element of the array:

```<code>return vsprintf(constant("self::" . $string), $args[0]);
</code>```

Or invoke it with flat parameters:

```<code>Test::translation_value("test", "test2");
</code>```

Title: PHP vprintf in magic method

Body:
My PHP contains translatable values as constants. By calling the class with the name of the constant, the formatted value should be returned.

class Test {
    const translation_value = 'Foo %s, bar %s';
    public static function __callStatic($string, $args) {
        return vsprintf(constant("self::" . $string), $args);
    }
}

If I call the class via Test::{"translation_value"}(["test", "test2"]); PHP show two errors:

Notice: Array to string conversion [...] on line 4

  PHP Warning:  vsprintf(): Too few arguments [...] on line 4

What am I doing wrong?

If I test the vprintf function by calling it manually (vsprintf("Foo %s, bar %s", ["val1", "val2"]);) PHP creates the expected output: Foo val1, bar val2

Body:
The second parameter of __callStatic($string, $args) is a list of arguments. You have 1 argument, so you need either to use first element of the array:

return vsprintf(constant("self::" . $string), $args[0]);

Or invoke it with flat parameters:

Test::translation_value("test", "test2");


问:
Tables with same structure and other tables with foreign keys
I want to create 3 Tables (I will call them Elements), that have nearly the same structure, and 4 tables (Informations) for each Elements that are linked with foreign keys.
The Informations have the same structure

```<code>CREATE TABLE Information (
     element INT UNSIGNED,
     information INT UNSIGNED,
     PRIMARY KEY (element, information),
     FOREIGN KEY element ON ElementTable(id) ON DELETE CASCADE,
     FOREIGN KEY information ON InformationTable(id) ON DELETE CASCADE
);
</code>```

The problem is that i want to create a unique table for all informations instead of having 12 tables (4 for each Elements), like that :

```<code>CREATE TABLE Information (
     --
     element_type VARCHAR(10),
     information_type VARCHAR(10),
     --
     element INT UNSIGNED,
     information INT UNSIGNED,
     PRIMARY KEY (element, information),
     FOREIGN KEY element ON ElementTable(id) ON DELETE CASCADE,
     FOREIGN KEY information ON InformationTable(id) ON DELETE CASCADE
);
</code>```

But foreign keys don't work like that.

While searching i found "polymorphic associations" but it lose the advantages of foreign keys that can cascade and that i am using. Or is there a way to mimic cascade without the foreign keys.

Also, is this better, in term of storage and performances to have the single table i want to create or the 12 tables (And do more (?) requests) knowing that each Elements can have more than 10 Information from each types of information.

答:
I tried this

```<code>CREATE TABLE ElementInformation (
     element INT UNSIGNED NOT NULL,
     information INT UNSIGNED NOT NULL,
     element_type VARCHAR(10) NOT NULL,
     information_type VARCHAR(10) NOT NULL,
     PRIMARY KEY (element, information, element_type, information_type)
 );
</code>```

And the trigger for each Elements

```<code>DELIMITER //
CREATE TRIGGER on_delete_element
AFTER DELETE ON Element
FOR EACH ROW
BEGIN
    DELETE FROM ElementInformation WHERE element_type=type AND element=OLD.id;
END//
DELIMITER ;
</code>```

This works as intended, thanks @Carolina Gil.
My last question about the performance isn't answered, but it will be the same with just a few thousands elements and information i guess.

Body:
I want to create 3 Tables (I will call them Elements), that have nearly the same structure, and 4 tables (Informations) for each Elements that are linked with foreign keys.
The Informations have the same structure

CREATE TABLE Information (
     element INT UNSIGNED,
     information INT UNSIGNED,
     PRIMARY KEY (element, information),
     FOREIGN KEY element ON ElementTable(id) ON DELETE CASCADE,
     FOREIGN KEY information ON InformationTable(id) ON DELETE CASCADE
);

The problem is that i want to create a unique table for all informations instead of having 12 tables (4 for each Elements), like that :

CREATE TABLE Information (
     --
     element_type VARCHAR(10),
     information_type VARCHAR(10),
     --
     element INT UNSIGNED,
     information INT UNSIGNED,
     PRIMARY KEY (element, information),
     FOREIGN KEY element ON ElementTable(id) ON DELETE CASCADE,
     FOREIGN KEY information ON InformationTable(id) ON DELETE CASCADE
);

But foreign keys don't work like that.

While searching i found "polymorphic associations" but it lose the advantages of foreign keys that can cascade and that i am using. Or is there a way to mimic cascade without the foreign keys.

Also, is this better, in term of storage and performances to have the single table i want to create or the 12 tables (And do more (?) requests) knowing that each Elements can have more than 10 Information from each types of information.

Body:
I tried this

CREATE TABLE ElementInformation (
     element INT UNSIGNED NOT NULL,
     information INT UNSIGNED NOT NULL,
     element_type VARCHAR(10) NOT NULL,
     information_type VARCHAR(10) NOT NULL,
     PRIMARY KEY (element, information, element_type, information_type)
 );

And the trigger for each Elements

DELIMITER //
CREATE TRIGGER on_delete_element
AFTER DELETE ON Element
FOR EACH ROW
BEGIN
    DELETE FROM ElementInformation WHERE element_type=type AND element=OLD.id;
END//
DELIMITER ;

This works as intended, thanks @Carolina Gil.
My last question about the performance isn't answered, but it will be the same with just a few thousands elements and information i guess.


问:
Single Dev team working on multiple product backlogs (Products)
We have one Dev Team (Approx 20 Team members) currently working on 5 products with 5 product owners (one for each product). We are struggling with story prioritization between different products and lots of meetings for the same.

Below are the two options we are looking at:

1. Merging product backlogs to a single product backlog

So that team can pull stories from one product backlog to sprint backlog. (And does not have to bother about priorities anymore). But a single product backlog maybe too huge and unmanageable.

2. Separating the team into 5 teams for each product

But this is not currently possible as we have resources specialized it a particular skillet and needs to be shared across the products.

Any suggestions?

答:
I have a couple of things to point out, the tasks priorities are not responsibility of the development team at all, this is something that is managed by the PO for many reasons, but lets not discuss about that.

As you don't have a single PO this is transformed in a fight of interests. If there is no common goal between them every PO will want their US to be done ASAP because is the highest priority for them (and this is totally understandable).

So, if you want to keep one single team for all this products you will need a PO that works as single point of contact for the Dev team, a single backlog for them and then you can try to make sprint goals focused on single products so the dev team does not have to change their "environment" in the middle of the sprint (but this is a bonus point, not mandatory).

The main thing is if it is possible to have this single PO to manage this single backlog, at the end its the same as if your current 5 POs becomes stakeholders, they will ask for what they want, and this single PO will put those thing in order. Based on what ? could be company need, if there are blocking issues or it could go as easy as money ... who is the one that is paying the most and thats the one you will attend first.

In resume, remove the responsibility of picking the task to be developed off the team, it could be by this single PO approach, by a forum between the PO where they manage the single product backlog all together. And those are my 2 propositions.

There are too many factors in place, the company, the POs shared vision and needs, the reason why there is 1 single team that is managing all this.. etc.

We are currently working with one single team for multiple products as well and we have just one PO and a single product backlog and things goes smoothly.

Hope this helps! Any doubt just tell me!