问:
Add rows in a gridview c#
Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code: </p>

```<code>DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();
</code>```

答:
Its because you are creating new table each time and binding it with the grid

Do code as below may resolve your issue ...

here i am taking existing datasource and binding it again by adding two more row...

```<code>DataTable dt = gridView.DataSource as DataTable;

if (dt != null)
{

  DataRow dr = dt.NewRow();
  dr["Question"] = txtQuestion.Text;
  dr["Answer"] = txtAnswer.Text;
  dt.Rows.Add(dr);
  dt.AcceptChanges();

  gvQnA.DataSource = dt;
  gvQnA.DataBind();
}
</code>```

Title: Add rows in a gridview c#

Body:
Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code:

DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();

Body:
Its because you are creating new table each time and binding it with the grid

Do code as below may resolve your issue ...

here i am taking existing datasource and binding it again by adding two more row...

DataTable dt = gridView.DataSource as DataTable;

if (dt != null)
{

  DataRow dr = dt.NewRow();
  dr["Question"] = txtQuestion.Text;
  dr["Answer"] = txtAnswer.Text;
  dt.Rows.Add(dr);
  dt.AcceptChanges();

  gvQnA.DataSource = dt;
  gvQnA.DataBind();
}


来源: stackexchange

问:
Access one item from a dict and store it into a variable
I am trying to get all the "uuid"'s from an API, and the issue is that it is stored into a dict (I think). Her is how it looks on the API:

```<code>{"guild": {
        "_id": "5eba1c5f8ea8c960a61f38ed",
        "name": "Creators Club",
        "name_lower": "creators club",
        "coins": 0,
        "coinsEver": 0,
        "created": 1589255263630,
        "members":
            [{  "uuid": "db03ceff87ad4909bababc0e2622aaf8",
                "rank": "Guild Master",
                "joined": 1589255263630,
                "expHistory": {
                "2020-06-01": 280,
                "2020-05-31": 4701,
                "2020-05-30": 0,
                "2020-05-29": 518,
                "2020-05-28": 1055,
                "2020-05-27": 136665,
                "2020-05-26": 34806}}]
        }
    }
</code>```

Now I am interested in the "uuid" part there, and take note: There is multiple players, it can be 1 to 100 players, and I am going to need every UUID.

Now I have done this in my python to get the UUID's displayed on the website:
try:

```<code>f = requests.get(
            "https://api.hypixel.net/guild?key=[secret]&id=" + guild).json()
        guildName = f["guild"]["name"]
        guildMembers = f["guild"]["members"]
        members = client.getPlayer(uuid=guildMembers) #this converts UUID to player names
        #I need to store all uuid's in variables and put them at "guildMembers"
</code>```

And that gives me all the "UUID codes", and I will be using client.getPlayer(uuid=---) to convert the UUID into the Player Names. I have to loop through each "UUID" into that code client.getPlayer(uuid=---) . But first of I need to save the UUID'S in variables, I have been doing members.uuid to access the UUID on my HTML file, but I don't know how you do the .uuid part in python

If you need anything else, just comment :)

答:
If i understood situation right, You just need to loop through all received uuids and get  players' data. Something like this:</p>

```<code>f = requests.get("https://api.hypixel.net/guild?key=[secret]&id=" + guild).json()
guildName = f["guild"]["name"]
guildMembers = f["guild"]["members"]
guildMembersData = dict()  # Here we will save member's data from getPlayer method

for guildMember in guildMembers:
    uuid = guildMember["uuid"]
    memberData = client.getPlayer(uuid=uuid)
    guildMembersData[uuid] = client.getPlayer(uuid=guildMember["uuid"])

print(guildMembersData)  # Here will be players' Data.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get all the "uuid"'s from an API, and the issue is that it is stored into a dict (I think). Her is how it looks on the API:

{"guild": {
        "_id": "5eba1c5f8ea8c960a61f38ed",
        "name": "Creators Club",
        "name_lower": "creators club",
        "coins": 0,
        "coinsEver": 0,
        "created": 1589255263630,
        "members":
            [{  "uuid": "db03ceff87ad4909bababc0e2622aaf8",
                "rank": "Guild Master",
                "joined": 1589255263630,
                "expHistory": {
                "2020-06-01": 280,
                "2020-05-31": 4701,
                "2020-05-30": 0,
                "2020-05-29": 518,
                "2020-05-28": 1055,
                "2020-05-27": 136665,
                "2020-05-26": 34806}}]
        }
    }

Now I am interested in the "uuid" part there, and take note: There is multiple players, it can be 1 to 100 players, and I am going to need every UUID.

Now I have done this in my python to get the UUID's displayed on the website:
try:

f = requests.get(
            "https://api.hypixel.net/guild?key=[secret]&id=" + guild).json()
        guildName = f["guild"]["name"]
        guildMembers = f["guild"]["members"]
        members = client.getPlayer(uuid=guildMembers) #this converts UUID to player names
        #I need to store all uuid's in variables and put them at "guildMembers"

And that gives me all the "UUID codes", and I will be using client.getPlayer(uuid=---) to convert the UUID into the Player Names. I have to loop through each "UUID" into that code client.getPlayer(uuid=---) . But first of I need to save the UUID'S in variables, I have been doing members.uuid to access the UUID on my HTML file, but I don't know how you do the .uuid part in python

If you need anything else, just comment :)

Body:
If i understood situation right, You just need to loop through all received uuids and get  players' data. Something like this:

f = requests.get("https://api.hypixel.net/guild?key=[secret]&id=" + guild).json()
guildName = f["guild"]["name"]
guildMembers = f["guild"]["members"]
guildMembersData = dict()  # Here we will save member's data from getPlayer method

for guildMember in guildMembers:
    uuid = guildMember["uuid"]
    memberData = client.getPlayer(uuid=uuid)
    guildMembersData[uuid] = client.getPlayer(uuid=guildMember["uuid"])

print(guildMembersData)  # Here will be players' Data.


问:
There is an error of exception in thread "main" and i need to have a message entered
I don't see the issue or how to input the message. The full error that I keep getting is below. I can't see any problems with the code and I can't find a way to a message into the code.</p>

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of ran
ge: 30
    at java.base/java.lang.StringLatin1.charAt (String.java:47)
    at java.base/java.lang.String.charAt (String.java:693
    at Main.main (Main.java:15)
</code>```

```<code>import java.util.Scanner;

public class Main
{
    public static void main( String[] args )
    {
        Scanner kb = new Scanner(System.in);

        System.out.println("What is your message? ");
        String message ="" + "\n";

        System.out.println("\nYour message is " +  " characters long.");
        System.out.println("The first character is at position 0 and is '" +  "'.");
        int lastpos = 30;
        System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
        System.out.println("\nHere are all the characters, one at a time:\n");

        for ( int i=0; i<message.length(); i++ )
        {
            System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
        }

        int a_count = 0;

        for ( int i=0; i<message.length(); i++ )
        {
            char letter = message.charAt(i);
            if ( letter == 'a' || letter == 'A' );
            {
                a_count++;
            }
        }

        System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");

    }
}
</code>```

答:
You never actually capture a message from the scanner - something like this:

```<code>message = kb.nextLine();
</code>```

In addition, if you're trying to get the last index/position of the message, you'd want to do something like this:

```<code>int lastpos = message.length();
OR
int lastpos = message.length()-1;
</code>```

The difference between the two being that the first gives you the size of the string, and the second gives you the last index of the string (for example, "abcdefg", lastpos 1 would be 7, and lastpos 2 would be 6).

Finally, keep in mind, you can do something like

```<code>message.charAt(0);
</code>```

to get the first index character of the string.

Body:
I don't see the issue or how to input the message. The full error that I keep getting is below. I can't see any problems with the code and I can't find a way to a message into the code.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of ran
ge: 30
    at java.base/java.lang.StringLatin1.charAt (String.java:47)
    at java.base/java.lang.String.charAt (String.java:693
    at Main.main (Main.java:15)

import java.util.Scanner;

public class Main
{
    public static void main( String[] args )
    {
        Scanner kb = new Scanner(System.in);

        System.out.println("What is your message? ");
        String message ="" + "\n";

        System.out.println("\nYour message is " +  " characters long.");
        System.out.println("The first character is at position 0 and is '" +  "'.");
        int lastpos = 30;
        System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
        System.out.println("\nHere are all the characters, one at a time:\n");

        for ( int i=0; i<message.length(); i++ )
        {
            System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
        }

        int a_count = 0;

        for ( int i=0; i<message.length(); i++ )
        {
            char letter = message.charAt(i);
            if ( letter == 'a' || letter == 'A' );
            {
                a_count++;
            }
        }

        System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");

    }
}

Body:
You never actually capture a message from the scanner - something like this:

message = kb.nextLine();

In addition, if you're trying to get the last index/position of the message, you'd want to do something like this:

int lastpos = message.length();
OR
int lastpos = message.length()-1;

The difference between the two being that the first gives you the size of the string, and the second gives you the last index of the string (for example, "abcdefg", lastpos 1 would be 7, and lastpos 2 would be 6).

Finally, keep in mind, you can do something like

message.charAt(0);

to get the first index character of the string.


问:
Issues when trying to space XMLHttpRequest() API calls every 5 seconds with setTimeout()
I am working on the initial data pull for a project. It will be cached and further requests will be much less.  I am attempting to space out my API requests every 5 seconds to avoid overloading the server and hitting the rate limit per their rules.  It does not seem that my setTimeout() function is actually working as desired. I logged time stamps to see and all iterations seem to be happening at the exact same time.  I think this somehow due to the asynchronous nature of javascript, but I'm not sure how to remedy it.  Any help would be greatly appreciated.

Code Excerpt:

```<code>var leagues;
function getLeagues(){

    var reqURL = "url";
    var data = new XMLHttpRequest();
    data.open("GET", reqURL);
    data.responseType = "text";
    data.send();

    // parse data on load
    data.onload = function() {
        // League IDs
        leagues = JSON.parse(data.response)

        for (i = 0; i < 5; i++) {
            delay(i); // iterate every 5 secs
        }
    };
}

function delay(i) {
  setTimeout(() => {
    var d = new Date();
    console.log(d.getSeconds())
  }, 5000);
}
</code>```

答:
You call delay to tell JS to do something in 5 seconds.

Then you immediately call delay to tell JS to do something in 5 seconds again.

So 5 seconds later the first delay timeout triggers, then immediately after that the second one triggers.

If you want to space them apart then you need to either:

Call delay the second time in the function that setTimeout calls so the second timer doesn't start under the first one is finished

Multiply your times so the first one is 5 seconds but the second is 10 seconds and so on

Refactor the code to use setInterval instead

Body:
I am working on the initial data pull for a project. It will be cached and further requests will be much less.  I am attempting to space out my API requests every 5 seconds to avoid overloading the server and hitting the rate limit per their rules.  It does not seem that my setTimeout() function is actually working as desired. I logged time stamps to see and all iterations seem to be happening at the exact same time.  I think this somehow due to the asynchronous nature of javascript, but I'm not sure how to remedy it.  Any help would be greatly appreciated.

Code Excerpt:

var leagues;
function getLeagues(){

    var reqURL = "url";
    var data = new XMLHttpRequest();
    data.open("GET", reqURL);
    data.responseType = "text";
    data.send();

    // parse data on load
    data.onload = function() {
        // League IDs
        leagues = JSON.parse(data.response)

        for (i = 0; i < 5; i++) {
            delay(i); // iterate every 5 secs
        }
    };
}

function delay(i) {
  setTimeout(() => {
    var d = new Date();
    console.log(d.getSeconds())
  }, 5000);
}


问:
How to use scanf() correctly when reading input into an array using pointers?
For some reason, reading input using scanf() won't work this way:

```<code>int main() {
    int arr1_size = 0;

    // Reading array size
    scanf("%d", &arr1_size);

    int* arr1 = (int*) malloc(sizeof(int) * arr1_size);

    // Reading and printing array values
    for(int i = 0; i < arr1_size; i++) {
        scanf("%d", arr1);
        arr1++;
    }
    for(int i = 0; i < arr1_size; i++) {
        printf("%d", arr1[i]);
    }

    return 0;
}
</code>```

What could be the issue?

答:
Here is a slightly improved version of your program:

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {
    int arr1_size = 0;

    printf("Hello,\nPlease enter the size of the first array:");
    scanf("%d", &arr1_size);

    int *arr1 = (int*) malloc(sizeof(int) * arr1_size);

    printf("\nPlease enter arr1 of size %d:\n", arr1_size);
    for(int i = 0; i < arr1_size; i++) {
        scanf("%d", arr1 + i);
    }
    printf("\nArray contents:\n");
    for(int i = 0; i < arr1_size; i++) {
        printf("%d \n", arr1[i]);
    }

    return 0;
}
</code>```

Execution:

```<code>./scan
Hello,
Please enter the size of the first array:3

Please enter arr1 of size 3:
1
2
3

Array contents:
1
2
3
</code>```

Body:
For some reason, reading input using scanf() won't work this way:

int main() {
    int arr1_size = 0;

    // Reading array size
    scanf("%d", &arr1_size);

    int* arr1 = (int*) malloc(sizeof(int) * arr1_size);

    // Reading and printing array values
    for(int i = 0; i < arr1_size; i++) {
        scanf("%d", arr1);
        arr1++;
    }
    for(int i = 0; i < arr1_size; i++) {
        printf("%d", arr1[i]);
    }

    return 0;
}

What could be the issue?

Body:
Here is a slightly improved version of your program:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int arr1_size = 0;

    printf("Hello,\nPlease enter the size of the first array:");
    scanf("%d", &arr1_size);

    int *arr1 = (int*) malloc(sizeof(int) * arr1_size);

    printf("\nPlease enter arr1 of size %d:\n", arr1_size);
    for(int i = 0; i < arr1_size; i++) {
        scanf("%d", arr1 + i);
    }
    printf("\nArray contents:\n");
    for(int i = 0; i < arr1_size; i++) {
        printf("%d \n", arr1[i]);
    }

    return 0;
}

Execution:

./scan
Hello,
Please enter the size of the first array:3

Please enter arr1 of size 3:
1
2
3

Array contents:
1
2
3


问:
Problem with downloading data - vertices of square
I would like to write a program in which you give two vertices of the square and the program finds the other two.

for example:

input:

2 3 4 5

output

(3,6) (0,5)

But I have a problem when it reads data from the program everything works fine

```<code>int main(void)
{

    rationalNumber *z,e,f,g,h;

    point *x, a, b, c, d;

    e.l = 2; e.m = 1; f.l=3; f.m=1; g.l = 4; g.m = 1; h.l=5; h.m=1;

    a.x = e;
    a.y = f;
    b.x = g;
    b.y = h;
    output_point(D_2(z,a, b));

return 0;
}
</code>```

but when  reads data from a user, I gets this message

"Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)"

In this place:

if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;

All code:

```<code>#include<stdio.h>
#include<stdlib.h>

typedef struct rn{
    int n;   /**numerator**/
    unsigned d;    /**denomirator**/
} rationalNumber;

int gcd(int,int);

void output(rationalNumber);
void input(rationalNumber *);
void Minus(rationalNumber*, rationalNumber, rationalNumber);
void Sum( rationalNumber *, rationalNumber, rationalNumber);
void Multiplication(rationalNumber *, rationalNumber, rationalNumber);
void Reciprocal( rationalNumber *);

typedef struct dot{
    rationalNumber x;
    rationalNumber y;
} point;

void load_point(point *);
void output_point(point);
point C_1(rationalNumber *, point, point);
point D_1(rationalNumber *, point, point);
point C_2(rationalNumber *, point, point);
point D_2(rationalNumber *, point, point);

int main(void)
{

    rationalNumber *z;
    point *a,b,c;

    load_point(a);
    b = *a;
    load_point(a);
    c = *a;

    output_point(D_2(z,b, c));

return 0;
}

int gcd(int a, int b)
{
  if(b!=0)
    return gcd(b,a%b);

       return a;
}

void output(rationalNumber a)
{
    if(a.d == 1)  printf("%d",a.n);
    else printf("%d/%u",a.n, a.d);
}

void input(rationalNumber *a)
{
    int nwd;
    if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;
    else
    {
        nwd = abs(gcd(a->n, a->d));
        a->n = a->n/nwd;
        a->d = a->d/nwd;
    }

}

void Minus(rationalNumber *a, rationalNumber b, rationalNumber c)
{
   int nwd;
      if(b.d == c.d)
      {
          a->n = b.n - c.n;
          a->d = b.d;
          nwd = abs(gcd(a->n, a->d));
          a->n = a->n/nwd;
          a->d = a->d/nwd;

      }else
      {
          a->n = b.n*c.d - c.n*b.d;
          a->d = b.d * c.d;
          nwd = abs(gcd(a->n, a->d));
          a->n = a->n/nwd;
          a->d = a->d/nwd;

      }
}

rationalNumber minus( rationalNumber a)
{
    return a;
}

void Sum( rationalNumber *a, rationalNumber b, rationalNumber c)
{
    int nwd;
    if(b.d == c.d)
    {
        a->n = b.n + c.n;
        a->d = b.d;
    }else
    {
        a->n = b.n*c.d + c.n*b.d;
        a->d = b.d * c.d;
        nwd = abs(gcd(a->n, a->d));
        a->n = a->n/nwd;
        a->d = a->d/nwd;

    }

}

void Multiplication( rationalNumber *a, rationalNumber b, rationalNumber c)
{
    int nwd;

    a->n = b.n*c.n;
    a->d = b.d *c.d;

    nwd = abs(gcd(a->n, a->d));
    a->n = a->n/nwd;
    a->d = a->d/nwd;

}

void Reciprocal( rationalNumber *a)
{
    int buffor;

    if(a->n<0)
    {
        buffor = abs(a->n);
        a->n = -(a->d);
        a->d = buffor;
    }
    else if(a->n>0)
    {
        buffor = a->n;
        a->n = a->d;
        a->d = buffor;
    }

}

void load_point(point *a)
{
    input(&a->x);
    input(&a->y);

}

void output_point(point a)
{
    printf("(");
    output(a.x);
    printf(",");
    output(a.y);
    printf(")\n");
}

point C_1(rationalNumber *c_1, point a, point b)
{

    point c;

    Sum(c_1,b.x,a.y);

    Minus(c_1,*c_1, b.y);
    c.x = *c_1;

    Sum(c_1,b.y,b.x);

    Minus(c_1,*c_1, a.x);
    c.y = *c_1;

    return c;
}

point D_1(rationalNumber *d_1, point a, point b)
{
    point d;

    Sum(d_1,a.x,a.y);

    Minus(d_1,*d_1, b.y);
    d.x = *d_1;

    Sum(d_1,a.y,b.x);

    Minus(d_1,*d_1, a.x);
    d.y = *d_1;

    return d;
}

point C_2(rationalNumber *c_1,point a, point b)
{
    point c;

    Minus(c_1,b.x,a.y);

    Sum(c_1,*c_1, b.y);
    c.x = *c_1;

    Minus(c_1,b.y,b.x);

    Sum(c_1,*c_1, a.x);
    c.y = *c_1;

    return c;
}

point D_2(rationalNumber *d_1,point a, point b)
{
    point d;

    Minus(d_1,a.x,a.y);

    Sum(d_1,*d_1, b.y);
    d.x = *d_1;

    Minus(d_1,a.y,b.x);

    Sum(d_1,*d_1, a.x);
    d.y = *d_1;

    return d;
}

</code>```

I' don't know how I can fix it

答:
If you have one side of the square as (a, b), you can immediately have one of it's two normals as (b, -a) (or (-b, a), your problem is ambiguous) and the last point you can get by adding both vectors, so (a + b, b - a) (or (a - b, b + a), depending on which vector you selected first)

The only thing for this to be transportable to any pair of points in the plane is to subtract one of the vectors first to move the figure origin.... once the problem is solved, you can move the whole thing back to the point you had it.

So, assuming you are given the two vectors P = (a, b) and Q = (c, d), the first task is to subtract P = (a, b) from Q = (c, d) to make it to start from the origin, then you get P'(a - a, b - b) = P'(0, 0); Q' = (c - a, d - b), now you generate your normal vector (you exchange coordinates and change the sign to one of them), let's say, R' = (-d + b, c - a), and add both vectors to get S' = (c - a - d + b, c - a + d - b), the opposite diagonally.  These are the two points you get.  Let's move the whole thing back to the original point:

```<code>P' = (0, 0) ==> P = (0 + a, 0 + b) = (a, b) = P
Q' = (c - a, d - b) ==> (c - a + a, d - b + b) = (c, d) = Q
R' = (b - d, c - a) ==> (b - d + a, c - a + b) = R
S' = (c - a - d + b, c - a + d - b) ==> (c - a - d + b + a, c - a + d - b + b) = (c + b - d, c - a + d) = S
</code>```

So, if you get two points P = (a, b) and Q = (c, d) you have to return R = (a + b - c, -a + b + c) and S = (b + c - d, -a + c + d).

```<code>double a, b, c, d;

scan("%g%g%g%g", &a, &b, &c, &d);
printf("Given (%g, %g) and (%g, %g),\n"
       "we got the other two vertices "
       "as (%g, %g) and (%g, %g)\n",
       a, b, c, d,
       a + b - c, b - a + c,
       b + c - d, c - a + d);
</code>```

Body:
I would like to write a program in which you give two vertices of the square and the program finds the other two.

for example:

input:

2 3 4 5

output

(3,6) (0,5)

But I have a problem when it reads data from the program everything works fine

int main(void)
{

    rationalNumber *z,e,f,g,h;

    point *x, a, b, c, d;

    e.l = 2; e.m = 1; f.l=3; f.m=1; g.l = 4; g.m = 1; h.l=5; h.m=1;

    a.x = e;
    a.y = f;
    b.x = g;
    b.y = h;
    output_point(D_2(z,a, b));

return 0;
}

but when  reads data from a user, I gets this message

"Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)"

In this place:

if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;

All code:

#include<stdio.h>
#include<stdlib.h>

typedef struct rn{
    int n;   /**numerator**/
    unsigned d;    /**denomirator**/
} rationalNumber;

int gcd(int,int);

void output(rationalNumber);
void input(rationalNumber *);
void Minus(rationalNumber*, rationalNumber, rationalNumber);
void Sum( rationalNumber *, rationalNumber, rationalNumber);
void Multiplication(rationalNumber *, rationalNumber, rationalNumber);
void Reciprocal( rationalNumber *);

typedef struct dot{
    rationalNumber x;
    rationalNumber y;
} point;

void load_point(point *);
void output_point(point);
point C_1(rationalNumber *, point, point);
point D_1(rationalNumber *, point, point);
point C_2(rationalNumber *, point, point);
point D_2(rationalNumber *, point, point);

int main(void)
{

    rationalNumber *z;
    point *a,b,c;

    load_point(a);
    b = *a;
    load_point(a);
    c = *a;

    output_point(D_2(z,b, c));

return 0;
}

int gcd(int a, int b)
{
  if(b!=0)
    return gcd(b,a%b);

       return a;
}

void output(rationalNumber a)
{
    if(a.d == 1)  printf("%d",a.n);
    else printf("%d/%u",a.n, a.d);
}

void input(rationalNumber *a)
{
    int nwd;
    if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;
    else
    {
        nwd = abs(gcd(a->n, a->d));
        a->n = a->n/nwd;
        a->d = a->d/nwd;
    }

}

void Minus(rationalNumber *a, rationalNumber b, rationalNumber c)
{
   int nwd;
      if(b.d == c.d)
      {
          a->n = b.n - c.n;
          a->d = b.d;
          nwd = abs(gcd(a->n, a->d));
          a->n = a->n/nwd;
          a->d = a->d/nwd;

      }else
      {
          a->n = b.n*c.d - c.n*b.d;
          a->d = b.d * c.d;
          nwd = abs(gcd(a->n, a->d));
          a->n = a->n/nwd;
          a->d = a->d/nwd;

      }
}

rationalNumber minus( rationalNumber a)
{
    return a;
}

void Sum( rationalNumber *a, rationalNumber b, rationalNumber c)
{
    int nwd;
    if(b.d == c.d)
    {
        a->n = b.n + c.n;
        a->d = b.d;
    }else
    {
        a->n = b.n*c.d + c.n*b.d;
        a->d = b.d * c.d;
        nwd = abs(gcd(a->n, a->d));
        a->n = a->n/nwd;
        a->d = a->d/nwd;

    }

}

void Multiplication( rationalNumber *a, rationalNumber b, rationalNumber c)
{
    int nwd;

    a->n = b.n*c.n;
    a->d = b.d *c.d;

    nwd = abs(gcd(a->n, a->d));
    a->n = a->n/nwd;
    a->d = a->d/nwd;

}

void Reciprocal( rationalNumber *a)
{
    int buffor;

    if(a->n<0)
    {
        buffor = abs(a->n);
        a->n = -(a->d);
        a->d = buffor;
    }
    else if(a->n>0)
    {
        buffor = a->n;
        a->n = a->d;
        a->d = buffor;
    }

}

void load_point(point *a)
{
    input(&a->x);
    input(&a->y);

}

void output_point(point a)
{
    printf("(");
    output(a.x);
    printf(",");
    output(a.y);
    printf(")\n");
}

point C_1(rationalNumber *c_1, point a, point b)
{

    point c;

    Sum(c_1,b.x,a.y);

    Minus(c_1,*c_1, b.y);
    c.x = *c_1;

    Sum(c_1,b.y,b.x);

    Minus(c_1,*c_1, a.x);
    c.y = *c_1;

    return c;
}

point D_1(rationalNumber *d_1, point a, point b)
{
    point d;

    Sum(d_1,a.x,a.y);

    Minus(d_1,*d_1, b.y);
    d.x = *d_1;

    Sum(d_1,a.y,b.x);

    Minus(d_1,*d_1, a.x);
    d.y = *d_1;

    return d;
}

point C_2(rationalNumber *c_1,point a, point b)
{
    point c;

    Minus(c_1,b.x,a.y);

    Sum(c_1,*c_1, b.y);
    c.x = *c_1;

    Minus(c_1,b.y,b.x);

    Sum(c_1,*c_1, a.x);
    c.y = *c_1;

    return c;
}

point D_2(rationalNumber *d_1,point a, point b)
{
    point d;

    Minus(d_1,a.x,a.y);

    Sum(d_1,*d_1, b.y);
    d.x = *d_1;

    Minus(d_1,a.y,b.x);

    Sum(d_1,*d_1, a.x);
    d.y = *d_1;

    return d;
}

I' don't know how I can fix it

Body:
If you have one side of the square as (a, b), you can immediately have one of it's two normals as (b, -a) (or (-b, a), your problem is ambiguous) and the last point you can get by adding both vectors, so (a + b, b - a) (or (a - b, b + a), depending on which vector you selected first)

The only thing for this to be transportable to any pair of points in the plane is to subtract one of the vectors first to move the figure origin.... once the problem is solved, you can move the whole thing back to the point you had it.

So, assuming you are given the two vectors P = (a, b) and Q = (c, d), the first task is to subtract P = (a, b) from Q = (c, d) to make it to start from the origin, then you get P'(a - a, b - b) = P'(0, 0); Q' = (c - a, d - b), now you generate your normal vector (you exchange coordinates and change the sign to one of them), let's say, R' = (-d + b, c - a), and add both vectors to get S' = (c - a - d + b, c - a + d - b), the opposite diagonally.  These are the two points you get.  Let's move the whole thing back to the original point:

P' = (0, 0) ==> P = (0 + a, 0 + b) = (a, b) = P
Q' = (c - a, d - b) ==> (c - a + a, d - b + b) = (c, d) = Q
R' = (b - d, c - a) ==> (b - d + a, c - a + b) = R
S' = (c - a - d + b, c - a + d - b) ==> (c - a - d + b + a, c - a + d - b + b) = (c + b - d, c - a + d) = S

So, if you get two points P = (a, b) and Q = (c, d) you have to return R = (a + b - c, -a + b + c) and S = (b + c - d, -a + c + d).

double a, b, c, d;

scan("%g%g%g%g", &a, &b, &c, &d);
printf("Given (%g, %g) and (%g, %g),\n"
       "we got the other two vertices "
       "as (%g, %g) and (%g, %g)\n",
       a, b, c, d,
       a + b - c, b - a + c,
       b + c - d, c - a + d);


问:
Filter data for last 24 hours using c#?
Here i am calculating the server restart count.

i need the server restart count for last 24 hours.

```<code>string logType = "System";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int count=0;
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.Source.ToUpper() == "USER32")
{
count = count + 1;
}
}
ev.Close();
</code>```

and i have tried like

```<code>DateTime dt = DateTime.Now;
TimeSpan ts = dt.Subtract(CurrentEntry.TimeGenerated);
int hours = (ts.Days * 24) + ts.Hours;
</code>```

Any suggestion?

答:
Use CurrentEntry.TimeGenerated to check when it has happened.

put one more condition at if (CurrentEntry.Source.ToUpper() == "USER32") to check if TimeGenerated is in last 24 hours

ContentLicense: CC BY-SA 3.0

Title: Filter data for last 24 hours using c#?

Body:
Here i am calculating the server restart count.

i need the server restart count for last 24 hours.

string logType = "System";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int count=0;
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.Source.ToUpper() == "USER32")
{
count = count + 1;
}
}
ev.Close();

and i have tried like

DateTime dt = DateTime.Now;
TimeSpan ts = dt.Subtract(CurrentEntry.TimeGenerated);
int hours = (ts.Days * 24) + ts.Hours;

Any suggestion?


问:
LoDash for node.js
How do I custom build lodash for node.js projects? I don't want any opera, IE, firefox based code in the custom build as i will always be using v8. Is it possible? kindly help.</p>

答:
Simply install npm install --save lodash

Use wherever needed with with

```<code>const _ = require('lodash');

const array = [1];
const other = _.concat(array, 2, [3], [[4]]);
</code>```

Title: LoDash for node.js

Body:
Simply install npm install --save lodash

Use wherever needed with with

const _ = require('lodash');

const array = [1];
const other = _.concat(array, 2, [3], [[4]]);


问:
Express Throws TypeError: Cannot read property 'app' of undefined
I have a nodejs server running the common framework express. I have noticed recently that when I make requests from my server, I get this error at seemingly random times, for example, if I were to make a request twice, the error would usually only happen the first request, and not the second. I'm having trouble pinpointing what is causing this error, because I often write my code in one go, then test it later. Here is the error in full:

```<code>TypeError: Cannot read property 'app' of undefined
    at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
    at process._tickCallback (internal/process/next_tick.js:68:7) 'Unhandled Rejection at Promise' Promise {
  <rejected> TypeError: Cannot read property 'app' of undefined
      at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
      at process._tickCallback (internal/process/next_tick.js:68:7) }
</code>```

All that I can tell from this error is that it may involve some reference to "app", however I am not sure what it could be specifically, as I haven't changed anything pertaining to "app" in express recently. Here is my express configuration on my server file:

```<code>    const express = require('express'),
        user = require('./routers/User.js'),
        helmet = require('helmet'),
        app = express();
    app.use(helmet());
    app.use(cors());
    app.use(bodyParser.urlencoded({
        extended: false
    }));
    app.use(bodyParser.json());
    app.set('trust proxy', true);

    //map router files to respective urls
    //these are stored in a directory and set above, these contain all of the handlers for each of my routes
    app.use('/user', user);

    //set port and listen on it
    app.listen(5000, () => console.log("Server running on port 5000"));
</code>```

If anything else is needed of me, please ask. I've tried to include every reference pertaining to the word "app" in my code, but that may not be enough.

EDIT: I thank you all for trying to help, but the code I provided was not intended to work, it was simply an example of what I import, this is an error with express, and I'm just trying to find out what kind of behavior would cause it. Sorry for the confusion.

答:
for your code to work you have to add </p>

```<code>const express = require('express'),
        user = require('./routers/User.js'),
        helmet = require('helmet')
 ----> const app = express();

or helmet = require('helmet'), <-----
 app = express()
</code>```

Body:
I have a nodejs server running the common framework express. I have noticed recently that when I make requests from my server, I get this error at seemingly random times, for example, if I were to make a request twice, the error would usually only happen the first request, and not the second. I'm having trouble pinpointing what is causing this error, because I often write my code in one go, then test it later. Here is the error in full:

TypeError: Cannot read property 'app' of undefined
    at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
    at process._tickCallback (internal/process/next_tick.js:68:7) 'Unhandled Rejection at Promise' Promise {
  <rejected> TypeError: Cannot read property 'app' of undefined
      at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
      at process._tickCallback (internal/process/next_tick.js:68:7) }

All that I can tell from this error is that it may involve some reference to "app", however I am not sure what it could be specifically, as I haven't changed anything pertaining to "app" in express recently. Here is my express configuration on my server file:

    const express = require('express'),
        user = require('./routers/User.js'),
        helmet = require('helmet'),
        app = express();
    app.use(helmet());
    app.use(cors());
    app.use(bodyParser.urlencoded({
        extended: false
    }));
    app.use(bodyParser.json());
    app.set('trust proxy', true);

    //map router files to respective urls
    //these are stored in a directory and set above, these contain all of the handlers for each of my routes
    app.use('/user', user);

    //set port and listen on it
    app.listen(5000, () => console.log("Server running on port 5000"));

If anything else is needed of me, please ask. I've tried to include every reference pertaining to the word "app" in my code, but that may not be enough.

EDIT: I thank you all for trying to help, but the code I provided was not intended to work, it was simply an example of what I import, this is an error with express, and I'm just trying to find out what kind of behavior would cause it. Sorry for the confusion.

Body:
for your code to work you have to add

const express = require('express'),
        user = require('./routers/User.js'),
        helmet = require('helmet')
 ----> const app = express();

or helmet = require('helmet'), <-----
 app = express()


问:
How to fix TypeError: cy.document(...).toMatchSnapshot is not a function?
I am trying to do snapshot testing for my e2e test on my page by using Cypress and cypress-plugin-snapshots.

But I got this error TypeError: cy.document(...).toMatchSnapshot is not a function.

Here are my configurations:

plugins/index.js

```<code>const { initPlugin } = require('cypress-plugin-snapshots/plugin');

module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
  initPlugin(on, config);
  return config;
}
</code>```

support/index.js

```<code>import 'cypress-plugin-snapshots/src/commands';
</code>```

cypress.json

```<code>{
    "ignoreTestFiles": [
        "**/__snapshots__/*",
        "**/__image_snapshots__/*"
    ]
}
</code>```

home.spec.js

```<code>context('Querying', () => {
    beforeEach(() => {
        cy.server();
        cy.fixture('user.json').as('userJSON');
        cy.route('GET', 'users?id=*', '@userJSON').as('getUser');
        cy.visit('http://localhost:4200/1');
    })

    it.only('LANDING - Snapshot test', () => {
        cy.wait(['@getUser']);
        cy.document().toMatchSnapshot()
    });
})

</code>```

答:
Just had the same issue. Your code should be:

```<code>expect(cy.document()).toMatchSnapshot()
</code>```

Note the expect

Body:
I am trying to do snapshot testing for my e2e test on my page by using Cypress and cypress-plugin-snapshots.

But I got this error TypeError: cy.document(...).toMatchSnapshot is not a function.

Here are my configurations:

plugins/index.js

const { initPlugin } = require('cypress-plugin-snapshots/plugin');

module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
  initPlugin(on, config);
  return config;
}

support/index.js

import 'cypress-plugin-snapshots/src/commands';

cypress.json

{
    "ignoreTestFiles": [
        "**/__snapshots__/*",
        "**/__image_snapshots__/*"
    ]
}

home.spec.js

context('Querying', () => {
    beforeEach(() => {
        cy.server();
        cy.fixture('user.json').as('userJSON');
        cy.route('GET', 'users?id=*', '@userJSON').as('getUser');
        cy.visit('http://localhost:4200/1');
    })

    it.only('LANDING - Snapshot test', () => {
        cy.wait(['@getUser']);
        cy.document().toMatchSnapshot()
    });
})

Body:
Just had the same issue. Your code should be:

expect(cy.document()).toMatchSnapshot()

Note the expect


问:
TypeError: fs.readFileSync is not a function Off Basic Install
I'm stumped - pretty simple app (I'm new to Node):

App.js

```<code>import * as RNFS from 'react-native-fs';
var config_full;
// readFile(filepath: string, encoding?: string)
RNFS.readFile('./config.toml', 'utf-8').then(res => {
    config_full = toml.parse(res);
})
.catch(err => {
    console.log(err.message, err.code);
});

</code>```

Package.json

```<code>{
  "name": "samples-dashboard",
  "version": "0.1.0",
  "private": false,
  "type": "module",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "fs": "0.0.1-security",
    "gremlin": "^3.4.6",
    "match-sorter": "^4.1.0",
    "namor": "^2.0.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-native-fs": "^2.16.6",
    "react-scripts": "3.4.1",
    "react-table": "^7.1.0",
    "styled-components": "^5.1.1",
    "toml": "^3.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "gh-pages": "^2.2.0"
  }
}

</code>```

And I get an error:

```<code>Failed to compile
./node_modules/react-native-fs/FS.common.js
SyntaxError: /node_modules/react-native-fs/FS.common.js: Unexpected token, expected ";" (32:5)

  30 | var normalizeFilePath = (path) => (path.startsWith('file://') ? path.slice(7) : path);
  31 |
> 32 | type MkdirOptions = {
     |      ^
  33 |   NSURLIsExcludedFromBackupKey?: boolean; // iOS only
  34 |   NSFileProtectionKey?: string; // IOS only
  35 | };
</code>```

I totally don't care what I use to load from the .toml file - just need to load a few things off disk. What should I be using?

To be clear, I don't need to deliver this file to the browser, I want the server to load the file and provide the value of the .toml to the variable.

I've checked the following and none seem to work:

TypeError: fs.readFileSync is not a function

https://dev-yakuza.github.io/en/react-native/react-native-fs/#read-file

Uncaught TypeError: fs.readFileSync is not a function

Error: fs.readFileSync is not a function

fs.readFileSync is not a function Meteor, React

My best hope was the core docs - https://github.com/alexbeletsky/toml-js - but none of the file system packages seemed to work there either.

答:
I now realize I'm thinking about this wrong. The entire app - including config - is being downloaded to the client and run, which would include the sensitive material in the .toml.

I'll need to figure out another way to auth with the database. This question doesn't make sense.

Body:
I'm stumped - pretty simple app (I'm new to Node):

App.js

import * as RNFS from 'react-native-fs';
var config_full;
// readFile(filepath: string, encoding?: string)
RNFS.readFile('./config.toml', 'utf-8').then(res => {
    config_full = toml.parse(res);
})
.catch(err => {
    console.log(err.message, err.code);
});

Package.json

{
  "name": "samples-dashboard",
  "version": "0.1.0",
  "private": false,
  "type": "module",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "fs": "0.0.1-security",
    "gremlin": "^3.4.6",
    "match-sorter": "^4.1.0",
    "namor": "^2.0.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-native-fs": "^2.16.6",
    "react-scripts": "3.4.1",
    "react-table": "^7.1.0",
    "styled-components": "^5.1.1",
    "toml": "^3.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "gh-pages": "^2.2.0"
  }
}

And I get an error:

Failed to compile
./node_modules/react-native-fs/FS.common.js
SyntaxError: /node_modules/react-native-fs/FS.common.js: Unexpected token, expected ";" (32:5)

  30 | var normalizeFilePath = (path) => (path.startsWith('file://') ? path.slice(7) : path);
  31 |
> 32 | type MkdirOptions = {
     |      ^
  33 |   NSURLIsExcludedFromBackupKey?: boolean; // iOS only
  34 |   NSFileProtectionKey?: string; // IOS only
  35 | };

I totally don't care what I use to load from the .toml file - just need to load a few things off disk. What should I be using?

To be clear, I don't need to deliver this file to the browser, I want the server to load the file and provide the value of the .toml to the variable.

I've checked the following and none seem to work:

TypeError: fs.readFileSync is not a function

https://dev-yakuza.github.io/en/react-native/react-native-fs/#read-file

Uncaught TypeError: fs.readFileSync is not a function

Error: fs.readFileSync is not a function

fs.readFileSync is not a function Meteor, React

My best hope was the core docs - https://github.com/alexbeletsky/toml-js - but none of the file system packages seemed to work there either.


问:
Failed to emit precompiled header for bridging header
I downloaded a project from GitHub, then pod the following files, some of which are written by OBJ-C and I used a bridge header.

```<code>pod ‘SnapKit’
pod ‘MJRefresh’
pod ‘Alamofire’
pod ‘Kingfisher’
pod ‘MBProgressHUD’
pod ‘pop’
pod ‘EVReflection’
pod ‘StreamingKit’
pod ‘iCarousel’
pod ‘ReflectionView’
</code>```

When I run the project with Xcode 9.0 beta 2, but unfortunately the error log as follows :

error: failed to emit precompiled header
  '/var/folders/kd/4gh0_kxx3jx4thjb_sssmmcw0000gn/T/EvoRadio-Bridging-Header-97bd5f.pch'
  for bridging header
  '/Users/ringo/Downloads/EvoRadio-master/EvoRadio/Resources/EvoRadio-Bridging-Header.h'

I have googled, but no such issue.The error means it needs a PCH file?
This is my .pch header configuration:

It can't solve it.

How to make it?

答:
In my case;

Under Target/Build Settings/

Product_Name section was different than $(TARGET_NAME)

When I changed it $(TARGET_NAME), it was resolved.

Body:
I downloaded a project from GitHub, then pod the following files, some of which are written by OBJ-C and I used a bridge header.

pod ‘SnapKit’
pod ‘MJRefresh’
pod ‘Alamofire’
pod ‘Kingfisher’
pod ‘MBProgressHUD’
pod ‘pop’
pod ‘EVReflection’
pod ‘StreamingKit’
pod ‘iCarousel’
pod ‘ReflectionView’

When I run the project with Xcode 9.0 beta 2, but unfortunately the error log as follows :

error: failed to emit precompiled header
  '/var/folders/kd/4gh0_kxx3jx4thjb_sssmmcw0000gn/T/EvoRadio-Bridging-Header-97bd5f.pch'
  for bridging header
  '/Users/ringo/Downloads/EvoRadio-master/EvoRadio/Resources/EvoRadio-Bridging-Header.h'

I have googled, but no such issue.The error means it needs a PCH file?
This is my .pch header configuration:

It can't solve it.

How to make it?


问:
assembly crap games. My code can't complete exit and stuck in a loop
Write a program that plays the game of Craps using the rules stated above so that it simulates a game without human input.   Instead of asking for a wager, the program should just calculate if the player would win or lose.  Create a function that simulates rolling the two dice and returns the sum.  Add a loop so that the program plays 10,000 games.  Add counters that count how many times the player wins, and how many times the player loses.  At the end of the 10,000 games, List total Wins and Losses for output.   Over the long run, who is going to win the most games of Craps, you or the house?

this is my code.
I think it stuck on an endless loop.
Please point out what I need to fix.

```<code>include Irvine32.inc

.data
point dword ?
winCount dword 0
loseCount dword 0
dice1 dword ?     ; 1 to 6
dice2 dword ?     ; 1 to 6
.code
 main PROC
    call clrscr
    mov ecx, 10
    call play

    mov eax, winCount
    call writedec
    call crlf
    mov eax, loseCount
    call writedec
    main endp

random1 PROC    ;generate first number
    mov eax, 5
    call randomrange
    inc eax
    mov dice1, eax
    ret
    random1 endp

random2 PROC    ;generate second number
    mov eax, 5
    call randomrange
    inc eax
    mov dice2, eax
    ret
    random2 endp

reroll PROC

    call random1
    call random2
    mov eax, dice1
    mov ebx, dice2
    add eax, ebx
    cmp eax,7
    je win
    cmp eax, point
    je lose
    jmp reroll
    ret
    reroll endp

win PROC
    mov eax, winCount
    inc eax
    mov winCount, eax
    jmp play
    ret
    win endp

lose PROC
    mov eax, loseCount
    inc eax
    mov loseCount, eax
    jmp play
    ret
    lose endp

play PROC

    playloop:
    call random1
    call random2
    mov eax, dice1
    mov ebx, dice2
    add eax, ebx
    mov point, eax
    cmp eax, 7
    je win
    cmp eax, 11
    je win

    cmp eax, 2
    je lose
    cmp eax, 3
    je lose
    cmp eax, 12
    je lose

    cmp eax, 4
    je reroll
    cmp eax, 5
    je reroll
    cmp eax, 6
    je reroll
    cmp eax, 8
    je reroll
    cmp eax, 9
    je reroll
    cmp eax, 10
    je reroll

    loop playloop

    ret
    play endp

    end main
</code>```

答:
I think it stuck on an endless loop.

The loop playloop instruction can never be reached!

When throwing 2 dice, the outcome is a number in the range [2,12].

Your code has cases for every possible value:

7 and 11 go to win

2, 3, and 12 go to lose

4, 5, 6, 8, 9, and 10 go to reroll

There's no way to fall through in the loopinstruction that would otherwise limit the playing time. There's your endless loop.

Please point out what I need to fix.

I don't know this game of Craps and so it's impossible to even start suggesting decisive corrections.

What I can tell you is that win, lose, and reroll ought to be labels within the play proc, and not procs by themselves.

IDEA

Your text says:

...the game of Craps using the rules stated above...

It's probably best to actually include these rules with your post.

Body:
Write a program that plays the game of Craps using the rules stated above so that it simulates a game without human input.   Instead of asking for a wager, the program should just calculate if the player would win or lose.  Create a function that simulates rolling the two dice and returns the sum.  Add a loop so that the program plays 10,000 games.  Add counters that count how many times the player wins, and how many times the player loses.  At the end of the 10,000 games, List total Wins and Losses for output.   Over the long run, who is going to win the most games of Craps, you or the house?

this is my code.
I think it stuck on an endless loop.
Please point out what I need to fix.

include Irvine32.inc

.data
point dword ?
winCount dword 0
loseCount dword 0
dice1 dword ?     ; 1 to 6
dice2 dword ?     ; 1 to 6
.code
 main PROC
    call clrscr
    mov ecx, 10
    call play

    mov eax, winCount
    call writedec
    call crlf
    mov eax, loseCount
    call writedec
    main endp

random1 PROC    ;generate first number
    mov eax, 5
    call randomrange
    inc eax
    mov dice1, eax
    ret
    random1 endp

random2 PROC    ;generate second number
    mov eax, 5
    call randomrange
    inc eax
    mov dice2, eax
    ret
    random2 endp

reroll PROC

    call random1
    call random2
    mov eax, dice1
    mov ebx, dice2
    add eax, ebx
    cmp eax,7
    je win
    cmp eax, point
    je lose
    jmp reroll
    ret
    reroll endp

win PROC
    mov eax, winCount
    inc eax
    mov winCount, eax
    jmp play
    ret
    win endp

lose PROC
    mov eax, loseCount
    inc eax
    mov loseCount, eax
    jmp play
    ret
    lose endp

play PROC

    playloop:
    call random1
    call random2
    mov eax, dice1
    mov ebx, dice2
    add eax, ebx
    mov point, eax
    cmp eax, 7
    je win
    cmp eax, 11
    je win

    cmp eax, 2
    je lose
    cmp eax, 3
    je lose
    cmp eax, 12
    je lose

    cmp eax, 4
    je reroll
    cmp eax, 5
    je reroll
    cmp eax, 6
    je reroll
    cmp eax, 8
    je reroll
    cmp eax, 9
    je reroll
    cmp eax, 10
    je reroll

    loop playloop

    ret
    play endp

    end main


问:
OAuth 2.0 Client ID and Secret Java implementation
I have been asked to make an OAuth 2.0 integration with an external company. All they need from me is to provide them with are client ID and client secret, and authorize their access if the details are correct.

Is there a simple library that does it, or maybe an implementation guide?

答: use https://auth0.com or Onelogin - https://developers.onelogin.com . both of them provide Oauth2.0 and enormous amount of documentation and samples. </p>


问:
How can I convert a vector of ints to be a vector of strings using STL algorithms?
For example, I would need {20,6,143} to become {"20","6","143"}.

答: std::transform combined with std::to_string should do the trick.</p>


问:
FCM Messaging Issue
I am trying to generate token from FCM by following this link. I am facing issue in messaging.service. I couldn't implement angularFireMessaging.messaging, its shrowing error in messaging keyword as

Property 'messaging' does not exist on type 'AngularFireMessaging'

Code

```<code>import { Injectable } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { BehaviorSubject } from 'rxjs'
@Injectable()
export class MessagingService {
  currentMessage = new BehaviorSubject(null);
  constructor(private angularFireMessaging: AngularFireMessaging) {
    this.angularFireMessaging.messaging.subscribe(  //issue here in messaging
      (_messaging) => {
        _messaging.onMessage = _messaging.onMessage.bind(_messaging);
        _messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
      }
    )
  }
  requestPermission() {
    this.angularFireMessaging.requestToken.subscribe(
      (token) => {
        console.log(token);
      },
      (err) => {
        console.error('Unable to get permission to notify.', err);
      }
    );
  }
  receiveMessage() {
    this.angularFireMessaging.messages.subscribe(
      (payload) => {
        console.log("new message received. ", payload);
        this.currentMessage.next(payload);
      })
  }
}
</code>```

Where I am going wrong please help me out

答:
To resolve this problem I run below command:</p>

```<code>1) decrease the version of @angular/fire from latest to @angular/fire: ^5.2.1
2) use the version of firebase: 7.6.0
</code>```

Title: FCM Messaging Issue

Body:
I am trying to generate token from FCM by following this link. I am facing issue in messaging.service. I couldn't implement angularFireMessaging.messaging, its shrowing error in messaging keyword as

Property 'messaging' does not exist on type 'AngularFireMessaging'

Code

import { Injectable } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { BehaviorSubject } from 'rxjs'
@Injectable()
export class MessagingService {
  currentMessage = new BehaviorSubject(null);
  constructor(private angularFireMessaging: AngularFireMessaging) {
    this.angularFireMessaging.messaging.subscribe(  //issue here in messaging
      (_messaging) => {
        _messaging.onMessage = _messaging.onMessage.bind(_messaging);
        _messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
      }
    )
  }
  requestPermission() {
    this.angularFireMessaging.requestToken.subscribe(
      (token) => {
        console.log(token);
      },
      (err) => {
        console.error('Unable to get permission to notify.', err);
      }
    );
  }
  receiveMessage() {
    this.angularFireMessaging.messages.subscribe(
      (payload) => {
        console.log("new message received. ", payload);
        this.currentMessage.next(payload);
      })
  }
}

Where I am going wrong please help me out

Body:
To resolve this problem I run below command:

1) decrease the version of @angular/fire from latest to @angular/fire: ^5.2.1
2) use the version of firebase: 7.6.0


问:
Calling getters on an object vs. storing it as a local variable (memory footprint, performance)
In the following piece of code we make a call listType.getDescription() twice:

```<code>for (ListType listType: this.listTypeManager.getSelectableListTypes())
{
    if (listType.getDescription() != null)
    {
        children.add(new SelectItem( listType.getId() , listType.getDescription()));
    }
}
</code>```

I would tend to refactor the code to use a single variable:

```<code>for (ListType listType: this.listTypeManager.getSelectableListTypes())
{
    String description = listType.getDescription();

    if (description != null)
    {
        children.add(new SelectItem(listType.getId() ,description));
    }
}
</code>```

My understanding is the JVM is somehow optimized for the original code and especially nesting calls like children.add(new SelectItem(listType.getId(), listType.getDescription()));.

Comparing the two options, which one is the preferred method and why? That is in terms of memory footprint, performance, readability/ease, and others that don't come to my mind right now.

When does the latter code snippet become more advantageous over the former, that is, is there any (approximate) number of listType.getDescription() calls when using a temp local variable becomes more desirable, as listType.getDescription() always requires some stack operations to store the this object?

答:
I agree on everything. About the readability I'd like to add something:
I see lots of programmers doing things like:

if (item.getFirst().getSecond().getThird().getForth() == 1 ||

item.getFirst().getSecond().getThird().getForth() == 2 ||

item.getFirst().getSecond().getThird().getForth() == 3)

Or even worse:

item.getFirst().getSecond().getThird().setForth(item2.getFirst().getSecond().getThird().getForth())

If you are calling the same chain of 10 getters several times, please, use an intermediate variable. It's just much easier to read and debug

Body:
In the following piece of code we make a call listType.getDescription() twice:

for (ListType listType: this.listTypeManager.getSelectableListTypes())
{
    if (listType.getDescription() != null)
    {
        children.add(new SelectItem( listType.getId() , listType.getDescription()));
    }
}

I would tend to refactor the code to use a single variable:

for (ListType listType: this.listTypeManager.getSelectableListTypes())
{
    String description = listType.getDescription();

    if (description != null)
    {
        children.add(new SelectItem(listType.getId() ,description));
    }
}

My understanding is the JVM is somehow optimized for the original code and especially nesting calls like children.add(new SelectItem(listType.getId(), listType.getDescription()));.

Comparing the two options, which one is the preferred method and why? That is in terms of memory footprint, performance, readability/ease, and others that don't come to my mind right now.

When does the latter code snippet become more advantageous over the former, that is, is there any (approximate) number of listType.getDescription() calls when using a temp local variable becomes more desirable, as listType.getDescription() always requires some stack operations to store the this object?


问:
Using iif clause in Ms Access for a column with "Yes/No" Data Type
I have a column called DayShift in a table which is of Yes/No data type (Boolean). The result Output I want is: if the value is true, display "Day" else display night.

I have tried the following:

```<code>SELECT iif(DayShift=Yes,"Day","Night") as Shift FROM table1;

SELECT iif(DayShift,"Day","Night") as Shift FROM table1;

SELECT iif(DayShift=True,"Day","Night") as Shift FROM table1;

SELECT iif(DayShift=1,"Day","Night") as Shift FROM table1;
</code>```

But none of the above work. It just gives me a list of blank check boxes in the output datasheet window. I am using Ms Access 2003. Any help appreciated.

Update:

After a bit of research that the yes/no data type in Ms Access 2003 cannot handle null values appropriately. Hence, the error. Check this link for details.

Update 2

Real Query with the joins. Didnt mention it since i though the information provided above would work.

```<code>SELECT tblovertime.contfirstname                        AS [First Name],
       tblovertime.contlastname                         AS [Last Name],
       tblovertime.employeenumber                       AS [Employee Number],
       tblsignup.thedate                                AS [Sign Up Date],
       Iif([tblOvertime.DayShift] =- 1, "Day", "Night") AS shift,
       (SELECT Mid(MIN(Iif(sector = 1, "," & sector, NULL)) & MIN(
                               Iif(sector = 2, "," & sector, NULL)) & MIN(
                               Iif(sector = 3, "," & sector, NULL)) & MIN(
                           Iif(sector = 4, "," & sector, NULL)), 2) AS concat
        FROM   tblempsectorlist
        WHERE  tblempsectorlist.empnum = tblsignup.employeenumber
        GROUP  BY empnum)                               AS sectors,
       tblovertime.timedatecontact                      AS [Date Contacted],
       tblovertimestatus.name                           AS status
FROM   (tblsignup
        INNER JOIN tblovertime
          ON ( tblsignup.thedate = tblovertime.otdate )
             AND ( tblsignup.employeenumber = tblovertime.employeenumber ))
       INNER JOIN tblovertimestatus
         ON Clng(tblovertime.statusid) = tblovertimestatus.statusid
WHERE  (( ( tblsignup.thedate ) ># 1 / 1 / 2011 # ))
ORDER  BY tblsignup.thedate;
</code>```

答:
The Access database engine (ACE, Jet, whatever) has a clever/stupid feature that allows an expression in the SELECT clause to refer to an AS clause ("column alias") in the same SELECT clause if that AS clause is to the left of the expression. This makes it easy to test expressions with test data without using a table at all (assuming ANSI-92 Query Mode, I think) e.g. try executing any of the following statements individually: all should work and produce the expected result:

```<code>SELECT CBOOL(TRUE) AS DayShift,
       IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;

SELECT CBOOL(FALSE) AS DayShift,
       IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;

SELECT NULL AS DayShift,
       IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;

SELECT CBOOL(TRUE) AS DayShift,
       IIF(DayShift, 'Day', 'Night') AS Shift;

SELECT CBOOL(FALSE) AS DayShift,
       IIF(DayShift, 'Day', 'Night') AS Shift;

SELECT NULL AS DayShift,
       IIF(DayShift, 'Day', 'Night') AS Shift;
</code>```

Body:
I have a column called DayShift in a table which is of Yes/No data type (Boolean). The result Output I want is: if the value is true, display "Day" else display night.

I have tried the following:

SELECT iif(DayShift=Yes,"Day","Night") as Shift FROM table1;

SELECT iif(DayShift,"Day","Night") as Shift FROM table1;

SELECT iif(DayShift=True,"Day","Night") as Shift FROM table1;

SELECT iif(DayShift=1,"Day","Night") as Shift FROM table1;

But none of the above work. It just gives me a list of blank check boxes in the output datasheet window. I am using Ms Access 2003. Any help appreciated.

Update:

After a bit of research that the yes/no data type in Ms Access 2003 cannot handle null values appropriately. Hence, the error. Check this link for details.

Update 2

Real Query with the joins. Didnt mention it since i though the information provided above would work.

SELECT tblovertime.contfirstname                        AS [First Name],
       tblovertime.contlastname                         AS [Last Name],
       tblovertime.employeenumber                       AS [Employee Number],
       tblsignup.thedate                                AS [Sign Up Date],
       Iif([tblOvertime.DayShift] =- 1, "Day", "Night") AS shift,
       (SELECT Mid(MIN(Iif(sector = 1, "," & sector, NULL)) & MIN(
                               Iif(sector = 2, "," & sector, NULL)) & MIN(
                               Iif(sector = 3, "," & sector, NULL)) & MIN(
                           Iif(sector = 4, "," & sector, NULL)), 2) AS concat
        FROM   tblempsectorlist
        WHERE  tblempsectorlist.empnum = tblsignup.employeenumber
        GROUP  BY empnum)                               AS sectors,
       tblovertime.timedatecontact                      AS [Date Contacted],
       tblovertimestatus.name                           AS status
FROM   (tblsignup
        INNER JOIN tblovertime
          ON ( tblsignup.thedate = tblovertime.otdate )
             AND ( tblsignup.employeenumber = tblovertime.employeenumber ))
       INNER JOIN tblovertimestatus
         ON Clng(tblovertime.statusid) = tblovertimestatus.statusid
WHERE  (( ( tblsignup.thedate ) ># 1 / 1 / 2011 # ))
ORDER  BY tblsignup.thedate;

Body:
The Access database engine (ACE, Jet, whatever) has a clever/stupid feature that allows an expression in the SELECT clause to refer to an AS clause ("column alias") in the same SELECT clause if that AS clause is to the left of the expression. This makes it easy to test expressions with test data without using a table at all (assuming ANSI-92 Query Mode, I think) e.g. try executing any of the following statements individually: all should work and produce the expected result:

SELECT CBOOL(TRUE) AS DayShift,
       IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;

SELECT CBOOL(FALSE) AS DayShift,
       IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;

SELECT NULL AS DayShift,
       IIF(DayShift = TRUE, 'Day', 'Night') AS Shift;

SELECT CBOOL(TRUE) AS DayShift,
       IIF(DayShift, 'Day', 'Night') AS Shift;

SELECT CBOOL(FALSE) AS DayShift,
       IIF(DayShift, 'Day', 'Night') AS Shift;

SELECT NULL AS DayShift,
       IIF(DayShift, 'Day', 'Night') AS Shift;


问:
I can't write into the shell of the PyCharm when I can write to the shell of Online Python Compiler (Interpreter) of Programiz
I'm doing the tutorial by Programiz and I'm using Pycharm to exercise my knowledge but it seems that I can't write into the Run tab of the Pycharm (or the Shell).

Here's my code:

class PowTwo:
    """Class to implement an iterator
    of powers of two"""

```<code>def __init__(self, max = 0):
    self.max = max

def __iter__(self):
    self.n = 0
    return self

def __next__(self):
    if self.n <= self.max:
        result = 2 ** self.n
        self.n += 1
        return result
    else:
        raise StopIteration
</code>```

I can clearly write to the shell of the Online Compiler but I can't to the PyCharm. What's the problem?

enter image description here

 unlink

答:
PyCharm's Run tab is only for interacting with the program while it is running, it isn't an interactive Python shell like the online REPL is, that's what the Python Console is for.

Open the Python Console tab, enter import [filename without .py] and you've got what you're looking for.

Body:
I'm doing the tutorial by Programiz and I'm using Pycharm to exercise my knowledge but it seems that I can't write into the Run tab of the Pycharm (or the Shell).

Here's my code:

class PowTwo:
    """Class to implement an iterator
    of powers of two"""

def __init__(self, max = 0):
    self.max = max

def __iter__(self):
    self.n = 0
    return self

def __next__(self):
    if self.n <= self.max:
        result = 2 ** self.n
        self.n += 1
        return result
    else:
        raise StopIteration

I can clearly write to the shell of the Online Compiler but I can't to the PyCharm. What's the problem?

enter image description here

 unlink


问:
How can I create SQL table keys with items from looping through a list in Python
I have a list called headers of about 40-50 items, and I'm trying to make them all keys in a table. I'm trying to avoid typing them all out, here's what I have so far:

```<code>def createtable_db():
    cnx = mysql.connector.connect(user='x', password='x', host='x', database='data')

    mycursor = cnx.cursor()

    create_table = "CREATE TABLE IF NOT EXISTS players (id INT AUTO_INCREMENT PRIMARY KEY)"

    for h in headers:
        pop_table = "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

    mycursor.execute(create_table)
    mycursor.execute(pop_table)

    cnx.close()

createtable_db()
</code>```

This only adds the very last key, I tried adding a + to make this line:

```<code> pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"
</code>```

but that's also not working: it gives me a syntax error.

答:
Try initializing pop_table to an empty string and then concatenating to it, inside of the for loop.

```<code>pop_table = ''

for h in headers:
    pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"
</code>```

You could also initialize it to an empty list and append the generated strings

```<code>pop_table = []

for h in headers:
    pop_table.append("ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)")

# join them with you choice of delimiter
joined_up = ','.join(pop_table)
</code>```

Body:
I have a list called headers of about 40-50 items, and I'm trying to make them all keys in a table. I'm trying to avoid typing them all out, here's what I have so far:

def createtable_db():
    cnx = mysql.connector.connect(user='x', password='x', host='x', database='data')

    mycursor = cnx.cursor()

    create_table = "CREATE TABLE IF NOT EXISTS players (id INT AUTO_INCREMENT PRIMARY KEY)"

    for h in headers:
        pop_table = "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

    mycursor.execute(create_table)
    mycursor.execute(pop_table)

    cnx.close()

createtable_db()

This only adds the very last key, I tried adding a + to make this line:

 pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

but that's also not working: it gives me a syntax error.

Body:
Try initializing pop_table to an empty string and then concatenating to it, inside of the for loop.

pop_table = ''

for h in headers:
    pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

You could also initialize it to an empty list and append the generated strings

pop_table = []

for h in headers:
    pop_table.append("ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)")

# join them with you choice of delimiter
joined_up = ','.join(pop_table)


问:
What is the best way to implement google analytics tracking for Actionscript 2?
I am looking for code, examples, library, components for using google analytics event tracking with my Actionscript 2 Flash movies. I can find info about AS3 on the google code site but not AS2. What is the best resource for tutorials and examples about tagging my Flash files to use the asynch google analytics code. I have found some old information about the old google analytics code.

thanks

答:
I have added this to my Flash projects and it seems to work so far. I have not left it long enough to check what has come through on google analytics reports yet but I will update this answer with what comes through.</p>

```<code>import flash.external.ExternalInterface;
//
function ga_track_pageview(_event:String) {
     if(ExternalInterface.available) {
        ExternalInterface.call("_gaq.push",['_trackPageview', _event]);
    }
}
function ga_track_event(_category:String, _action:String, _label:String, _value:Number) {
     if(ExternalInterface.available) {
        ExternalInterface.call("_gaq.push",['_trackEvent', _category, _action, _label, _value]);
    }
}
//
// Button 1 pressed -
btn_1.onRelease = function() {
    _root.ga_track_event("button", "pressed", "button1", null);
}
// Button 2 pressed -
btn_2.onRelease = function() {
    _root.ga_track_event("button", "pressed", "button2", null);
}
// Tracking a page view -
ga_track_pageview("testpage_opened");
</code>```

Body:
I have added this to my Flash projects and it seems to work so far. I have not left it long enough to check what has come through on google analytics reports yet but I will update this answer with what comes through.

import flash.external.ExternalInterface;
//
function ga_track_pageview(_event:String) {
     if(ExternalInterface.available) {
        ExternalInterface.call("_gaq.push",['_trackPageview', _event]);
    }
}
function ga_track_event(_category:String, _action:String, _label:String, _value:Number) {
     if(ExternalInterface.available) {
        ExternalInterface.call("_gaq.push",['_trackEvent', _category, _action, _label, _value]);
    }
}
//
// Button 1 pressed -
btn_1.onRelease = function() {
    _root.ga_track_event("button", "pressed", "button1", null);
}
// Button 2 pressed -
btn_2.onRelease = function() {
    _root.ga_track_event("button", "pressed", "button2", null);
}
// Tracking a page view -
ga_track_pageview("testpage_opened");


问:
Typescript Intface Array with elementd being Object or null
Im trying to convert this JSON prototype into a typescript interface

```<code>{
  "foo": [
     null,
     null,
     null,
     {...}
     null,
     {...}
   ]
}
</code>```

Basically all elements of array foo can either be Object | null.
I know in typescript you can have something like this

```<code>interface Example {
  test: String | null;
}
</code>```

but I don't see any examples for dynamic array types.

Would a better approach be using the ? instead?

```<code>interface Example {
  test?: Object;
}
</code>```

答:
Thanks to Aleksey L, it seems that is the correct the way of doing things. To anybody finding this question later the correct interface to model the given json
object is</p>

```<code>interface Example {
  foo: Array<object | null>
}
</code>```

Body:
Im trying to convert this JSON prototype into a typescript interface

{
  "foo": [
     null,
     null,
     null,
     {...}
     null,
     {...}
   ]
}

Basically all elements of array foo can either be Object | null.
I know in typescript you can have something like this

interface Example {
  test: String | null;
}

but I don't see any examples for dynamic array types.

Would a better approach be using the ? instead?

interface Example {
  test?: Object;
}

Body:
Thanks to Aleksey L, it seems that is the correct the way of doing things. To anybody finding this question later the correct interface to model the given json
object is

interface Example {
  foo: Array<object | null>
}


问:
Regular expression for all abbreviated keyword variations
I need to search for a keyword, such as "abcdef", which can also be in an abbreviated version with a dot at the end. All valid variants are:

```<code>abcdef
abcde.
abcd.
abc.
ab.
a.
</code>```

I have a regular expression for this, which is clear:

```<code>abcdef|abcde\.|abcd\.|abc\.|ab\.|a\.
</code>```

Another regular expression where the keyword characters are not repeated:

```<code>a(b(c(d(e(f|\.)|\.)|\.)|\.)|\.)
</code>```

I'm looking for a more compact expression where not even a dot will be repeated.
I use .NET syntax.

答:
You can use a conditional construct:

```<code>a(b(c(d(e(?<f>f)?)?)?)?)?(?(f)|\.?)
</code>```

See the regex demo. Here, (?<f>f)? is an optional named group matching f one or zero times. If the group matches, the f group is not empty, and (?(f)|\.?) matches an empty string then. If it is empty, \.? matches an optional ..

In PCRE falvor, could use

```<code>a(b(c(d(e(f(*ACCEPT))?)?)?)?)?\.?
</code>```

where (*ACCEPT) verb inside an optional group would stop analyzing the current regex and return the value matched so far (so the last \.? would not be tried if f is found). See this regex flavor.

Body:
I need to search for a keyword, such as "abcdef", which can also be in an abbreviated version with a dot at the end. All valid variants are:

abcdef
abcde.
abcd.
abc.
ab.
a.

I have a regular expression for this, which is clear:

abcdef|abcde\.|abcd\.|abc\.|ab\.|a\.

Another regular expression where the keyword characters are not repeated:

a(b(c(d(e(f|\.)|\.)|\.)|\.)|\.)

I'm looking for a more compact expression where not even a dot will be repeated.
I use .NET syntax.

Body:
You can use a conditional construct:

a(b(c(d(e(?<f>f)?)?)?)?)?(?(f)|\.?)

See the regex demo. Here, (?<f>f)? is an optional named group matching f one or zero times. If the group matches, the f group is not empty, and (?(f)|\.?) matches an empty string then. If it is empty, \.? matches an optional ..

In PCRE falvor, could use

a(b(c(d(e(f(*ACCEPT))?)?)?)?)?\.?

where (*ACCEPT) verb inside an optional group would stop analyzing the current regex and return the value matched so far (so the last \.? would not be tried if f is found). See this regex flavor.


问:
How can I use a loop to get clockwise spiral output in matrix as an independent output?
This image explains the problem I'm trying to solve.

And here is my attempted solution:

```<code>matrix = [[1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
      [16, 17, 18, 19, 20]]
i = 0
y = (len(matrix)-1)
while i < len(matrix):
    if i == 0:
        # print 1st row.
        for rows in matrix[i]:
            print(rows)

    # print all the last element of every rows, except 1st and last row.
    elif i != 0 and i != y:
        print(matrix[i][-1])

    # print the last row in reverse.
    elif i == y and i != 0:
        matrix[i].sort(reverse=True)
        for row in matrix[i]:
            print(row)

        print(matrix[i-1][0])       # print the 1st element of 3rd row.

        # print the 1st four elements of 2nd row.
        for r in matrix[1][0:4]:
            print(r)

        # finally print the rest of the elements in reverse.
        matrix[2].sort(reverse=True)
        for r_remain in matrix[2][1:4]:
            print(r_remain)

    i += 1
</code>```

My question is, is this algorithm right or wrong?

Secondly, my algorithm depends on the size and contents of the input matrix. How can I make it work for any input?

答:
One can obtain a very short solution using numpy, although that is perhaps not in the spirit of the assignment (the library does most of the work):</p>

```<code>import numpy

matrix = [[ 1,  2,  3,  4,  5],
          [14, 15, 16, 17,  6],
          [13, 20, 19, 18,  7],
          [12, 11, 10,  9,  8]]

def recurse(matrix):
    if not len(matrix): return
    for el in matrix[0]: print(el)
    recurse(numpy.rot90(matrix[1:]))

recurse(numpy.array(matrix))
</code>```

Body:
This image explains the problem I'm trying to solve.

And here is my attempted solution:

matrix = [[1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
      [16, 17, 18, 19, 20]]
i = 0
y = (len(matrix)-1)
while i < len(matrix):
    if i == 0:
        # print 1st row.
        for rows in matrix[i]:
            print(rows)

    # print all the last element of every rows, except 1st and last row.
    elif i != 0 and i != y:
        print(matrix[i][-1])

    # print the last row in reverse.
    elif i == y and i != 0:
        matrix[i].sort(reverse=True)
        for row in matrix[i]:
            print(row)

        print(matrix[i-1][0])       # print the 1st element of 3rd row.

        # print the 1st four elements of 2nd row.
        for r in matrix[1][0:4]:
            print(r)

        # finally print the rest of the elements in reverse.
        matrix[2].sort(reverse=True)
        for r_remain in matrix[2][1:4]:
            print(r_remain)

    i += 1

My question is, is this algorithm right or wrong?

Secondly, my algorithm depends on the size and contents of the input matrix. How can I make it work for any input?

Body:
One can obtain a very short solution using numpy, although that is perhaps not in the spirit of the assignment (the library does most of the work):

import numpy

matrix = [[ 1,  2,  3,  4,  5],
          [14, 15, 16, 17,  6],
          [13, 20, 19, 18,  7],
          [12, 11, 10,  9,  8]]

def recurse(matrix):
    if not len(matrix): return
    for el in matrix[0]: print(el)
    recurse(numpy.rot90(matrix[1:]))

recurse(numpy.array(matrix))


问:
AWS Lex bot: Enable user to continue conversation after page refresh
I'm currently building a bot using AWS Lex. One issue I'm facing is how to store the user's session and the retrieve it in order for the bot to be able to continue the conversation (and show the previous conversation) if the user goes to a new page, refreshes the page or returns after for example a week?

e.g. 1
For example, the bot is helping the user make a buying decision while the user is checking different pages on an ecommerce site.

e.g. 2
Another example could be where the user revisits the website after a week and the bot recognises the user, shows the previous conversation history and sends a customised message?

答:
AWS provides LexRuntime javascript APIs for web integration. This API provides the NLP but does not store/fetch the conversation history. You have to create your own application server and store conversations into DB. You also need to manage the database of users coming to your website.

When a user visits the website, get the conversation history of the user from DB and populate it on UI. This way even a user refreshes a page he will be able to see the chat history as it is being loaded from DB.

Now the question is How does the Lex remember the user and for how long?

The Lex creates user session using the below parameters :

Bot name

Bot alias

User id

These parameters are sent to Lex along with user queries. Here user id can be any unique identifier that represents a user of your website. Lex uses these parameters to determine the session for the current user query. If any of these values are changed Lex will create a new session or reuse existing if available for the same set of values. By default, the session duration is 5 minutes, but you can specify any duration between 0 and 1,440 minutes (24 hours).

Using the Lex Runtime APIs you can use below two methods to send the user queries to your bot:

PostContent

PostText

Both methods require botName, aliasName, and userId parameters. I hope this answers your second question.

Now coming to your first use case where

A bot is helping the user  to make a buying decision while the user is
  checking different pages on an e-commerce site.

To achieve this, first, you have to implement the above approach. Once this is done, you can send the page URL(in which bot sits) to Lex. You can send this info as a request attribute. At the Lex console, use a lambda function to determine the response according to the page URL.

All this takes the development efforts and time. There are a lot of third-party tools available that provide the code less integration with lex. I recommend the Kommunicate. Have a look at this blog too.


问:
Rails Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
I'm building a rails app and I'm having trouble installing docker.

The build works, but when I try to create the DB with this command :

```<code>docker-compose run web bundle exec rails db:create
</code>```

it throws this error :

```<code>could not connect to server: Connection refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?
could not connect to server: Address not available
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 5432?
</code>```

I've try to rename the host from localhost to db, it didn't work and I also tried to edit my etc/hosts.

docker-compose.yml

```<code>version: '3'
services:
  localhost:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - localhost
    working_dir: /myapp

</code>```

Dockerfile

```<code>FROM ruby:2.6.2-alpine

RUN apk add --no-cache build-base postgresql-dev tzdata libxml2-dev libxslt-dev nodejs yarn

RUN mkdir /myapp
WORKDIR /myapp

COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
COPY package.json /myapp/package.json

RUN gem install bundler:2.1.2
RUN bundle install

COPY . /myapp

RUN yarn install --check-files
</code>```

database.yml

```<code>default: &default
  adapter: postgresql
  encoding: unicode
  host: localhost
  username: postgres
  password:
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: myapp_development
</code>```

/etc/hosts

```<code># Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
# Added by Docker Desktop
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section
127.0.0.1 postgres
</code>```

How can I fix this issue ? I'm not sure what I'm missing!

答:
In Docker each "service" runs in its own container. So you would have the Rails app and the database in different containers. Each service is conceptually speaking a different server.

Your error (Is the server running on host "localhost" (127.0.0.1)..) suggests that your Rails application is looking for a database engine on the same machine. That DB is running on a separate server.

In a docker-compose file each service is addressable by its name. So change the connection string or setting in your Rails app from localhost to db or something.

Edit: I just now see that you named your DB server localhost, that's asking for trouble. Change that to db or something? :)

Body:
I'm building a rails app and I'm having trouble installing docker.

The build works, but when I try to create the DB with this command :

docker-compose run web bundle exec rails db:create

it throws this error :

could not connect to server: Connection refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?
could not connect to server: Address not available
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 5432?

I've try to rename the host from localhost to db, it didn't work and I also tried to edit my etc/hosts.

docker-compose.yml

version: '3'
services:
  localhost:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - localhost
    working_dir: /myapp

Dockerfile

FROM ruby:2.6.2-alpine

RUN apk add --no-cache build-base postgresql-dev tzdata libxml2-dev libxslt-dev nodejs yarn

RUN mkdir /myapp
WORKDIR /myapp

COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
COPY package.json /myapp/package.json

RUN gem install bundler:2.1.2
RUN bundle install

COPY . /myapp

RUN yarn install --check-files

database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  host: localhost
  username: postgres
  password:
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: myapp_development

/etc/hosts

# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
# Added by Docker Desktop
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section
127.0.0.1 postgres

How can I fix this issue ? I'm not sure what I'm missing!


问:
Angular 8 : How to send the value from *ngfor to TS file
I have a code

```<code><div *ngFor="let a of ABC">
{{a.error}}
</div>
</code>```

Now I want to send the value of a to my TS file. I want to meet some expectation say 'a.error == true' then call some function and assign the value of a to some variable in ts file.

I hope it is clear. please ask if require more clarification

答:
To communicate with the ts file as you say you just call a function which you declare

```<code>// In your ts.file

someFunction(a: any) {
  // some amazing stuff
  return 'Hello World';
}
</code>```

and in your template

```<code><div *ngFor="let a of ABC">
  {{ someFunction(a) }}
</div>
</code>```

Body:
I have a code

{{a.error}}

Now I want to send the value of a to my TS file. I want to meet some expectation say 'a.error == true' then call some function and assign the value of a to some variable in ts file.

I hope it is clear. please ask if require more clarification

Body:
To communicate with the ts file as you say you just call a function which you declare

// In your ts.file

someFunction(a: any) {
  // some amazing stuff
  return 'Hello World';
}

and in your template

<div *ngFor="let a of ABC">
  {{ someFunction(a) }}
</div>


问:
How can create a Junit4 Suite with Groovy?
I have

```<code>@RunWith(Suite.class)
 @Suite.SuiteClasses( [
     First.class,Second.class
 ])
 public class MySuite{

}
</code>```

But eclipse doesn't give me a "Run As Junit4 Test".  All the individual test classes work fine with GUnit, the groovy unit test runner built into eclipse.

Any thoughts?

答:
@Suite.SuiteClasses accepts Class[] as its parameter.

You may try:

```<code> @RunWith(Suite.class)
 @Suite.SuiteClasses([First.class, Second.class] as Class[])
 public class MySuite {

 }
</code>```

OwnerDisplayName: John Russell

ContentLicense: CC BY-SA 2.5

Body:
I have

@RunWith(Suite.class)
 @Suite.SuiteClasses( [
     First.class,Second.class
 ])
 public class MySuite{

}

But eclipse doesn't give me a "Run As Junit4 Test".  All the individual test classes work fine with GUnit, the groovy unit test runner built into eclipse.

Any thoughts?

Body:
@Suite.SuiteClasses accepts Class[] as its parameter.

You may try:

 @RunWith(Suite.class)
 @Suite.SuiteClasses([First.class, Second.class] as Class[])
 public class MySuite {

 }

OwnerDisplayName: chanwit


问:
How to convert List of Double to List of String?
This just might be too easy for all of you, but I am just learning and implementing Java in a project and am stuck with this.

How to convert List of Double  to List String?

答:
You have to iterate over your double list and add to a new list of strings.</p>

```<code>List<String> stringList = new LinkedList<String>();
for(Double d : YOUR_DOUBLE_LIST){
   stringList.add(d.toString());
}
return stringList;
</code>```

Body:
You have to iterate over your double list and add to a new list of strings.

List<String> stringList = new LinkedList<String>();
for(Double d : YOUR_DOUBLE_LIST){
   stringList.add(d.toString());
}
return stringList;