问:
Error: derefferencing out of bounds pointer
Given the below code, I get the following error at runtime

FATAL RUN-TIME ERROR: line 21, col 11, thread id 0x00002068:

  Dereference of out-of-bounds pointer: 1 bytes (1 elements) past end of
  array.

What am I doing wrong here? I create a 2D char array and initialize all elements to 'x'. Then I attempt to print all elements by using the pointer logic. It prints the characters to standard IO but then throws the runtime error. I don't see where the out of bounds is occurring.

```<code>#include <stdio.h>
#define EDGE 10

int main(void){

    char fabric[EDGE][EDGE];
    char *cell = fabric;
    int totalCells = EDGE*EDGE;

    for(int i = 0; i < totalCells; ++i){
            *(cell + i) = 'x';
    }

    cell = fabric; //set cell to point back to first element

    while(*cell){                  //while there is content at address, print content
        printf("%c", *cell);
        ++cell;
    }

    getchar();
    return 0;

}
</code>```

答:
First of all the array does not contain a string. So this condition

```<code>while(*cell){
</code>```

results in undefined behaviour.

Also you have to cast pointers in the declaration and in the statement

```<code>char *cell = ( char * )fabric;

cell = ( char * )fabric;
</code>```

because there is no implicit conversion from the type char ( * )[EDGE] to the type char *.

Body:
Given the below code, I get the following error at runtime

FATAL RUN-TIME ERROR: line 21, col 11, thread id 0x00002068:

  Dereference of out-of-bounds pointer: 1 bytes (1 elements) past end of
  array.

What am I doing wrong here? I create a 2D char array and initialize all elements to 'x'. Then I attempt to print all elements by using the pointer logic. It prints the characters to standard IO but then throws the runtime error. I don't see where the out of bounds is occurring.

#include <stdio.h>
#define EDGE 10

int main(void){

    char fabric[EDGE][EDGE];
    char *cell = fabric;
    int totalCells = EDGE*EDGE;

    for(int i = 0; i < totalCells; ++i){
            *(cell + i) = 'x';
    }

    cell = fabric; //set cell to point back to first element

    while(*cell){                  //while there is content at address, print content
        printf("%c", *cell);
        ++cell;
    }

    getchar();
    return 0;

}

Body:
First of all the array does not contain a string. So this condition

while(*cell){

results in undefined behaviour.

Also you have to cast pointers in the declaration and in the statement

char *cell = ( char * )fabric;

cell = ( char * )fabric;

because there is no implicit conversion from the type char ( * )[EDGE] to the type char *.


来源: stackexchange

问:
Installed e(fx)clipse from the eclipse marketplace but running JavaFX application still gives error
So I downloaded the e(fx)clipse from the eclipse marketplace and when I click on New > Project > JavaFX project it creates a new project bundle but it already has errors in the import statements.

The errors say :

```<code>     The import javafx cannot be resolved
</code>```

I am using Windows 10 , Jdk 12 and e(fx)clipse version 3.5.0 .

Any help appreciated, thanks.

答:
If you want to learn simple JavaFx application, you do not need e(fx) eclipse plugin necessarily. Still if you want to leverage the usage of e(fx), you can go through this following step by step tutorial.

https://wiki.eclipse.org/Efxclipse/Tutorials/AddingE(fx)clipse_to_eclipse

While creating a program, make sure that jfxrt.jar is in the classpath. It will be available in the jdk installation.

ContentLicense: CC BY-SA 4.0

Body:
So I downloaded the e(fx)clipse from the eclipse marketplace and when I click on New > Project > JavaFX project it creates a new project bundle but it already has errors in the import statements.

The errors say :

     The import javafx cannot be resolved

I am using Windows 10 , Jdk 12 and e(fx)clipse version 3.5.0 .

Any help appreciated, thanks.


问:
How to convert Double to String with exponential sign
I want to convert a Double to String with exponential signs in it.
For example, Double value is 4.4395749E7 after converting to String it should be 4.4395749E+07 (Same as how it shows in MS Excel).

I have tried double.toString(), but it is converting to 4.4395749E7:

```<code>Double doubleValue = 44395749d;
doubleValue.toString();
</code>```

Expected is 4.4395749E+07, but actual is 4.4395749E7.

答:
you can use String.format(), E is the format code for exponentials

```<code>Double doubleValue = 44395749d;
System.out.println(String.format("%E", doubleValue));
</code>```

Body:
I want to convert a Double to String with exponential signs in it.
For example, Double value is 4.4395749E7 after converting to String it should be 4.4395749E+07 (Same as how it shows in MS Excel).

I have tried double.toString(), but it is converting to 4.4395749E7:

Double doubleValue = 44395749d;
doubleValue.toString();

Expected is 4.4395749E+07, but actual is 4.4395749E7.

Body:
you can use String.format(), E is the format code for exponentials

Double doubleValue = 44395749d;
System.out.println(String.format("%E", doubleValue));


问:
Run 'openssl req' command in Java?
It seems x509 cert request can only be generated by Openssl that Java has no control over that. So I decided to invoke Openssl command in Java; my system is Windows7-64bit, JDK 1.7, Openssl 1.02 binary distribution.

Generating CSR request is good via direct Openssl command, but invoking the same command in Java reports an error.

Openssl command:

```<code>openssl req -new -key bob.pem -out bob.csr -subj /C=CN
</code>```

Java code:

```<code>Process p;
String command="openssl req -new -key bob.pem -out bob.csr -subj /C=CN";
Runtime r=Runtime.getRuntime();
p=r.exec(command);
</code>```

Error message:

```<code>unable to load Private Key
8016:error:0906D06C:PEM routines:PEM_read_bio:no start line:.\crypto\pem\pem_lib.c:701:Expecting: ANY PRIVATE KEY
</code>```

The .pem is indeed private key generated by openssl. Please give me hand. Thanks.

bob.pem is generated via this command:

```<code>openssl genrsa -out bob.pem

-----BEGIN RSA PRIVATE KEY-----
MIIEpgIBAAKCAQEA25I5wAAGJIBvQtLXghdCjwDuNTbIQX9ISx4ZRDL5CQl8WU7U
vxEnGxJHiJBPE1aJOXSL12LGgzgsnw7G5MIMsJoGI929H8VaiM+iU96+eA6TE6xu
5DheApLiUwq62fybHg1bnXZlHhXUSIQYhTT2dvYMVXnhKO99siLIcKG8LK3H1JUE
KGKShO+0skiA0f70J8hFSGgeB2VCClMkEgoGslYkYnlKNNP38rEWaQdlQdVZGu4q
8okkRcsHsG0vJRx5G7uateoo8uWwqMhVF1tLEcYAYJhOOInofo6MVyqdZ55i8DTb
IPv80kMqx4tmxDN4Q+yjN6PpgijWIG0fA0GlcQIDAQABAoIBAQDNlxkjweH+g5Oq
Ciln0ceshr6EbQsM6NUUINafmOq9n3gjV0C0tqbbHj6EjDq+bKSIe6wEvKQLcam2
NOvefiPLqCxfoNvYx72BpIjl5waI+3yTSz15y52a41WvU7ipK3FCrlc+FQGRLfda
/vTGpVSxBql9z2UYI0aaaR8s9wNvAHzBbfbGTE0JpmTbviyZipj0y18Dykqt5eUO
Wj1Ox0+0hkub7vbVjRIRBUDdsxvLcPZMwPQwdWOsuTH/3wxe/bqczVPVlbDBDok/
xmwd03pqh0+78I6BP/r9eyxwwwe2L94lf+zsojsIu17WlzH9fGhAxfkixTA8TM8l
L/Y1LAgBAoGBAO4gBAaY4VCcoYcGoDbzOXbRBHgN/gvmtVuakidpwA+RSiO2cqgz
bik0d5sSWLqbbxXta+aQdUwX9ngeWUm2dugZP3umkjUfCvrsic6QxiX7up0M5OYF
ukFMaUL0ukr8g7VIA2JaXheia9gEIMnDTbjebA+J/qIUujqfdOACIQ1RAoGBAOwN
qk3kZajPV/Ja3Ij7mAGa5dPwomFTKfBUwbj8cMDDNK+LsR2SpPh8aaIsoWCUwgCB
O3E3TSXql/DvxcgrvRJ52XNm8hERpoCcJ+ol3VmPL+g2C9btjGb6HglON0hiXKAN
F78cSv59OhBbOqbLzhx06XtlKbaxNigWBkQW3I4hAoGBAJnK9a6pGIRu1OgXQGyd
BBUYA9Hh/50CIUmLeC+aXh/vzzlngX/ez5wvNbxiygmjj8hSseiUjh1aMKX9u98e
yIc4n0amGzHR3c6X7J0L5d3sSedax49ETboUtrs2wgbiNdJkM0NXaAPNs+ctK1wE
FnN6u8IBdwKJbomkKODwnxYxAoGBAK2yzIvuskPK91tWMwv1nwAnXFFdtA9L5AN+
SuL1l36w5fb7IwSw4QYcfpqgnst0C2HVtsjzuahZ/R6FQZOvY7zRvwplSWD4DP58
af6piD0b2VPVWVb5jCRGjo2oaZOxFZmMqNmvVxv3SB+7Eeik9fEIsrpjUZOmyUQs
GMZH0FohAoGBANHXkYWRQKSJp02kmwJ1GZ/6905KnDOY9pjFEXTb657yYXvPb1tp
B8pVBwtsrXb6XT827Dpn3Rf/bitqwWwJuWwSc37C/6AavUHQGo1lm8+m86Imy4XJ
xOOhZIpmJocMSF9TBBYFLvJV+s3/1aXrnFPuc5rrh3A1jWtT/zN+lUON
-----END RSA PRIVATE KEY-----
</code>```

答:
You could always just put the openssl commands in a bash script, and then launch the bash script from your program like this</p>

```<code>Process bash_script = Runtime.getRuntime().exec("/your/directory/openssl_script.sh");
</code>```

ContentLicense: CC BY-SA 3.0

Title: Run 'openssl req' command in Java?

Body:
It seems x509 cert request can only be generated by Openssl that Java has no control over that. So I decided to invoke Openssl command in Java; my system is Windows7-64bit, JDK 1.7, Openssl 1.02 binary distribution.

Generating CSR request is good via direct Openssl command, but invoking the same command in Java reports an error.

Openssl command:

openssl req -new -key bob.pem -out bob.csr -subj /C=CN

Java code:

Process p;
String command="openssl req -new -key bob.pem -out bob.csr -subj /C=CN";
Runtime r=Runtime.getRuntime();
p=r.exec(command);

Error message:

unable to load Private Key
8016:error:0906D06C:PEM routines:PEM_read_bio:no start line:.\crypto\pem\pem_lib.c:701:Expecting: ANY PRIVATE KEY

The .pem is indeed private key generated by openssl. Please give me hand. Thanks.

bob.pem is generated via this command:

openssl genrsa -out bob.pem

-----BEGIN RSA PRIVATE KEY-----
MIIEpgIBAAKCAQEA25I5wAAGJIBvQtLXghdCjwDuNTbIQX9ISx4ZRDL5CQl8WU7U
vxEnGxJHiJBPE1aJOXSL12LGgzgsnw7G5MIMsJoGI929H8VaiM+iU96+eA6TE6xu
5DheApLiUwq62fybHg1bnXZlHhXUSIQYhTT2dvYMVXnhKO99siLIcKG8LK3H1JUE
KGKShO+0skiA0f70J8hFSGgeB2VCClMkEgoGslYkYnlKNNP38rEWaQdlQdVZGu4q
8okkRcsHsG0vJRx5G7uateoo8uWwqMhVF1tLEcYAYJhOOInofo6MVyqdZ55i8DTb
IPv80kMqx4tmxDN4Q+yjN6PpgijWIG0fA0GlcQIDAQABAoIBAQDNlxkjweH+g5Oq
Ciln0ceshr6EbQsM6NUUINafmOq9n3gjV0C0tqbbHj6EjDq+bKSIe6wEvKQLcam2
NOvefiPLqCxfoNvYx72BpIjl5waI+3yTSz15y52a41WvU7ipK3FCrlc+FQGRLfda
/vTGpVSxBql9z2UYI0aaaR8s9wNvAHzBbfbGTE0JpmTbviyZipj0y18Dykqt5eUO
Wj1Ox0+0hkub7vbVjRIRBUDdsxvLcPZMwPQwdWOsuTH/3wxe/bqczVPVlbDBDok/
xmwd03pqh0+78I6BP/r9eyxwwwe2L94lf+zsojsIu17WlzH9fGhAxfkixTA8TM8l
L/Y1LAgBAoGBAO4gBAaY4VCcoYcGoDbzOXbRBHgN/gvmtVuakidpwA+RSiO2cqgz
bik0d5sSWLqbbxXta+aQdUwX9ngeWUm2dugZP3umkjUfCvrsic6QxiX7up0M5OYF
ukFMaUL0ukr8g7VIA2JaXheia9gEIMnDTbjebA+J/qIUujqfdOACIQ1RAoGBAOwN
qk3kZajPV/Ja3Ij7mAGa5dPwomFTKfBUwbj8cMDDNK+LsR2SpPh8aaIsoWCUwgCB
O3E3TSXql/DvxcgrvRJ52XNm8hERpoCcJ+ol3VmPL+g2C9btjGb6HglON0hiXKAN
F78cSv59OhBbOqbLzhx06XtlKbaxNigWBkQW3I4hAoGBAJnK9a6pGIRu1OgXQGyd
BBUYA9Hh/50CIUmLeC+aXh/vzzlngX/ez5wvNbxiygmjj8hSseiUjh1aMKX9u98e
yIc4n0amGzHR3c6X7J0L5d3sSedax49ETboUtrs2wgbiNdJkM0NXaAPNs+ctK1wE
FnN6u8IBdwKJbomkKODwnxYxAoGBAK2yzIvuskPK91tWMwv1nwAnXFFdtA9L5AN+
SuL1l36w5fb7IwSw4QYcfpqgnst0C2HVtsjzuahZ/R6FQZOvY7zRvwplSWD4DP58
af6piD0b2VPVWVb5jCRGjo2oaZOxFZmMqNmvVxv3SB+7Eeik9fEIsrpjUZOmyUQs
GMZH0FohAoGBANHXkYWRQKSJp02kmwJ1GZ/6905KnDOY9pjFEXTb657yYXvPb1tp
B8pVBwtsrXb6XT827Dpn3Rf/bitqwWwJuWwSc37C/6AavUHQGo1lm8+m86Imy4XJ
xOOhZIpmJocMSF9TBBYFLvJV+s3/1aXrnFPuc5rrh3A1jWtT/zN+lUON
-----END RSA PRIVATE KEY-----

Body:
You could always just put the openssl commands in a bash script, and then launch the bash script from your program like this

Process bash_script = Runtime.getRuntime().exec("/your/directory/openssl_script.sh");


问:
Simpler way to use array of class
I have a class and then defined an array of class, each time that I want to add a node to array, I have to mention the class name that I don't like it:

```<code>export class ItemModel {
  constructor(
    ID,
    Name
  ) {
    this.ID = ID;
    this.Name = Name;
  }
}

export var ItemsArray = [];

ItemsArray.push(new ItemModel(0, "BreakFast"));
ItemsArray.push(new ItemModel(1, "Lunch"));
ItemsArray.push(new ItemModel(2, "Dinner"));
</code>```

After reading this post:

https://answers.unity.com/questions/637902/how-to-use-javascript-array-with-classes.html

I tried to declare the class at the time that I define the array like this:

```<code>var ItemsArray : ItemModel[];
</code>```

but I get error : "Types Can only be used in .ts files.

I searched google for that but none of them was helpful.

Any recommendation would be appreciated.

答:
Another alternative is to create a class that holds your items and make a method to add/remove them. This way, you won't have to new up your array items everytime. ...Well, you will. You just don't have to do it, the code will.

class ItemModel {
  constructor(id, name) {
    this.id = id;
    this.name = name;
  }
}

class ItemModelCollection {
  constructor() {
    this.items = [];
  }
  addItem(id, name) {
    if (Array.isArray(this.items)) {
      this.items.push(new ItemModel(id, name));
    }
  }
  removeItem(id) {
    if (Array.isArray(this.items)) {
      this.items = this.items.filter( i => i.id !== id);
    }
  }
}

const itemCollection = new ItemModelCollection();
document.getElementById('addItem').onclick = (e) => {
  const id = itemCollection.items.length; // obviously figure out a better id generator
  itemCollection.addItem(id, `Item Number ${id}`);
  console.log(itemCollection);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="addItem">Add Item</button></code>```

I should also note that not doing new ItemModel(id, name) and doing the mentioned typescript way (<ItemModel>{ id: id, name: name}) is fine, but if the class has methods, they will not work since you are not 'newing it up'. If you just set the properties without initializing the class, you essentially lose the point of having the class.

Related/Explantion for the pattner/issues with classes (not really angular specific like the article says): Angular : Class and Interface

Title: Simpler way to use array of class

Body:
I have a class and then defined an array of class, each time that I want to add a node to array, I have to mention the class name that I don't like it:

export class ItemModel {
  constructor(
    ID,
    Name
  ) {
    this.ID = ID;
    this.Name = Name;
  }
}

export var ItemsArray = [];

ItemsArray.push(new ItemModel(0, "BreakFast"));
ItemsArray.push(new ItemModel(1, "Lunch"));
ItemsArray.push(new ItemModel(2, "Dinner"));

After reading this post:

https://answers.unity.com/questions/637902/how-to-use-javascript-array-with-classes.html

I tried to declare the class at the time that I define the array like this:

var ItemsArray : ItemModel[];

but I get error : "Types Can only be used in .ts files.

I searched google for that but none of them was helpful.

Any recommendation would be appreciated.

Body:
Another alternative is to create a class that holds your items and make a method to add/remove them. This way, you won't have to new up your array items everytime. ...Well, you will. You just don't have to do it, the code will.

class ItemModel {
  constructor(id, name) {
    this.id = id;
    this.name = name;
  }
}

class ItemModelCollection {
  constructor() {
    this.items = [];
  }
  addItem(id, name) {
    if (Array.isArray(this.items)) {
      this.items.push(new ItemModel(id, name));
    }
  }
  removeItem(id) {
    if (Array.isArray(this.items)) {
      this.items = this.items.filter( i => i.id !== id);
    }
  }
}

const itemCollection = new ItemModelCollection();
document.getElementById('addItem').onclick = (e) => {
  const id = itemCollection.items.length; // obviously figure out a better id generator
  itemCollection.addItem(id, `Item Number ${id}`);
  console.log(itemCollection);
};

<button id="addItem">Add Item</button>

I should also note that not doing new ItemModel(id, name) and doing the mentioned typescript way (<ItemModel>{ id: id, name: name}) is fine, but if the class has methods, they will not work since you are not 'newing it up'. If you just set the properties without initializing the class, you essentially lose the point of having the class.

Related/Explantion for the pattner/issues with classes (not really angular specific like the article says): Angular : Class and Interface


问:
OnTouch bitmap overlayed
I'm developing a game where different bitmap run on the screen (a SurfaceView). Since they have different speed, it happen that sometimes two characters are superimposed, one behind the other. I've used the OnTouch function to catch the moment when the player touch the character. However, when two characters are superimposed, I always "touch" the one that is behind, I never touch the other one in front of him. Why? How I can change this behaviour? Since I'm touching the one in front, it's is really annoying that I always touch the other behind.
I hope the problem is clear.

Thanks!

Edit: This is my OnTouchEvent function:

```<code>@Override
public boolean onTouchEvent(MotionEvent event){
    synchronized (getHolder()) {

        boolean chibi_toccato = false;

        if (!blocco_tocco){
</code>```

// Here I have the structure (a Vector) containing the chibis to be shown

```<code>        for (int i = (mChibiVector.size() - 1); i >= 0; i--) {
            Chibi chibi = mChibiVector.elementAt(i);

        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            if (!chibi_toccato){
</code>```

// touched is a flag that tell if a chibi were touched before

```<code>                if (chibi.touched) {
</code>```

// if I touch on the boat bitmap (somewhere on the screen) the chibi will be safe

```<code>                    int navexend = posiz_nave_x + thread.mNave.getWidth();
                    int naveyend = posiz_nave_y + thread.mNave.getHeight();
                    if ((int) event.getX() >= posiz_nave_x &&
                            (int) event.getX() <= navexend &&
                            (int) event.getY() >= posiz_nave_y &&
                            (int) event.getY() <= naveyend){
                        chibi.chibisalvo = true;

                        thread.calcola_vel_x(chibi);
                        thread.calcola_vel_y(chibi);
                        } else {
                            chibi.touched = false;

                            int temp_chibi_y = chibi.getCoordinate().getY();

                            chibi.getCoordinate().setY(
                                    temp_chibi_y +
                                    chibi.getBitmapDimensions()[1]);

                        }
                    chibi_toccato = true;
                } else {
                // Here I check if a chibi is touched:

                    chibi = thread.checkTouched(chibi, (int) event.getX(),
                            (int) event.getY());

                    if (chibi.touched){
// If the chibi is touched, I save the X-Y info:

                        chibi.getCoordinate().setTouchedX((int) event.getX());
                        chibi.getCoordinate().setTouchedY((int) event.getY());

                        int temp_chibi_y = chibi.getCoordinate().getY();

                        chibi.getCoordinate().setY(
                                temp_chibi_y -
                                chibi.getBitmapDimensions()[1]);

                        chibi_toccato = true;
                        }
                    }
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {

                if (chibi.touched){

                    chibi_toccato = false;

                int navexend = posiz_nave_x + thread.mNave.getWidth();
                int naveyend = posiz_nave_y + thread.mNave.getHeight();
                if ((int) event.getX() >= posiz_nave_x &&
                        (int) event.getX() <= navexend &&
                        (int) event.getY() >= posiz_nave_y &&
                        (int) event.getY() <= naveyend){
                    chibi.chibisalvo = true;

                    thread.calcola_vel_x(chibi);
                    thread.calcola_vel_y(chibi);
                    }
                }
            }
        }
        }
    }
    return true;
}
</code>```

答:
Well, after a while, finally I got the issue. The problem were in the for cycle:

for (int i = (mChibiVector.size() - 1); i >= 0; i--)

Since I started to pick the frames from the end of the vector, the first touch were always on the image behind the others. I'm still wondering why, but finally I changed the for cycle starting from the first vector item to the end and it worked.

Hope it could be useful for others.

ContentLicense: CC BY-SA 2.5

Title: OnTouch bitmap overlayed

Body:
I'm developing a game where different bitmap run on the screen (a SurfaceView). Since they have different speed, it happen that sometimes two characters are superimposed, one behind the other. I've used the OnTouch function to catch the moment when the player touch the character. However, when two characters are superimposed, I always "touch" the one that is behind, I never touch the other one in front of him. Why? How I can change this behaviour? Since I'm touching the one in front, it's is really annoying that I always touch the other behind.
I hope the problem is clear.

Thanks!

Edit: This is my OnTouchEvent function:

@Override
public boolean onTouchEvent(MotionEvent event){
    synchronized (getHolder()) {

        boolean chibi_toccato = false;

        if (!blocco_tocco){

// Here I have the structure (a Vector) containing the chibis to be shown

        for (int i = (mChibiVector.size() - 1); i >= 0; i--) {
            Chibi chibi = mChibiVector.elementAt(i);

        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            if (!chibi_toccato){

// touched is a flag that tell if a chibi were touched before

                if (chibi.touched) {

// if I touch on the boat bitmap (somewhere on the screen) the chibi will be safe

                    int navexend = posiz_nave_x + thread.mNave.getWidth();
                    int naveyend = posiz_nave_y + thread.mNave.getHeight();
                    if ((int) event.getX() >= posiz_nave_x &&
                            (int) event.getX() <= navexend &&
                            (int) event.getY() >= posiz_nave_y &&
                            (int) event.getY() <= naveyend){
                        chibi.chibisalvo = true;

                        thread.calcola_vel_x(chibi);
                        thread.calcola_vel_y(chibi);
                        } else {
                            chibi.touched = false;

                            int temp_chibi_y = chibi.getCoordinate().getY();

                            chibi.getCoordinate().setY(
                                    temp_chibi_y +
                                    chibi.getBitmapDimensions()[1]);

                        }
                    chibi_toccato = true;
                } else {
                // Here I check if a chibi is touched:

                    chibi = thread.checkTouched(chibi, (int) event.getX(),
                            (int) event.getY());

                    if (chibi.touched){
// If the chibi is touched, I save the X-Y info:

                        chibi.getCoordinate().setTouchedX((int) event.getX());
                        chibi.getCoordinate().setTouchedY((int) event.getY());

                        int temp_chibi_y = chibi.getCoordinate().getY();

                        chibi.getCoordinate().setY(
                                temp_chibi_y -
                                chibi.getBitmapDimensions()[1]);

                        chibi_toccato = true;
                        }
                    }
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {

                if (chibi.touched){

                    chibi_toccato = false;

                int navexend = posiz_nave_x + thread.mNave.getWidth();
                int naveyend = posiz_nave_y + thread.mNave.getHeight();
                if ((int) event.getX() >= posiz_nave_x &&
                        (int) event.getX() <= navexend &&
                        (int) event.getY() >= posiz_nave_y &&
                        (int) event.getY() <= naveyend){
                    chibi.chibisalvo = true;

                    thread.calcola_vel_x(chibi);
                    thread.calcola_vel_y(chibi);
                    }
                }
            }
        }
        }
    }
    return true;
}


问:
Trouble returning date from DatePickerDialog fragment when using Navigation Controller
I am trying to return a date selected from my DatePickerDialog. I know there are a few questions about this here on SO and I am sure I have checked for those in my code and I still can't get the date back into my fragment that calls the DatePickerDialog.

I am using the Navigation confonent to show the dialog, could that be what is causing the issue?

Here is my DatePickerDialog:

```<code>class DatePickerFragment : DialogFragment(), DatePickerDialog.OnDateSetListener {

    private var onDateSetListener: DatePickerDialog.OnDateSetListener? = null

    fun setListeningActivity(listener: DatePickerDialog.OnDateSetListener) {
        onDateSetListener = listener
    }

    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        onDateSetListener?.onDateSet(view,year, month, dayOfMonth)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // Use the current date as the default date in the picker
        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)

        // Create a new instance of DatePickerDialog and return it
        return DatePickerDialog(context, this, year, month, day)
    }
}
</code>```

Relevant code from the fragment calling the Datepicker:

```<code>private fun showDatePicker(hasFocus: Boolean, view: View) {
    Log.i(FRAGMENT_NAME, "Has focus $hasFocus")
    val fragment = DatePickerFragment()
    fragment.setListeningActivity(this)
    if (hasFocus) {
        Navigation.findNavController(view).navigate(R.id.datePickerFragment)
    }
}

override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
    Log.i(FRAGMENT_NAME, "Date received: $year-$month-$day")
    fragmentView.dateOfBirthField.editText?.setText("$year-$month-$day")
}
</code>```

This is how I am calling the showDatePicker method:

fragmentView.dateOfBirthField.editText?.setOnFocusChangeListener { _, hasFocus -> showDatePicker(hasFocus, fragmentView) }

Question: How do I get the date back into the Fragment that calls the DatePickerDialog. I do not want to have the DatePickerDialog as an internal class to the class that calls it.

答:
One can either set a target Fragment:

```<code>val fragment = DatePickerFragment()
fragment.setTargetFragment(this, requestCode)
</code>```

or let it deliver the result to an Activity:

```<code>val fragment = DatePickerFragment()
fragment.setListeningActivity(this)
</code>```

this should happen before showing the DialogFragment; so that the DialogFragment will already know where it has to deliver it's result to. For either delivery destination, method onDateSet() needs to return an Intent with an extras Bundle... and onActivityResult() needs to process that result and update the GUI accordingly. This is how the communication in between Activity & Fragment works - and this also applies to a DialogFragment. Method onActivityResult() may handle the callbacks from both, Activity and Fragment.

In Java that would be something alike this - for returning the result in the DialogFragment, in method override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int):

```<code>/* converting the selection to long integer */
GregorianCalendar date = new java.util.GregorianCalendar();
date.set(GregorianCalendar.YEAR, year);
date.set(GregorianCalendar.MONTH, month);
date.set(GregorianCalendar.DAY_OF_MONTH, day);
Log.d(LOG_TAG, "confirmed " + date.getTime());
long dueDate = date.getTime().getTime();

if (getTargetFragment() != null) {

    /* stuffing the result value into a Bundle */
    Intent intent = this.getActivity().getIntent();
    Bundle extras = new Bundle();
    extras.putLong(ArgumentKeys.ARGUMENT_SELECT_DUE_DATE, dueDate);
    intent.putExtras(extras);

    /* this delivers the result */
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);

    /* close dialog */
    this.dismiss();

} else {
    Log.w(LOG_TAG, ".setTargetFragment() had not been called.");
}
</code>```

or similarly for returning to an Activity:

```<code>if(this.dialog.getOwnerActivity() != null) {
    ...
}
</code>```

and the onActivityResult() of the Activity or Fragment which opened the DialogFragment:

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    Bundle extras = intent.getExtras();
    if(resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case RequestCodes.REQUESTCODE_TASK_DUE_DATE: {
                if(extras != null) {
                    long dueDate = extras.getLong(ArgumentKeys.ARGUMENT_SELECT_DUE_DATE, -1);

                        /* set the value in here */
                    }
                }
            }
            ...
    }
}
</code>```

returning a Fragment result works almost alike returning an Activity result.

Body:
I am trying to return a date selected from my DatePickerDialog. I know there are a few questions about this here on SO and I am sure I have checked for those in my code and I still can't get the date back into my fragment that calls the DatePickerDialog.

I am using the Navigation confonent to show the dialog, could that be what is causing the issue?

Here is my DatePickerDialog:

class DatePickerFragment : DialogFragment(), DatePickerDialog.OnDateSetListener {

    private var onDateSetListener: DatePickerDialog.OnDateSetListener? = null

    fun setListeningActivity(listener: DatePickerDialog.OnDateSetListener) {
        onDateSetListener = listener
    }

    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        onDateSetListener?.onDateSet(view,year, month, dayOfMonth)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // Use the current date as the default date in the picker
        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)

        // Create a new instance of DatePickerDialog and return it
        return DatePickerDialog(context, this, year, month, day)
    }
}

Relevant code from the fragment calling the Datepicker:

private fun showDatePicker(hasFocus: Boolean, view: View) {
    Log.i(FRAGMENT_NAME, "Has focus $hasFocus")
    val fragment = DatePickerFragment()
    fragment.setListeningActivity(this)
    if (hasFocus) {
        Navigation.findNavController(view).navigate(R.id.datePickerFragment)
    }
}

override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
    Log.i(FRAGMENT_NAME, "Date received: $year-$month-$day")
    fragmentView.dateOfBirthField.editText?.setText("$year-$month-$day")
}

This is how I am calling the showDatePicker method:

fragmentView.dateOfBirthField.editText?.setOnFocusChangeListener { _, hasFocus -> showDatePicker(hasFocus, fragmentView) }

Question: How do I get the date back into the Fragment that calls the DatePickerDialog. I do not want to have the DatePickerDialog as an internal class to the class that calls it.

Body:
One can either set a target Fragment:

val fragment = DatePickerFragment()
fragment.setTargetFragment(this, requestCode)

or let it deliver the result to an Activity:

val fragment = DatePickerFragment()
fragment.setListeningActivity(this)

this should happen before showing the DialogFragment; so that the DialogFragment will already know where it has to deliver it's result to. For either delivery destination, method onDateSet() needs to return an Intent with an extras Bundle... and onActivityResult() needs to process that result and update the GUI accordingly. This is how the communication in between Activity & Fragment works - and this also applies to a DialogFragment. Method onActivityResult() may handle the callbacks from both, Activity and Fragment.

In Java that would be something alike this - for returning the result in the DialogFragment, in method override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int):

/* converting the selection to long integer */
GregorianCalendar date = new java.util.GregorianCalendar();
date.set(GregorianCalendar.YEAR, year);
date.set(GregorianCalendar.MONTH, month);
date.set(GregorianCalendar.DAY_OF_MONTH, day);
Log.d(LOG_TAG, "confirmed " + date.getTime());
long dueDate = date.getTime().getTime();

if (getTargetFragment() != null) {

    /* stuffing the result value into a Bundle */
    Intent intent = this.getActivity().getIntent();
    Bundle extras = new Bundle();
    extras.putLong(ArgumentKeys.ARGUMENT_SELECT_DUE_DATE, dueDate);
    intent.putExtras(extras);

    /* this delivers the result */
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);

    /* close dialog */
    this.dismiss();

} else {
    Log.w(LOG_TAG, ".setTargetFragment() had not been called.");
}

or similarly for returning to an Activity:

if(this.dialog.getOwnerActivity() != null) {
    ...
}

and the onActivityResult() of the Activity or Fragment which opened the DialogFragment:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    Bundle extras = intent.getExtras();
    if(resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case RequestCodes.REQUESTCODE_TASK_DUE_DATE: {
                if(extras != null) {
                    long dueDate = extras.getLong(ArgumentKeys.ARGUMENT_SELECT_DUE_DATE, -1);

                        /* set the value in here */
                    }
                }
            }
            ...
    }
}

returning a Fragment result works almost alike returning an Activity result.


问:
Add Value to Array Without Specifying A Key C#
Like in PHP and some other languages, is there a way to add a value to an array without specifying the index?

```<code>int[] aWhich = {};

aWhich[] = 1;
</code>```

Thanks.

答:
Edit: this method does NOT work for adding a new array item.

```<code>myArray[myArray.Length] = newArrayItem;
</code>```

.Length - # will work for overwriting array items.

Body:
Like in PHP and some other languages, is there a way to add a value to an array without specifying the index?

int[] aWhich = {};

aWhich[] = 1;

Thanks.

Body:
Edit: this method does NOT work for adding a new array item.

myArray[myArray.Length] = newArrayItem;

.Length - # will work for overwriting array items.


问:
Why is a period in a character class not matching only a literal period
```<code>console.log("<p>email@address.com</p>".match(/([a-zA-Z0-9.-_+]+@[a-zA-Z0-9.-]+\.[a-z]{2,10})/g))
</code>```

["
email@address.com"]

Can someone help me understand why the < > characters are matching this regular expression? I always thought that a . in a character class [] was interpreted literally.

When I remove the ., it no longer returns that paragraph tag.

答:
You are matching .-_ (all characters in the range from . to _) which includes all the characters in the ASCII range 46-95.

To fix this, escape the - by writing \-

```<code>([a-zA-Z0-9.\-_+]+@[a-zA-Z0-9.-]+\.[a-z]{2,10})
            ^ note backslash here
</code>```

Body:
console.log("
email@address.com
".match(/([a-zA-Z0-9.-_+]+@[a-zA-Z0-9.-]+\.[a-z]{2,10})/g))

["
email@address.com"]

Can someone help me understand why the < > characters are matching this regular expression? I always thought that a . in a character class [] was interpreted literally.

When I remove the ., it no longer returns that paragraph tag.

Body:
You are matching .-_ (all characters in the range from . to _) which includes all the characters in the ASCII range 46-95.

To fix this, escape the - by writing \-

([a-zA-Z0-9.\-_+]+@[a-zA-Z0-9.-]+\.[a-z]{2,10})
            ^ note backslash here


问:
How could I Deserialize this xml to class
I want to deserialize a XML file to a class but it fails. Please Help!!

XML file like this:

```<code><messages>
   <message name="a">
  <field name="ab"/>
  <field name="ab1"/>
  <field name="ab2"/>
 </message>
   <message name="b">
      <field name="bc"/>
      <group name="ab">
         <field name="ab"/>
         <field name="ab1"/>
         <field name="ab2"/>
          <group name="ab">
             <field name="4"/>
           </group>
      </group>
       <field />
       ....

    </message>
</messages>
</code>```

this is just a demo.The reality is a "message" include several "field" and "group",and the group include several field and also group!!!
It is random not constant.

I have try this:

```<code>[XmlInclude(typeof(GroupInMsg))]
[XmlType("field")]
public class FieldBase
{
    [XmlAttribute("name")]
    public string name { get; set; }

}

[XmlType("message")]
public class Message
{
    public Message()
    {

    }
    [XmlAttribute("name")]
    public string name { get; set; }

    public FieldBase[] Fields { get; set; }
}

public class GroupInMsg : FieldBase
{
    public GroupInMsg()
    {

    }

    //[XmlArrayItem(Type = typeof(FieldBase))]
    //[XmlArrayItem(Type = typeof(GroupInMsg))]
    public FieldBase[] Fields { get; set; }
}
</code>```

My final target is to Deserialize the Quickfix Something like this

```<code><messages>
    <message name="Heartbeat" msgtype="0" msgcat="admin">
      <field name="TestReqID" required="N"/>
    </message>
    <message name="Logon" msgtype="A" msgcat="admin">
      <field name="EncryptMethod" required="Y"/>
      <field name="HeartBtInt" required="Y"/>
      <field name="RawDataLength" required="N"/>
      <field name="RawData" required="N"/>
      <field name="ResetSeqNumFlag" required="N"/>
      <field name="MaxMessageSize" required="N"/>
      <group name="NoMsgTypes" required="N">
        <field name="RefMsgType" required="N"/>
        <field name="MsgDirection" required="N"/>
      </group>
    </message>
    <message name="TestRequest" msgtype="1" msgcat="admin">
      <field name="TestReqID" required="Y"/>
    </message>
    <message name="ResendRequest" msgtype="2" msgcat="admin">
      <field name="BeginSeqNo" required="Y"/>
      <field name="EndSeqNo" required="Y"/>
    </message>
    <message name="Reject" msgtype="3" msgcat="admin">
      <field name="RefSeqNum" required="Y"/>
      <field name="RefTagID" required="N"/>
      <field name="RefMsgType" required="N"/>
      <field name="SessionRejectReason" required="N"/>
      <field name="Text" required="N"/>
      <field name="EncodedTextLen" required="N"/>
      <field name="EncodedText" required="N"/>
    </message>
    <message name="SequenceReset" msgtype="4" msgcat="admin">
      <field name="GapFillFlag" required="N"/>
      <field name="NewSeqNo" required="Y"/>
    </message>
    <message name="Logout" msgtype="5" msgcat="admin">
      <field name="Text" required="N"/>
      <field name="EncodedTextLen" required="N"/>
      <field name="EncodedText" required="N"/>
    </message>
......
</code>```

many messges.many feild and group in messge.And also many group and field in group!!!

Forgive me!Thanks!

答:
@ppz.whenever you want to ask something help or solution On StackOverflow community. I mean what you expect or facing some error You have to describe a proper way.so that the community will understand and provide a better solution asap.
You can refer below code
As per XML data you provided to us.
  Model

```<code>[XmlRoot(ElementName = "field")]
    public class Field
    {
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
    }

    [XmlRoot(ElementName = "message")]
    public class Message
    {
        [XmlElement(ElementName = "field")]
        public List<Field> Field { get; set; }
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
        [XmlElement(ElementName = "group")]
        public Group Group { get; set; }
    }

    [XmlRoot(ElementName = "group")]
    public class Group
    {
        [XmlElement(ElementName = "field")]
        public List<Field> Field { get; set; }
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
    }

    [XmlRoot(ElementName = "messages")]
    public class Messages
    {
        [XmlElement(ElementName = "message")]
        public List<Message> Message { get; set; }
    }
</code>```

And you deserialize your XML like below

```<code>string path = string.Empty;
            string xmlInputData = string.Empty;
            try
            {
               path = "XML file path";
                xmlInputData = File.ReadAllText(path);
                Messages _Messages = Deserialize<Messages>(xmlInputData);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public static T Deserialize<T>(string input) where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
            {
                return (T)ser.Deserialize(sr);
            }
        }
</code>```

I hope It helps you. Thank you..!

Body:
I want to deserialize a XML file to a class but it fails. Please Help!!

XML file like this:

<messages>
   <message name="a">
  <field name="ab"/>
  <field name="ab1"/>
  <field name="ab2"/>
 </message>
   <message name="b">
      <field name="bc"/>
      <group name="ab">
         <field name="ab"/>
         <field name="ab1"/>
         <field name="ab2"/>
          <group name="ab">
             <field name="4"/>
           </group>
      </group>
       <field />
       ....

    </message>
</messages>

this is just a demo.The reality is a "message" include several "field" and "group",and the group include several field and also group!!!
It is random not constant.

I have try this:

[XmlInclude(typeof(GroupInMsg))]
[XmlType("field")]
public class FieldBase
{
    [XmlAttribute("name")]
    public string name { get; set; }

}

[XmlType("message")]
public class Message
{
    public Message()
    {

    }
    [XmlAttribute("name")]
    public string name { get; set; }

    public FieldBase[] Fields { get; set; }
}

public class GroupInMsg : FieldBase
{
    public GroupInMsg()
    {

    }

    //[XmlArrayItem(Type = typeof(FieldBase))]
    //[XmlArrayItem(Type = typeof(GroupInMsg))]
    public FieldBase[] Fields { get; set; }
}

My final target is to Deserialize the Quickfix Something like this

<messages>
    <message name="Heartbeat" msgtype="0" msgcat="admin">
      <field name="TestReqID" required="N"/>
    </message>
    <message name="Logon" msgtype="A" msgcat="admin">
      <field name="EncryptMethod" required="Y"/>
      <field name="HeartBtInt" required="Y"/>
      <field name="RawDataLength" required="N"/>
      <field name="RawData" required="N"/>
      <field name="ResetSeqNumFlag" required="N"/>
      <field name="MaxMessageSize" required="N"/>
      <group name="NoMsgTypes" required="N">
        <field name="RefMsgType" required="N"/>
        <field name="MsgDirection" required="N"/>
      </group>
    </message>
    <message name="TestRequest" msgtype="1" msgcat="admin">
      <field name="TestReqID" required="Y"/>
    </message>
    <message name="ResendRequest" msgtype="2" msgcat="admin">
      <field name="BeginSeqNo" required="Y"/>
      <field name="EndSeqNo" required="Y"/>
    </message>
    <message name="Reject" msgtype="3" msgcat="admin">
      <field name="RefSeqNum" required="Y"/>
      <field name="RefTagID" required="N"/>
      <field name="RefMsgType" required="N"/>
      <field name="SessionRejectReason" required="N"/>
      <field name="Text" required="N"/>
      <field name="EncodedTextLen" required="N"/>
      <field name="EncodedText" required="N"/>
    </message>
    <message name="SequenceReset" msgtype="4" msgcat="admin">
      <field name="GapFillFlag" required="N"/>
      <field name="NewSeqNo" required="Y"/>
    </message>
    <message name="Logout" msgtype="5" msgcat="admin">
      <field name="Text" required="N"/>
      <field name="EncodedTextLen" required="N"/>
      <field name="EncodedText" required="N"/>
    </message>
......

many messges.many feild and group in messge.And also many group and field in group!!!

Forgive me!Thanks!

Body:
@ppz.whenever you want to ask something help or solution On StackOverflow community. I mean what you expect or facing some error You have to describe a proper way.so that the community will understand and provide a better solution asap.
You can refer below code
As per XML data you provided to us.
  Model

[XmlRoot(ElementName = "field")]
    public class Field
    {
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
    }

    [XmlRoot(ElementName = "message")]
    public class Message
    {
        [XmlElement(ElementName = "field")]
        public List<Field> Field { get; set; }
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
        [XmlElement(ElementName = "group")]
        public Group Group { get; set; }
    }

    [XmlRoot(ElementName = "group")]
    public class Group
    {
        [XmlElement(ElementName = "field")]
        public List<Field> Field { get; set; }
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }
    }

    [XmlRoot(ElementName = "messages")]
    public class Messages
    {
        [XmlElement(ElementName = "message")]
        public List<Message> Message { get; set; }
    }

And you deserialize your XML like below

string path = string.Empty;
            string xmlInputData = string.Empty;
            try
            {
               path = "XML file path";
                xmlInputData = File.ReadAllText(path);
                Messages _Messages = Deserialize<Messages>(xmlInputData);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public static T Deserialize<T>(string input) where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
            {
                return (T)ser.Deserialize(sr);
            }
        }

I hope It helps you. Thank you..!


问:
Calling method from grandchild component in angular 7
I have an angular 7 application and trying to call method of Parent from its grandchild component. I have Modal Component which is the grand child component. I am trying to call the method from there. I am calling the same method from its  immediate parent by using output event which works
 but how do I call from the grandchild.

I have declared Event

@Output() termDetailsEvent = new EventEmitter<string>();
```

<p>And call the parent method this way: <code>this.termDetailsEvent.next('getTermsDetails');</code> </p>

<p>Parent Component</p>

<pre class="lang-js prettyprint-override"><code>    import { Component, OnInit, Input, ViewChild } from '@angular/core';
    import { TermsService } from '../services/terms.service';
    import { FundClassesComponent } from './fundClasses/fundClasses.component';

    @Component({
        selector: 'mgr-terms',
        templateUrl: 'terms.component.html'
    })

    export class TermsComponent implements OnInit {

        private Error: string;
        public TermDetails: any;
        private _ManagerStrategyId: number;
        FilteredClasses: any;
        OriginalList: any;
        Funds: any;
        FundClassType: any;
        FirmFunds: any;
        public get ManagerStrategyId(): number {
            return this._ManagerStrategyId;
        }

        @ViewChild(FundClassesComponent)
        fundClassesComponent: FundClassesComponent;

        @Input()
        public set ManagerStrategyId(value: number) {
            this._ManagerStrategyId = value;
        }
        FundClasses: any;
        LegalFundClasses: any;
        originalFundClasses: any;
        constructor(private termsService: TermsService) { }

        ngOnInit() {
            this.init();
        }

        init() {
            this.getTermsDetails();
        }

        public getTermsDetails() {
            if (this.ManagerStrategyId != null) {
                this.termsService.getTermsDetails(this.ManagerStrategyId).subscribe((data: any) => {
                    this.TermDetails = data;
                    this.OriginalList = JSON.parse(JSON.stringify(data));
                    this.FundClasses = this.TermDetails.FundClassViewModel;
                    this.LegalFundClasses = this.TermDetails.LegalFundClassViewModel;
                    this.Funds = this.TermDetails.LegalFundClassViewModel.Funds;
                    this.FundClassType = this.TermDetails.LegalFundClassViewModel.FundClassType;
                    this.FirmFunds = this.TermDetails.LegalFundClassViewModel.FirmFunds;

                    this.TermDetails.FundClassViewModel.FundDetailsViewModel.forEach(funDetail=> {
                        funDetail.FundClassDetailsViewModel = funDetail.FundClassDetailsViewModel
                            .reduce((prev, next) => prev = prev.concat(next), [])
                            .filter(obj => obj.InvestedAmount !== null);
                    });

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

Parent component html

<mgr-fund-classes (termDetailsEvent)="getFundInvestedDetails($event)" [FundClasses]="FundClasses" ></mgr-fund-classes>

<mgr-legal-fund-classes  (termDetailsEvent)="getTermsDetails()" [Funds] = "Funds" [FundClassType] = "FundClassType" [LegalFundClasses]="LegalFundClasses" [FirmFunds] ="FirmFunds" ></mgr-legal-fund-classes>
```

<p>Child component</p>

<pre class="lang-js prettyprint-override"><code>    import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from '@angular/core';
    import { TermsService } from '../../services/terms.service';
    import { NotifyService } from '../../utilities/notify.service';
    import { number } from '@amcharts/amcharts4/core';
    import { IReview } from '../terms.interface';
    import { AddLegalFundClassComponent } from './addLegalFundClass.component';
    import { AddSideLetterComponent } from './addSideLetter.component';
    import { CloneLegalFundClassComponent } from './cloneLegalFundClass.component';

    @Component({
        selector: 'mgr-legal-fund-classes',
        templateUrl: './legalFundClasses.component.html'
    })

    export class LegalFundClassesComponent implements OnInit {

        private _legalFundClasses: any;
        LegalFundClass: any;

        @Output() termDetailsEvent = new EventEmitter<string>();

        public get LegalFundClasses(): any {
            return this._legalFundClasses;
        }
        @Input()
        public set LegalFundClasses(value: any) {
            this._legalFundClasses = value;
        }

        public defaultItem: { Name: string, Id: number } = { Name: "Select item...", Id: null };

        constructor(private termsService: TermsService, private notify: NotifyService) { }

        ngOnInit() {
            this.init();
        }

        public value: any = [{ Id: null, Name: "" }];

        Update(id) {
            this.LegalFundClass = this.LegalFundClasses.LegalFundClassDetailsViewModel
                  .find(obj => obj.Id === id);

            this.termsService.updateLegalFundClasses(this.LegalFundClass).then((result) => {
                if (result) {
                    this.notify.success('Legal Fund Class Details Successfully Updated');
                    this.EditMode[id] = !this.EditMode[id];
                    this.termDetailsEvent.next('getTermsDetails');
                }
            }).catch(err => {
                this.notify.error('An Error Has Occured While Updating Legal Fund Class Details');
            });
        }

        Delete(id) {

            this.termsService.deleteLegalFundClasses(id).then((result) => {
                if (result) {
                    this.notify.success('Legal Fund Class Successfully Deleted');
                    this.EditMode = !this.EditMode[id];
                    this.termDetailsEvent.next('getTermsDetails');
                }
            }).catch(err => {
                this.notify.error('An Error Has Occured While Deleting Fund Class Details');
            });
        }
</code>```

Child component html

<shared-modal [modalSize]="1" class="survey-edit" [open]="cloneLegalFundClassWindowOpened">

<button aria-label="Dismiss" class="close" style="margin-top: -10px"
                    type="button" (click)="dismissCloneModal()">X</button>

        <app-clone-legalclass  (termDetailsEvent)="getTermsDetails()" [FirmFunds]="FirmFunds"></app-clone-legalclass>

</shared-modal>
```

<p>Grand child component</p>

<pre class="lang-js prettyprint-override"><code>    export class CloneLegalFundClassComponent implements OnInit {

        private Error: string;
        public ManagerDetails: any;
        public EditorConfig: string;
        public CloneLegalFundClass: ICloneLegalFundClass;

        @Input() FirmFunds: any;
        @Output() termDetailsEvent = new EventEmitter<string>();

        constructor(private termsService: TermsService, private notify: NotifyService) {
        }

        ngOnInit() {

            this.CloneLegalFundClass = { Description: '', Id: null, FundId: null };
        }

        cloneLegalFundClass() {
            this.CloneLegalFundClass.FundId = this.FirmFunds.find(x => x.Id === this.CloneLegalFundClass.Id).FundId;
            this.termsService.cloneLegalFundClasses(this.CloneLegalFundClass).then((result) => {
                if (result) {
                    this.notify.success('Legal Fund Class Cloned Successfully');
                    this.termDetailsEvent.next('getTermsDetails');
                }
            }).catch(err => {
                this.notify.error('An Error Has Occured While cloning Legal Fund Class');
            });
        }

        closeLegalFundClass() {

        }
    }
</code>```

答:
I created a simple Stackblitz showing how to do it. You just continue emitting further out:
https://stackblitz.com/edit/angular-ad4kf3

Grandchild ts:

```<code>    import { Component, Output, EventEmitter, OnInit } from '@angular/core';
import { timer } from 'rxjs';

@Component({
  selector: 'app-grandchild',
  templateUrl: './grandchild.component.html',
  styleUrls: ['./grandchild.component.css']
})
export class GrandchildComponent implements OnInit {
  @Output() emitToChild: EventEmitter<void> = new EventEmitter();
  constructor() { }

  ngOnInit() {
    // emitting to child every two seconds, check console
    this.emit();
  }

  emit() {
    this.emitToChild.emit();
    timer(2000).subscribe(() => this.emit());
  }
}
</code>```

Grandchild HTML:

```<code><p>I'm grandchild.</p>
</code>```

Child TS:

```<code>import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Output() emitToParent: EventEmitter<void> = new EventEmitter();
  constructor() { }

  ngOnInit() {
  }

}
</code>```

Child HTML:

```<code><p>I'm child.</p>
<app-grandchild (emitToChild)="emitToParent.emit()"></app-grandchild>
</code>```

Parent TS:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  doSomething() {
    console.log('hello');
  }
}
</code>```

Parent HTML:

```<code><p>I'm Parent</p>

<app-child (emitToParent)="doSomething()"></app-child>
</code>```

Body:
I have an angular 7 application and trying to call method of Parent from its grandchild component. I have Modal Component which is the grand child component. I am trying to call the method from there. I am calling the same method from its  immediate parent by using output event which works
 but how do I call from the grandchild.

I have declared Event

@Output() termDetailsEvent = new EventEmitter<string>();

And call the parent method this way: this.termDetailsEvent.next('getTermsDetails');

Parent Component

    import { Component, OnInit, Input, ViewChild } from '@angular/core';
    import { TermsService } from '../services/terms.service';
    import { FundClassesComponent } from './fundClasses/fundClasses.component';

    @Component({
        selector: 'mgr-terms',
        templateUrl: 'terms.component.html'
    })

    export class TermsComponent implements OnInit {

        private Error: string;
        public TermDetails: any;
        private _ManagerStrategyId: number;
        FilteredClasses: any;
        OriginalList: any;
        Funds: any;
        FundClassType: any;
        FirmFunds: any;
        public get ManagerStrategyId(): number {
            return this._ManagerStrategyId;
        }

        @ViewChild(FundClassesComponent)
        fundClassesComponent: FundClassesComponent;

        @Input()
        public set ManagerStrategyId(value: number) {
            this._ManagerStrategyId = value;
        }
        FundClasses: any;
        LegalFundClasses: any;
        originalFundClasses: any;
        constructor(private termsService: TermsService) { }

        ngOnInit() {
            this.init();
        }

        init() {
            this.getTermsDetails();
        }

        public getTermsDetails() {
            if (this.ManagerStrategyId != null) {
                this.termsService.getTermsDetails(this.ManagerStrategyId).subscribe((data: any) => {
                    this.TermDetails = data;
                    this.OriginalList = JSON.parse(JSON.stringify(data));
                    this.FundClasses = this.TermDetails.FundClassViewModel;
                    this.LegalFundClasses = this.TermDetails.LegalFundClassViewModel;
                    this.Funds = this.TermDetails.LegalFundClassViewModel.Funds;
                    this.FundClassType = this.TermDetails.LegalFundClassViewModel.FundClassType;
                    this.FirmFunds = this.TermDetails.LegalFundClassViewModel.FirmFunds;

                    this.TermDetails.FundClassViewModel.FundDetailsViewModel.forEach(funDetail=> {
                        funDetail.FundClassDetailsViewModel = funDetail.FundClassDetailsViewModel
                            .reduce((prev, next) => prev = prev.concat(next), [])
                            .filter(obj => obj.InvestedAmount !== null);
                    });

                });
            }
        }
    }

Parent component html

<mgr-fund-classes (termDetailsEvent)="getFundInvestedDetails($event)" [FundClasses]="FundClasses" ></mgr-fund-classes>

<mgr-legal-fund-classes  (termDetailsEvent)="getTermsDetails()" [Funds] = "Funds" [FundClassType] = "FundClassType" [LegalFundClasses]="LegalFundClasses" [FirmFunds] ="FirmFunds" ></mgr-legal-fund-classes>

Child component

    import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from '@angular/core';
    import { TermsService } from '../../services/terms.service';
    import { NotifyService } from '../../utilities/notify.service';
    import { number } from '@amcharts/amcharts4/core';
    import { IReview } from '../terms.interface';
    import { AddLegalFundClassComponent } from './addLegalFundClass.component';
    import { AddSideLetterComponent } from './addSideLetter.component';
    import { CloneLegalFundClassComponent } from './cloneLegalFundClass.component';

    @Component({
        selector: 'mgr-legal-fund-classes',
        templateUrl: './legalFundClasses.component.html'
    })

    export class LegalFundClassesComponent implements OnInit {

        private _legalFundClasses: any;
        LegalFundClass: any;

        @Output() termDetailsEvent = new EventEmitter<string>();

        public get LegalFundClasses(): any {
            return this._legalFundClasses;
        }
        @Input()
        public set LegalFundClasses(value: any) {
            this._legalFundClasses = value;
        }

        public defaultItem: { Name: string, Id: number } = { Name: "Select item...", Id: null };

        constructor(private termsService: TermsService, private notify: NotifyService) { }

        ngOnInit() {
            this.init();
        }

        public value: any = [{ Id: null, Name: "" }];

        Update(id) {
            this.LegalFundClass = this.LegalFundClasses.LegalFundClassDetailsViewModel
                  .find(obj => obj.Id === id);

            this.termsService.updateLegalFundClasses(this.LegalFundClass).then((result) => {
                if (result) {
                    this.notify.success('Legal Fund Class Details Successfully Updated');
                    this.EditMode[id] = !this.EditMode[id];
                    this.termDetailsEvent.next('getTermsDetails');
                }
            }).catch(err => {
                this.notify.error('An Error Has Occured While Updating Legal Fund Class Details');
            });
        }

        Delete(id) {

            this.termsService.deleteLegalFundClasses(id).then((result) => {
                if (result) {
                    this.notify.success('Legal Fund Class Successfully Deleted');
                    this.EditMode = !this.EditMode[id];
                    this.termDetailsEvent.next('getTermsDetails');
                }
            }).catch(err => {
                this.notify.error('An Error Has Occured While Deleting Fund Class Details');
            });
        }

Child component html

<shared-modal [modalSize]="1" class="survey-edit" [open]="cloneLegalFundClassWindowOpened">

<button aria-label="Dismiss" class="close" style="margin-top: -10px"
                    type="button" (click)="dismissCloneModal()">X</button>

        <app-clone-legalclass  (termDetailsEvent)="getTermsDetails()" [FirmFunds]="FirmFunds"></app-clone-legalclass>

</shared-modal>

Grand child component

    export class CloneLegalFundClassComponent implements OnInit {

        private Error: string;
        public ManagerDetails: any;
        public EditorConfig: string;
        public CloneLegalFundClass: ICloneLegalFundClass;

        @Input() FirmFunds: any;
        @Output() termDetailsEvent = new EventEmitter<string>();

        constructor(private termsService: TermsService, private notify: NotifyService) {
        }

        ngOnInit() {

            this.CloneLegalFundClass = { Description: '', Id: null, FundId: null };
        }

        cloneLegalFundClass() {
            this.CloneLegalFundClass.FundId = this.FirmFunds.find(x => x.Id === this.CloneLegalFundClass.Id).FundId;
            this.termsService.cloneLegalFundClasses(this.CloneLegalFundClass).then((result) => {
                if (result) {
                    this.notify.success('Legal Fund Class Cloned Successfully');
                    this.termDetailsEvent.next('getTermsDetails');
                }
            }).catch(err => {
                this.notify.error('An Error Has Occured While cloning Legal Fund Class');
            });
        }

        closeLegalFundClass() {

        }
    }

Body:
I created a simple Stackblitz showing how to do it. You just continue emitting further out:
https://stackblitz.com/edit/angular-ad4kf3

Grandchild ts:

    import { Component, Output, EventEmitter, OnInit } from '@angular/core';
import { timer } from 'rxjs';

@Component({
  selector: 'app-grandchild',
  templateUrl: './grandchild.component.html',
  styleUrls: ['./grandchild.component.css']
})
export class GrandchildComponent implements OnInit {
  @Output() emitToChild: EventEmitter<void> = new EventEmitter();
  constructor() { }

  ngOnInit() {
    // emitting to child every two seconds, check console
    this.emit();
  }

  emit() {
    this.emitToChild.emit();
    timer(2000).subscribe(() => this.emit());
  }
}

Grandchild HTML:

<p>I'm grandchild.</p>

Child TS:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Output() emitToParent: EventEmitter<void> = new EventEmitter();
  constructor() { }

  ngOnInit() {
  }

}

Child HTML:

<p>I'm child.</p>
<app-grandchild (emitToChild)="emitToParent.emit()"></app-grandchild>

Parent TS:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  doSomething() {
    console.log('hello');
  }
}

Parent HTML:

<p>I'm Parent</p>

<app-child (emitToParent)="doSomething()"></app-child>


问:
apache ab in for loop
I'd like to run apache ab test more times with different parameters that will be stored in an array.
eg.:

```<code>$array {10,50,100,500,1000}
for $i in $array
ab -A name:pass -n $i -c $i http://www.google.com/.... > file_$i.txt
</code>```

While it's important that, to begin the i-th test, the previous test has to be finished.

答:
off the top of my head (untested)</p>

```<code>array=(10 50 100 500 1000)
for i in ${array[@]}; do
  ab -A name:pass -n $i -c $i http://www.google.com/.... > file_$i.txt
done
</code>```

Title: apache ab in for loop

Body:
I'd like to run apache ab test more times with different parameters that will be stored in an array.
eg.:

$array {10,50,100,500,1000}
for $i in $array
ab -A name:pass -n $i -c $i http://www.google.com/.... > file_$i.txt

While it's important that, to begin the i-th test, the previous test has to be finished.

Body:
off the top of my head (untested)

array=(10 50 100 500 1000)
for i in ${array[@]}; do
  ab -A name:pass -n $i -c $i http://www.google.com/.... > file_$i.txt
done


问:
Installing node-sass fails on Ubuntu 18.04
I have a simple next.js project, which I created following their tutorial. It builds and runs well on my Windows development machine.

I want to deploy it on Ubuntu 18.04.02 LTS but when I clone the git project and run npm install it fails to install node-sass with the following error message:

```<code>> node-sass@4.12.0 install /var/www/example.com/beta/node_modules/node-sass
> node scripts/install.js

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module '/var/www/example.com/beta/node_modules/node-sass/scripts/install.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.12.0 install: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.12.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: ...
</code>```

Here is a gist of the log file. See the last few lines for the error (I have included the whole file in case there is other information that is useful).

My NodeJS version is 10.15.3 and my NPM version is 6.4.1. I am not sure how to run next.js project on Ubuntu.

答:
Apparently, I needed to install it with --unsafe-perms flag:

```<code>npm install --unsafe-perms
</code>```

No explanation onto why it needs this and the unsafe word is not recommended by many.

In addition, the folder permissions needed to be in such a way that the script can create folders. I had to create a folder as me, clone the repo there, run the npm install --unsafe-perms, and then set the permissions as of a production web server.

For reference see here.

Body:
I have a simple next.js project, which I created following their tutorial. It builds and runs well on my Windows development machine.

I want to deploy it on Ubuntu 18.04.02 LTS but when I clone the git project and run npm install it fails to install node-sass with the following error message:

> node-sass@4.12.0 install /var/www/example.com/beta/node_modules/node-sass
> node scripts/install.js

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module '/var/www/example.com/beta/node_modules/node-sass/scripts/install.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.12.0 install: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.12.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: ...

Here is a gist of the log file. See the last few lines for the error (I have included the whole file in case there is other information that is useful).

My NodeJS version is 10.15.3 and my NPM version is 6.4.1. I am not sure how to run next.js project on Ubuntu.

Body:
Apparently, I needed to install it with --unsafe-perms flag:

npm install --unsafe-perms

No explanation onto why it needs this and the unsafe word is not recommended by many.

In addition, the folder permissions needed to be in such a way that the script can create folders. I had to create a folder as me, clone the repo there, run the npm install --unsafe-perms, and then set the permissions as of a production web server.

For reference see here.


问:
How can I remove a project from the sidebar?
New to Qt Creator. I just want to clean up the sidebar so it only shows the current project. How can I remove (not delete) my other projects?</p>

答: You can right-click on the project folder and select "close project".</p>


问:
keep a variable type when I get value from input onchange with React-hooks

const { useState } = React;

const App = () => {
  const [num, setNum] = useState(0);

  return (
    <input type="number" value={num} onChange={(e)=>setNum(parseInt(e.target.value))} />
  )
}

ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" /></code>```

I want to keep num's type as Number, not String.

but, onChange=(e=>setNum(e.target.value)) makes num's type String

I tried to change like this onChange={e=>setNum(parseInt(e.target.value))}.

but, when I inputted white-space, It occurs error.

Warning: Received NaN for the value attribute. If this is expected, cast the value to a string.

What is the best way to keep num's type?

答:
The issue stems from the fact that parseInt can break.

In case you cannot successfully parseInt your "string" input value, you will get an error. You can add a fallback to current value or reset to 0, or avoid calling setNum in case your parseInt fails.

```<code>import React, { useState } from 'react';

const App: React.FC = () => {
  const [num, setNum] = useState(0);

  return (
    <input
      type="number"
      onChange={e => setNum(parseInt(e.target.value) || num)}
    />
  );
};

export default App;
</code>```

Body:
const { useState } = React;

const App = () => {
  const [num, setNum] = useState(0);

  return (
    <input type="number" value={num} onChange={(e)=>setNum(parseInt(e.target.value))} />
  )
}

ReactDOM.render(<App />, document.getElementById('root'));

I want to keep num's type as Number, not String.

but, onChange=(e=>setNum(e.target.value)) makes num's type String

I tried to change like this onChange={e=>setNum(parseInt(e.target.value))}.

but, when I inputted white-space, It occurs error.

Warning: Received NaN for the value attribute. If this is expected, cast the value to a string.

What is the best way to keep num's type?

Body:
The issue stems from the fact that parseInt can break.

In case you cannot successfully parseInt your "string" input value, you will get an error. You can add a fallback to current value or reset to 0, or avoid calling setNum in case your parseInt fails.

import React, { useState } from 'react';

const App: React.FC = () => {
  const [num, setNum] = useState(0);

  return (
    <input
      type="number"
      onChange={e => setNum(parseInt(e.target.value) || num)}
    />
  );
};

export default App;


问:
How can connect jupyter notebook in desired environment in Anaconda in server computer by using Putty?
I'm trying to connect to server computer from my desktop computer via Putty to use capacity and source of powerful server remotely via Tunneling and applying localhost address and port. The problem is I have successfully installed Anaconda in server and created environment([CR7]) and installed Keras and tensorflow and already tested them via python but when I call jupyter notebook and import tensorflow in my environment [CR7], I face ModuleNotFoundError: No module named 'tensorflow' which is ridiculous as following picture:

Why it's the case and how can I fix that?

Should I install TF nad Keras in root environment in Anaconda?

Any help would be greatly appreciated.

Update I've just installed TF & Keras in root in server and it works but still I can't access my already built environment via Jupyter notebook and run TF & Keras!!! I don;t want to work in root environments due to some consequences!

BTW Python version is 3.7.1

答: In the screenshot you use Python 3 env. Go to Kernel/Change kernel > select CR7 environment.</p>


问:
Ip Address is not returning on rquesting cdpCacheAddress in snmp, instead showing c0:a8:0a:xX
i did a snmpwalk code in java , to retrieve data associated with cdp cache. except cdpCacheAddress, every thing is showing as expected. cdpCacheAddress is expected as IP but shows as c0:a8:0a:xX . the oid i requested is begins with .1.3.6.1.4.1.9.9.23.1.2.1.1.4. how can i find the ip address of the neighbor with this data. is there any other way to find the neighbor's IP address with cdp .
please help.

答:
That is an IP address.

It's four octets, each shown in hex, delimited by colons. It could also be rendered as "192.168.10.xX".

The syntax is defined to be a CiscoNetworkAddress (whose definition includes the DISPLAY-HINT that results in the default rendering you see), so you should interpret it as such.

You can transform & display it however you like!

How to do that depends entirely on your language/environment.


问:
Is it possible to customize material's datepicker body?
The idea is to edit the datepicker body in order to add a button. I know it is possible to edit the header, but I'd like to add a button (that upon being pressed sets the calendar date to today's date) below the actual dates.

答:
I did not find a way to edit the body of the calendar. However, I ended up adding the button from the CalendarHeaderComponent. It is not an ideal situation but it gets the job done and since I already had the header customized, it wasn't much extra effort.

The html (add the following to your custom calendar header):

```<code><button (click)="goToToday()" class="today-button" mat-button color="link">Today</button>
</code>```

The css:

```<code>.today-button {
  position: relative;
  top: 280px;
  left: 80px;
}
</code>```

Extra css in the actual datepicker itself:

```<code>.mat-datepicker-content {
  padding-bottom: 5px;
}
</code>```

Body:
I did not find a way to edit the body of the calendar. However, I ended up adding the button from the CalendarHeaderComponent. It is not an ideal situation but it gets the job done and since I already had the header customized, it wasn't much extra effort.

The html (add the following to your custom calendar header):

<button (click)="goToToday()" class="today-button" mat-button color="link">Today</button>

The css:

.today-button {
  position: relative;
  top: 280px;
  left: 80px;
}

Extra css in the actual datepicker itself:

.mat-datepicker-content {
  padding-bottom: 5px;
}


问:
Where do I put html bold tags in this php code sample?
I need to have the word "Located:" in bold but can't figure out where to put the tags so they don't either print or break the code.

Read other threads here, put the bold tags around Located: but they just print. Tried moving the tags but it breaks the code.

```<code>/* translators: used between list items, there is a space after the comma
*/
$tags_list = get_the_tag_list( '', esc_html__( ', ', 'vogue' ) );
if ( $tags_list ) {
    printf( '<br /><br /><span class="tags-links">' . esc_html__( '<b>Located:</b> %1$s', 'vogue' ) . '</span>', $tags_list ); // WPCS: XSS OK
}
</code>```

答:
```<code>if ($tags_list ) {
    printf(
        '<br /><br /><span class="tags-links"><b>Located:</b> ' . esc_html__('%1$s', 'vogue' ) . '</span>',
        $tags_list
    ); // WPCS: XSS OK
}
</code>```

Body:
I need to have the word "Located:" in bold but can't figure out where to put the tags so they don't either print or break the code.

Read other threads here, put the bold tags around Located: but they just print. Tried moving the tags but it breaks the code.

/* translators: used between list items, there is a space after the comma
*/
$tags_list = get_the_tag_list( '', esc_html__( ', ', 'vogue' ) );
if ( $tags_list ) {
    printf( '

' . esc_html__( 'Located: %1$s', 'vogue' ) . '', $tags_list ); // WPCS: XSS OK
}


问:
Database Diagram Support Objects cannot be Installed ... no valid owner
I tried to create a database diagramm with SQL Server 2008, but an error occurs:

Database diagram support objects
  cannot be installed because this
  database does not have a valid owner.
  To continue, first use the Files page
  of the Database Properties dialog box
  or the ALTER AUTHORIZATION statement
  to set the database owner to a valid
  login, then add the database diagram
  support objects.

Then I tried the following:

```<code>EXEC sp_dbcmptlevel 'Ariha', '90';
GO
ALTER AUTHORIZATION ON DATABASE::Ariha TO [WIN-NDKPHUPPNFL\Administrator]
GO
USE Ariha
GO
EXECUTE AS USER = N'dbo' REVERT
GO
</code>```

Next erorr pops up:

Msg 15404, Level 16, State 11, Line 1
  Could not obtain information about
  Windows NT group/user
  'WIN-NDKPHUPPNFL\Administrator', error
  code 0x534.

The Problem is the name of the PC has changed into "DevPC" I also changed this in the update script, but still the same error 15404.

What can I do to fix this annoying error?

答:
Only need to execute it in query editor
ALTER AUTHORIZATION ON DATABASE::YourDatabase TO [domain\account];</p>

Body:
I tried to create a database diagramm with SQL Server 2008, but an error occurs:

Database diagram support objects
  cannot be installed because this
  database does not have a valid owner.
  To continue, first use the Files page
  of the Database Properties dialog box
  or the ALTER AUTHORIZATION statement
  to set the database owner to a valid
  login, then add the database diagram
  support objects.

Then I tried the following:

EXEC sp_dbcmptlevel 'Ariha', '90';
GO
ALTER AUTHORIZATION ON DATABASE::Ariha TO [WIN-NDKPHUPPNFL\Administrator]
GO
USE Ariha
GO
EXECUTE AS USER = N'dbo' REVERT
GO

Next erorr pops up:

Msg 15404, Level 16, State 11, Line 1
  Could not obtain information about
  Windows NT group/user
  'WIN-NDKPHUPPNFL\Administrator', error
  code 0x534.

The Problem is the name of the PC has changed into "DevPC" I also changed this in the update script, but still the same error 15404.

What can I do to fix this annoying error?


问:
mysql query show only 1 result
i want to output the result based on todays date.
the problem is, the output only show 1 result?</p>

```<code>database report table:
id  |  r_amount | id_therapist | date | time | t_tanning | t_deep

// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")

// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
     // (1) echoing all result from database
     echo $r['r_amount'].'<br>';
     // (2) echoing only 1 result????
     echo $r['totalProTan'].'<br>';
endwhile;
</code>```

答:
If the date field is of type datetime, you'll have to do something like

SELECT ... WHERE DATE(date)=CURDATE()

Notice that I'm using curdate() in the query. There's no need to generate the date value in PHP. MySQL is perfectly capable of doing that itself.

Title: mysql query show only 1 result

Body:
i want to output the result based on todays date.
the problem is, the output only show 1 result?

database report table:
id  |  r_amount | id_therapist | date | time | t_tanning | t_deep

// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")

// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
     // (1) echoing all result from database
     echo $r['r_amount'].'
';
     // (2) echoing only 1 result????
     echo $r['totalProTan'].'
';
endwhile;


问:
how can i format a datediff to show hh:mm
I am not sure how to format a datediff to show as hours and minutes. It show as eg. 7.78

```<code>=DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)/60
</code>```

I would like this to show as eg. hh:mm

答:
One possible option is to combine your datediff with a dateadd then convert it to a varchar of the desired format:

```<code>=convert( varchar
        , dateadd( "n"
                 , datediff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)
                 , 0)
        , 8)
</code>```

The above function will output a value in HH:MM:SS format. The day portion of durations longer than 24 hours, however, will lose the number of days.  To remove the seconds from the output value you can of course use the substring function to get the first 5 characters.

Body:
I am not sure how to format a datediff to show as hours and minutes. It show as eg. 7.78

=DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)/60

I would like this to show as eg. hh:mm

Body:
One possible option is to combine your datediff with a dateadd then convert it to a varchar of the desired format:

=convert( varchar
        , dateadd( "n"
                 , datediff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)
                 , 0)
        , 8)

The above function will output a value in HH:MM:SS format. The day portion of durations longer than 24 hours, however, will lose the number of days.  To remove the seconds from the output value you can of course use the substring function to get the first 5 characters.


问:
wifiManager.getScanResult() returns null value
I'm searching to do a scan of available wifi networks but the method getScanResults() returns null list.

I included all permissions needed :

```<code>android.permission.ACCESS_COARSE_LOCATION
android.permission.CHANGE_WIFI_STATE
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_WIFI_STATE
</code>```

The main activity class is :

```<code>public class Home extends Activity {`

    Context context;
    WifiManager wifiManager = null;
    WiFiReceiver wifiReceiver = null;

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

        context = this;
        wifiManager = (WifiManager)
        context.getSystemService(Context.WIFI_SERVICE);
        wifiReceiver = new WiFiReceiver(wifiManager);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(wifiReceiver, intentFilter);

        wifiManager.startScan();
        List<ScanResult> results = wifiReceiver.results;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(wifiReceiver);
    }
}
</code>```

The Broadcast Receiver is :

```<code>public class WiFiReceiver extends BroadcastReceiver {`

    public List<ScanResult> results;
    private WifiManager wifiManager;

    public WiFiReceiver(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
        if (success) {
            results = wifiManager.getScanResults();
            Log.e("wiFi Manager", "Done");

        } else {
            Log.e("wiFi Manager", "Scan failure");
        }
    }
}
</code>```

答:
The issue is that your are assuming that startScan() will produce a result immediately but it actually only does what is says, starting the scan. Your are accessing then results variable before onReceive in your WiFiReceiver has been triggered which is why it will always be null (your logging should confirm that).

What you need to to is use a callback to get the results when they're ready like the code here does. Notice how the onReceive method calls scanSuccess() and the results are only accessed in scanSuccess() and not immediately after calling startScan().
Also notice how they are checking if starting the scan was actually successful by checking the Boolean startScan() returns

Body:
I'm searching to do a scan of available wifi networks but the method getScanResults() returns null list.

I included all permissions needed :

android.permission.ACCESS_COARSE_LOCATION
android.permission.CHANGE_WIFI_STATE
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_WIFI_STATE

The main activity class is :

public class Home extends Activity {`

    Context context;
    WifiManager wifiManager = null;
    WiFiReceiver wifiReceiver = null;

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

        context = this;
        wifiManager = (WifiManager)
        context.getSystemService(Context.WIFI_SERVICE);
        wifiReceiver = new WiFiReceiver(wifiManager);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(wifiReceiver, intentFilter);

        wifiManager.startScan();
        List<ScanResult> results = wifiReceiver.results;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(wifiReceiver);
    }
}

The Broadcast Receiver is :

public class WiFiReceiver extends BroadcastReceiver {`

    public List<ScanResult> results;
    private WifiManager wifiManager;

    public WiFiReceiver(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
        if (success) {
            results = wifiManager.getScanResults();
            Log.e("wiFi Manager", "Done");

        } else {
            Log.e("wiFi Manager", "Scan failure");
        }
    }
}


问:
How to filter rows only when all conditions are met in R
I'm trying to remove rows from a table of survey response data. I want to remove rows only where all my specified conditions are met. For example, if three columns contain NA then I want to remove the whole row. But if only one or two of those same columns contains NA that is acceptable.

I haven't managed to use filter to achieve this. If I use the code below then it removes the row if any NA's exist as opposed to all the

 df <- filter(df,
              is.na(Q1) == FALSE &
              is.na(Q2) == FALSE &
              is.na(Q3) == FALSE)
```

<p>So if we have a df like below I'd only want to remove row #2:</p>

<pre class="lang-r prettyprint-override"><code>rowid    Q1      Q2     Q3
1        1       3      2
2        NA      NA     NA
3        NA      1      0
4        1       NA     2
5        1       1      NA
</code>```

答:
An option would be to use filter_at and specify any_vars with the condition check for any non-NA elements in a row

```<code>library(dplyr)
df %>%
     filter_at(vars(starts_with("Q")), any_vars(!is.na(.)))
#  rowid Q1 Q2 Q3
#1     1  1  3  2
#2     3 NA  1  0
#3     4  1 NA  2
#4     5  1  1 NA
</code>```

As the OP requested specifically (in the comments) for all_vars

```<code>df %>%
  filter_at(vars(starts_with('Q')), all_vars(is.na(.))) %>%
  anti_join(df, ., by = 'rowid')
</code>```

Or with rowSums from base R

```<code>df[ rowSums(!is.na(df[-1])) != 0,]
</code>```

data

```<code>df <- structure(list(rowid = 1:5, Q1 = c(1L, NA, NA, 1L, 1L), Q2 = c(3L,
NA, 1L, NA, 1L), Q3 = c(2L, NA, 0L, 2L, NA)), class = "data.frame",
row.names = c(NA,
-5L))
</code>```

Body:
I'm trying to remove rows from a table of survey response data. I want to remove rows only where all my specified conditions are met. For example, if three columns contain NA then I want to remove the whole row. But if only one or two of those same columns contains NA that is acceptable.

I haven't managed to use filter to achieve this. If I use the code below then it removes the row if any NA's exist as opposed to all the

 df <- filter(df,
              is.na(Q1) == FALSE &
              is.na(Q2) == FALSE &
              is.na(Q3) == FALSE)

So if we have a df like below I'd only want to remove row #2:

rowid    Q1      Q2     Q3
1        1       3      2
2        NA      NA     NA
3        NA      1      0
4        1       NA     2
5        1       1      NA

Body:
An option would be to use filter_at and specify any_vars with the condition check for any non-NA elements in a row

library(dplyr)
df %>%
     filter_at(vars(starts_with("Q")), any_vars(!is.na(.)))
#  rowid Q1 Q2 Q3
#1     1  1  3  2
#2     3 NA  1  0
#3     4  1 NA  2
#4     5  1  1 NA

As the OP requested specifically (in the comments) for all_vars

df %>%
  filter_at(vars(starts_with('Q')), all_vars(is.na(.))) %>%
  anti_join(df, ., by = 'rowid')

Or with rowSums from base R

df[ rowSums(!is.na(df[-1])) != 0,]

data

df <- structure(list(rowid = 1:5, Q1 = c(1L, NA, NA, 1L, 1L), Q2 = c(3L,
NA, 1L, NA, 1L), Q3 = c(2L, NA, 0L, 2L, NA)), class = "data.frame",
row.names = c(NA,
-5L))


问:
intent.getStringExtra must not be null kotlin
I want to passing data with intent extra from fragment to activity, Usually I use anko common intent from activity to activity

```<code>startactivity<secondActivity>("values" to "123")
</code>```

but in my case, I want to passing data from fragment to activity like this

```<code>activity?.startactivity<secondActivity>("values" to "123")
</code>```

when I want to get String Extra in my activity,

```<code>val values: String = ""
val intent = intent
values = intent.getStringExtra("values")
</code>```

I get Error

```<code>intent.getstringextra must not be null
</code>```

Do you have a solution for my case? because I do that to get extra from activity to activity no problem

答:
Because you declare that values can't be null, if you want values can be null, you should declare it like this

```<code>var values:String? = null
</code>```

Or if you want to get a default value when values are null, you can do something like this

```<code>values = if (intent.getStringExtra("values")==null) "" else intent.getStringExtra("values")
</code>```

Body:
I want to passing data with intent extra from fragment to activity, Usually I use anko common intent from activity to activity

startactivity<secondActivity>("values" to "123")

but in my case, I want to passing data from fragment to activity like this

activity?.startactivity<secondActivity>("values" to "123")

when I want to get String Extra in my activity,

val values: String = ""
val intent = intent
values = intent.getStringExtra("values")

I get Error

intent.getstringextra must not be null

Do you have a solution for my case? because I do that to get extra from activity to activity no problem

Body:
Because you declare that values can't be null, if you want values can be null, you should declare it like this

var values:String? = null

Or if you want to get a default value when values are null, you can do something like this

values = if (intent.getStringExtra("values")==null) "" else intent.getStringExtra("values")


问:
In MySql, using Python, how to INSERT INTO tables and columns, depending on variables?
I am building an interface in Python to get access to different queries in some big data tables (queries such as insert, search, predefined ones, etc.). The problem is that there are a few different tables which contain each a number of columns... So I would want to modularize my code and MySql queries, so that depending on which table we want to insert data to and to which columns these data concern, it will know what MySql command it will have to execute.

I saw that we can use variables for values, for example :

```<code>sql = "INSERT INTO table_name (col1, col2) VALUES (%s, %s)"
values = ("val1", "val2")
mycursor.execute(sql, values)
</code>```

Is it possible to have something similar with table_nameand columns ? To have something for example like :

```<code>sql = "INSERT INTO (%s) (%s, %s) VALUES (%s, %s)"
table = "table_name"
columns = ("col1", "col2")
values = ("val1", "val2")
mycursor.execute(sql, table, columns, values)
</code>```

With that, it would be far easier for me to initialize table, columnsand values when needed (for example when the user clicks a button, enters values in some text fields, etc.) than having a lot of such sql queries, one for each table and each possible subset of columns.

I am not sure that it is all clear with my pretty random english, if you need some more information feel free to ask !

Thank you in advance for your time,

Sanimys

答:
For the few of you that will see this while looking for an answer, in fact this is pretty easy ! You can do pretty much exaclty like I proposed, for example :

```<code>sql = "INSERT INTO %s %s VALUES %s"
table = "table_name"
columns = "(col1, col2)"
values = "(val1, val2)"
mycursor.execute(sql % (table, columns, values))
</code>```

Where every element is a string.

By doing that, you can have some nice dynamic computations, such as :

```<code>sql = "INSERT INTO %s %s VALUES %s"
table = "table_name"
values = "(val1, val2)"

// Some code

def compute_columns(list_of_columns_to_insert):
    col = "("
    for c in list_of_columns_to_insert:
        col = col + "'" + c + "', "

    col = col[:-2] + ")"
    return col

// Some code generating a list of columns that we want to insert to

columns = compute_columns(list_of_columns_to_insert)
mycursor.execute(sql % (columns, values))
</code>```

Here you go, hope that it could help someone that struggles like me !

Body:
I am building an interface in Python to get access to different queries in some big data tables (queries such as insert, search, predefined ones, etc.). The problem is that there are a few different tables which contain each a number of columns... So I would want to modularize my code and MySql queries, so that depending on which table we want to insert data to and to which columns these data concern, it will know what MySql command it will have to execute.

I saw that we can use variables for values, for example :

sql = "INSERT INTO table_name (col1, col2) VALUES (%s, %s)"
values = ("val1", "val2")
mycursor.execute(sql, values)

Is it possible to have something similar with table_nameand columns ? To have something for example like :

sql = "INSERT INTO (%s) (%s, %s) VALUES (%s, %s)"
table = "table_name"
columns = ("col1", "col2")
values = ("val1", "val2")
mycursor.execute(sql, table, columns, values)

With that, it would be far easier for me to initialize table, columnsand values when needed (for example when the user clicks a button, enters values in some text fields, etc.) than having a lot of such sql queries, one for each table and each possible subset of columns.

I am not sure that it is all clear with my pretty random english, if you need some more information feel free to ask !

Thank you in advance for your time,

Sanimys

Body:
For the few of you that will see this while looking for an answer, in fact this is pretty easy ! You can do pretty much exaclty like I proposed, for example :

sql = "INSERT INTO %s %s VALUES %s"
table = "table_name"
columns = "(col1, col2)"
values = "(val1, val2)"
mycursor.execute(sql % (table, columns, values))

Where every element is a string.

By doing that, you can have some nice dynamic computations, such as :

sql = "INSERT INTO %s %s VALUES %s"
table = "table_name"
values = "(val1, val2)"

// Some code

def compute_columns(list_of_columns_to_insert):
    col = "("
    for c in list_of_columns_to_insert:
        col = col + "'" + c + "', "

    col = col[:-2] + ")"
    return col

// Some code generating a list of columns that we want to insert to

columns = compute_columns(list_of_columns_to_insert)
mycursor.execute(sql % (columns, values))

Here you go, hope that it could help someone that struggles like me !