问:
Google Assistant sdk GRPC authentication error : io.grpc.StatusRuntimeException: UNAUTHENTICATED:
I successfully created EmbeddedAssistantStub using the below code.

```<code>EmbeddedAssistantGrpc.EmbeddedAssistantStub mAssistantService = EmbeddedAssistantGrpc.newStub(channel)
                                  .withCallCredentials(MoreCallCredentials.from(
                                            Credentials.fromResource(mClientId,mRefreshToken,mAccessToken)
                                   ));
</code>```

After this i passed audio data to StreamObserver, At that time below exxception was occured.

```<code>Line 3378: 12-07 12:59:25.099  1917  4286 E  GASample: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Line 3378: 12-07 12:59:25.099  1917  4286 E  GASample: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Line 3379: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.Status.asRuntimeException(Status.java:540)
Line 3380: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:392)
Line 3381: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:428)
Line 3382: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:76)
Line 3383: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:514)
Line 3384: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$700(ClientCallImpl.java:431)
Line 3385: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:546)
Line 3386: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
Line 3387: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.SerializingExecutor$TaskRunner.run(SerializingExecutor.java:152)
Line 3388: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
Line 3389: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
Line 3390: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.lang.Thread.run(Thread.java:764)
</code>```

After this no response from response observer.

Kindly help me to solve this issue.

答:
They messed up with their backend. Just wait until they fix it. Here is the github thread regarding that bug:
https://github.com/googlesamples/assistant-sdk-python/issues/138</p>

Body:
I successfully created EmbeddedAssistantStub using the below code.

EmbeddedAssistantGrpc.EmbeddedAssistantStub mAssistantService = EmbeddedAssistantGrpc.newStub(channel)
                                  .withCallCredentials(MoreCallCredentials.from(
                                            Credentials.fromResource(mClientId,mRefreshToken,mAccessToken)
                                   ));

After this i passed audio data to StreamObserver, At that time below exxception was occured.

Line 3378: 12-07 12:59:25.099  1917  4286 E  GASample: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Line 3378: 12-07 12:59:25.099  1917  4286 E  GASample: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Line 3379: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.Status.asRuntimeException(Status.java:540)
Line 3380: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:392)
Line 3381: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:428)
Line 3382: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:76)
Line 3383: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:514)
Line 3384: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$700(ClientCallImpl.java:431)
Line 3385: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:546)
Line 3386: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
Line 3387: 12-07 12:59:25.099  1917  4286 E  GASample:  at io.grpc.internal.SerializingExecutor$TaskRunner.run(SerializingExecutor.java:152)
Line 3388: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
Line 3389: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
Line 3390: 12-07 12:59:25.099  1917  4286 E  GASample:  at java.lang.Thread.run(Thread.java:764)

After this no response from response observer.

Kindly help me to solve this issue.


来源: stackexchange

问:
How to use bootstrap in Meteor?
I'm trying to use bootstrap in meteor 1.0.
I add bootstrap package in meteor with this command: "meteor add bootstrap".
But it can't works for me correctly.

I need one row with two columns.
This is my html:

```<code>    <head>
    <meta charset="utf-8">
    <title>Аггрегатор новостей</title>
</head>

<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-6">.col-md-6</div>
        <div class="col-md-6">.col-md-6</div>
    </div>
</div>
</body>
</code>```

But I see two rows with 100% width. Wherein container or container-fluid  works, I see this is one the screen.
What is the problem?
I need to link bootstrap.css in header? But Meteor do this automatically IMHO.

Thank you.

答:
Starting from Meteor 1.3 which offers first-class npm support, the recommended approach is to install Bootstrap directly from npm.

```<code>$ meteor npm install --save bootstrap
</code>```

(This also saves bootstrap in your package.json file so someone else who checks out your app can install it with meteor npm install.)

Then, in any client-side JS file (e.g. /client/main.js):

```<code>import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
</code>```

If you're interested in more customized Bootstrap installs using SASS/SCSS, etc. check out this post.

ContentLicense: CC BY-SA 3.0

Title: How to use bootstrap in Meteor?

Body:
I'm trying to use bootstrap in meteor 1.0.
I add bootstrap package in meteor with this command: "meteor add bootstrap".
But it can't works for me correctly.

I need one row with two columns.
This is my html:

    <meta charset="utf-8">
    <title>Аггрегатор новостей</title>

.col-md-6

.col-md-6

But I see two rows with 100% width. Wherein container or container-fluid  works, I see this is one the screen.
What is the problem?
I need to link bootstrap.css in header? But Meteor do this automatically IMHO.

Thank you.

Body:
Starting from Meteor 1.3 which offers first-class npm support, the recommended approach is to install Bootstrap directly from npm.

$ meteor npm install --save bootstrap

(This also saves bootstrap in your package.json file so someone else who checks out your app can install it with meteor npm install.)

Then, in any client-side JS file (e.g. /client/main.js):

import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';

If you're interested in more customized Bootstrap installs using SASS/SCSS, etc. check out this post.


问:
scanf picking up characters after whitespace C
I am writing a program that takes a line of user input and stores the data in a struct that is then used in a linked list. The data is entered in the following format: command_name full_name address account_balance

command_name calls the function;

full_name is a single char array with a dash instead of a space.

address is a single char array with street,city,state,zip all separated by a comma

account_balance is a double.

I have a function to replace the '-' and ',' chars with spaces so they contain whitespace.

The issue I am having is that when I read the address the state is read as the state and zip stuck together. The zip is read fine and all other input is read fine. Just the state. It is slowly driving me into madness so I have decided to ask for help. I've attached the code of the insert and print methods below along with a sample printout of a struct.

```<code>Input: insert rick137 schwifty-ln,mango,nc,28105 2500

Sample output:

rick137
schwifty ln
mango, nc28105 28105
  2500.00

Desired output:

rick137
schwifty ln
mango, nc 28105
  2500.00
</code>```

Below is my code:

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

#define NAME_LEN 40
#define ADDRESS_LEN 98
#define MENU_LEN 11

  typedef struct customer {
        char full_name[NAME_LEN+1];
        char address[ADDRESS_LEN+1];
        char street[55];
        char city[32];
        char state[2];
        char zip[5];
        double account_balance;
        struct customer *next;
    }customer;

    customer *database = NULL;

 int strcasecmp(const char *s1, const char *s2);

 void rem_dash(char * str);

 void rem_dash(char *str){
     int i=0;
     while(str[i]!='\0')
     {
           if(str[i]=='-')
           {
               str[i]=' ';
           }
           i++;
     }
 }

 void rem_comma(char *str);
 void rem_comma(char *str){
     int i=0;
     while(str[i]!='\0')
     {
          if(str[i]==',')
          {
              str[i]=' ';
          }
          i++;
     }
 }

 void split_add(char *address, char *street, char *city, char *state, char *zip);

 void split_add(char *address, char *street, char *city, char *state, char *zip){

    rem_comma(address);

    printf("%s\n", address);

    sscanf(address, "%s %s %s %s", street, city, state, zip);

    rem_dash(street);
    rem_dash(city);
    rem_dash(state);
    rem_dash(zip);

 }

    void insert_customer(void);

    void insert_customer(void){

        customer *current, *prev, *new_customer;

        new_customer =  malloc(sizeof(struct customer));
        current=NULL;
        prev=NULL;

        if(new_customer==NULL){
            printf("Database full, cannot add more customers.\n");
            return;
        }

        scanf("%40s %98s %lf", new_customer->full_name, new_customer->address, &new_customer->account_balance);

        rem_dash(new_customer->full_name);

        printf("%s\n", new_customer->full_name);

        split_add(new_customer->address,  new_customer->street,  new_customer->city,  new_customer->state,  new_customer->zip);

        //printf("%s\n%s, %s %s\n", new_customer->street, new_customer->city, new_customer->state, new_customer->zip);

       current=database;
       prev=NULL;

       for (;current != NULL;prev = current, current = current->next){

         if (current != NULL && strcmp(new_customer->full_name, current->full_name)==0) {
            printf("DUPLICATE RECORD\n");
            free(new_customer);
            return;
            }
        }

       current=database;
       prev=NULL;

       while(current != NULL && strcmp(current->full_name, new_customer->full_name)<0){
          prev=current;
          current=current->next;
       }

       new_customer->next=current;

       if(prev==NULL){
           database=new_customer;
       }
       else{
           prev->next=new_customer;
       }

       printf("RECORD INSERTED\n");
 }

void print_list(void);

void print_list(void){
    customer *print;

    for (print=database; print != NULL; print = print->next){
    printf("%s\n%s\n%s, %2s %5s\n%9.2f\n-----\n", print->full_name, print->street, print->city, print->state, print->zip, print->account_balance);
    }
}
</code>```

答:
Your struct does not allow enough space for string terminators.  The state field needs a capacity of at least 3 (two characters plus a terminator), and the zip field needs a capacity of at least 6.  You might or might not want larger capacity for the other fields.

When you read into the existing struct, you overrun the boundaries of some of the member arrays, producing undefined behavior.  The actual output suggests that the terminator of your state string is being overwritten by the first character of the zip, but that's a post hoc analysis -- you cannot assume that it would work that way in all cases.

Body:
I am writing a program that takes a line of user input and stores the data in a struct that is then used in a linked list. The data is entered in the following format: command_name full_name address account_balance

command_name calls the function;

full_name is a single char array with a dash instead of a space.

address is a single char array with street,city,state,zip all separated by a comma

account_balance is a double.

I have a function to replace the '-' and ',' chars with spaces so they contain whitespace.

The issue I am having is that when I read the address the state is read as the state and zip stuck together. The zip is read fine and all other input is read fine. Just the state. It is slowly driving me into madness so I have decided to ask for help. I've attached the code of the insert and print methods below along with a sample printout of a struct.

Input: insert rick137 schwifty-ln,mango,nc,28105 2500

Sample output:

rick137
schwifty ln
mango, nc28105 28105
  2500.00

Desired output:

rick137
schwifty ln
mango, nc 28105
  2500.00

Below is my code:

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

#define NAME_LEN 40
#define ADDRESS_LEN 98
#define MENU_LEN 11

  typedef struct customer {
        char full_name[NAME_LEN+1];
        char address[ADDRESS_LEN+1];
        char street[55];
        char city[32];
        char state[2];
        char zip[5];
        double account_balance;
        struct customer *next;
    }customer;

    customer *database = NULL;

 int strcasecmp(const char *s1, const char *s2);

 void rem_dash(char * str);

 void rem_dash(char *str){
     int i=0;
     while(str[i]!='\0')
     {
           if(str[i]=='-')
           {
               str[i]=' ';
           }
           i++;
     }
 }

 void rem_comma(char *str);
 void rem_comma(char *str){
     int i=0;
     while(str[i]!='\0')
     {
          if(str[i]==',')
          {
              str[i]=' ';
          }
          i++;
     }
 }

 void split_add(char *address, char *street, char *city, char *state, char *zip);

 void split_add(char *address, char *street, char *city, char *state, char *zip){

    rem_comma(address);

    printf("%s\n", address);

    sscanf(address, "%s %s %s %s", street, city, state, zip);

    rem_dash(street);
    rem_dash(city);
    rem_dash(state);
    rem_dash(zip);

 }

    void insert_customer(void);

    void insert_customer(void){

        customer *current, *prev, *new_customer;

        new_customer =  malloc(sizeof(struct customer));
        current=NULL;
        prev=NULL;

        if(new_customer==NULL){
            printf("Database full, cannot add more customers.\n");
            return;
        }

        scanf("%40s %98s %lf", new_customer->full_name, new_customer->address, &new_customer->account_balance);

        rem_dash(new_customer->full_name);

        printf("%s\n", new_customer->full_name);

        split_add(new_customer->address,  new_customer->street,  new_customer->city,  new_customer->state,  new_customer->zip);

        //printf("%s\n%s, %s %s\n", new_customer->street, new_customer->city, new_customer->state, new_customer->zip);

       current=database;
       prev=NULL;

       for (;current != NULL;prev = current, current = current->next){

         if (current != NULL && strcmp(new_customer->full_name, current->full_name)==0) {
            printf("DUPLICATE RECORD\n");
            free(new_customer);
            return;
            }
        }

       current=database;
       prev=NULL;

       while(current != NULL && strcmp(current->full_name, new_customer->full_name)<0){
          prev=current;
          current=current->next;
       }

       new_customer->next=current;

       if(prev==NULL){
           database=new_customer;
       }
       else{
           prev->next=new_customer;
       }

       printf("RECORD INSERTED\n");
 }

void print_list(void);

void print_list(void){
    customer *print;

    for (print=database; print != NULL; print = print->next){
    printf("%s\n%s\n%s, %2s %5s\n%9.2f\n-----\n", print->full_name, print->street, print->city, print->state, print->zip, print->account_balance);
    }
}


问:
When to call pipe from the controller when there's a change on the input values?
I have a table filled out with data like this :

```<code>  <tr *ngFor="let row of allData | filterPipe:color:currentDate ">
          <td *ngIf="row != -1">{{row.date| date:'MM/dd/yy'}} </td>
          <td>{{row.Color}}</td>
          <td>{{row.Name}}</td>
</code>```

And I have a pipe that filters based on color and date:

```<code>  transform(value: any, color: any, currentData: any):any{
      if(color)
            value=value.filter(item=>item.Color==color));
      filter by date
   return value
  }
</code>```

What I want to do, is invoke the pipe from the controller instead of the html, because I need the to have a variable that will hold the filtered data. Because I need to export the filtered data in csv format. In the controller I have a function that does that : this.allData.forEach((row: MyData) => { csvContent += MyData.toCsv(row) + "\r\n"; });

So in the component ts I was thinking,after importing it to initalize it like this :

```<code>    let filterPipe=new FilterPipe();
    this.filteredData=filterPipe.transform(this.allData,this.color,this.currentDate)
</code>```

And then on the html to have :

```<code>   <tr *ngFor="let row of filteredData">
</code>```

But as i have it, whenever color is chosen ( it's a dropdown value from a ngModel) or currentDate, it invokes the pipe.
Where do I call the pipe in the controller, so that it gets invoked the same way ?
except that I really need to have access to the filteredData so that I can export it later on.

Or if there's a way to bind the filtered data after it's returned, to the controller so that I have that as an object in the controller for exporting.

Any guidance is appreciated!

Edit:

Initially I want to have a default filter, that filters data where date=now.
That data will be sliced 10 and added more in scrolling as needed.
Then user can choose to filter based on a color and change the date.

So if I have a function

```<code>filterByDate(date:any){
this.filteredData=this.allData.filter... where date=date
}

filterByColor(color:string)
{
this.filteredData=this.allData.filter where color=color;
}
</code>```

and I bind the ngModel of the dropdown and the input field of both.
How do I manage it without breaking the flow that i had?
How do I make it that what's returned on ngOnInit is first filtered for todays date, then displayed?

When I had it on the html, on the pipe function I had an if(startDate empty) then default filter for moment(). Else filter for startDate.

答:
Since Pipes are purely presentational and can not mutate their data source, I would suggest filtering entirely in the Component.

First, implement your filtering function in the Component, like

```<code>filterList(color: string) {
  this.filteredData = this.allData.filter(item => item.Color === color);
}
</code>```

Not forgetting that when you make your service call to get allData the first time, you also set filteredData to the full list.

Then, just bind your filter function to an (ngModelChange) event of your filter dropdown (something like (ngModelChange)="filterList($event.target.value)") so that when you change the drop-down it will run your filter.

Then just always display the filtered data:
 and change detection will update the list for you when filteredData changes.

EDIT

Since you need to show only 10 rows of data, you could write a second utility function, store the cursor position, slice and return the desired window:

```<code>cursor: number = 0;

function onScroll(down: boolean) {
  // Slice your array
  this.windowData = this.filteredData.slice(this.cursor,
    down ? this.cursor + 10 : this.cursor - 10);

  // Update the cursor to your new position
  this.cursor = down ? this.cursor + 10 : this.cursor - 10;
}
</code>```

And instead show windowData in your *ngFor, also remembering to set the first windowData on load.

Body:
I have a table filled out with data like this :

          {{row.date| date:'MM/dd/yy'}}
          {{row.Color}}
          {{row.Name}}

And I have a pipe that filters based on color and date:

  transform(value: any, color: any, currentData: any):any{
      if(color)
            value=value.filter(item=>item.Color==color));
      filter by date
   return value
  }

What I want to do, is invoke the pipe from the controller instead of the html, because I need the to have a variable that will hold the filtered data. Because I need to export the filtered data in csv format. In the controller I have a function that does that : this.allData.forEach((row: MyData) => { csvContent += MyData.toCsv(row) + "\r\n"; });

So in the component ts I was thinking,after importing it to initalize it like this :

    let filterPipe=new FilterPipe();
    this.filteredData=filterPipe.transform(this.allData,this.color,this.currentDate)

And then on the html to have :

But as i have it, whenever color is chosen ( it's a dropdown value from a ngModel) or currentDate, it invokes the pipe.
Where do I call the pipe in the controller, so that it gets invoked the same way ?
except that I really need to have access to the filteredData so that I can export it later on.

Or if there's a way to bind the filtered data after it's returned, to the controller so that I have that as an object in the controller for exporting.

Any guidance is appreciated!

Edit:

Initially I want to have a default filter, that filters data where date=now.
That data will be sliced 10 and added more in scrolling as needed.
Then user can choose to filter based on a color and change the date.

So if I have a function

filterByDate(date:any){
this.filteredData=this.allData.filter... where date=date
}

filterByColor(color:string)
{
this.filteredData=this.allData.filter where color=color;
}

and I bind the ngModel of the dropdown and the input field of both.
How do I manage it without breaking the flow that i had?
How do I make it that what's returned on ngOnInit is first filtered for todays date, then displayed?

When I had it on the html, on the pipe function I had an if(startDate empty) then default filter for moment(). Else filter for startDate.

Body:
Since Pipes are purely presentational and can not mutate their data source, I would suggest filtering entirely in the Component.

First, implement your filtering function in the Component, like

filterList(color: string) {
  this.filteredData = this.allData.filter(item => item.Color === color);
}

Not forgetting that when you make your service call to get allData the first time, you also set filteredData to the full list.

Then, just bind your filter function to an (ngModelChange) event of your filter dropdown (something like (ngModelChange)="filterList($event.target.value)") so that when you change the drop-down it will run your filter.

Then just always display the filtered data: <tr *ngFor="let row of filteredData"> and change detection will update the list for you when filteredData changes.

EDIT

Since you need to show only 10 rows of data, you could write a second utility function, store the cursor position, slice and return the desired window:

cursor: number = 0;

function onScroll(down: boolean) {
  // Slice your array
  this.windowData = this.filteredData.slice(this.cursor,
    down ? this.cursor + 10 : this.cursor - 10);

  // Update the cursor to your new position
  this.cursor = down ? this.cursor + 10 : this.cursor - 10;
}

And instead show windowData in your *ngFor, also remembering to set the first windowData on load.


问:
Trouble solving generated output
I'm fairly new to java and am having trouble preparing for an exam. This sample question asks to show work to give the exact output generated by this code:

```<code>public class Lab7Experiment extends JApplet
{
    int x=3, y=-3, z=5;
    int someValues [] = {2, -6, 4, -4, 6, -2};

    public void init()
    {
        char y = 'y';
        z=10;
        System.out.println("Print 1 x,y,z, = "+x+" "+y+" "+z);
        y= sub1(x,y,z);
        System.out.println("Print 2 x,y,z, = "+x+" "+y+" "+z);
        x= sub2(x, someValues);
        System.out.println("Print 3 x,y,z, = "+x+" "+y+" "+z);
        for (int i=0; i<3; i++)
            System.out.println("Print "+(i+4)+" "+someValues[i*2]+" "+someValues[i*2+1]);
    }
    public char sub1(int a, char b, int c)
    {
        if (a>=c)
            return b;
        else
        {
            c=15;
            z=25;
            return 'z';
        }
    }
    public int sub2(int x, int [] anArray)
    {
        int y=0;
        for(int i=anArray.length-1; i>=0; i--)
        {
            if (anArray[i] > x)
            {
                anArray[i]=x;
                y++;
            }

        }
        x=100;
        return y;
    }

}
</code>```

I'm having trouble understanding how the someValues array and anArray are used when generating this output. I've run it in Eclipse so I'm able to check my answers, but I'm not sure why the generated output results are what they are. Can someone explain this to me? Would appreciate it so much. Thanks

答:
It is a long answer(s) and not an issue to solve...

BTW:

Print 1 x,y,z, = 3 y 10

because class variable x = 3: int x=3
then local variable char y = 'y' is used and z changed to 10 z=10;

Print 2 x,y,z, = 3 z 25
because class variable x still untouched. in sub1: 3 is not >= 10 (passed z), so else branch:

```<code>    `c=15;` does not change passed `x` Java is `pass-by-value`
    `z=25;` changes class variable `z` to 25
    return 'z';
</code>```

then local variable y now is 'z'

after sub2 you have:

class variable x = 2

 class variable y =-3

 class variable z = 25

 local variable y = 'y'

UPDATED:     class variable someValues [] = {2, -6, 3, -4, 3, -2};

then follow last loop to get Print 4,5 and 6 from someValues as:

```<code>`Print 4 2 -6`
`Print 5 3 -4`
`Print 6 3 -2`
</code>```

good luck!

Title: Trouble solving generated output

Body:
I'm fairly new to java and am having trouble preparing for an exam. This sample question asks to show work to give the exact output generated by this code:

public class Lab7Experiment extends JApplet
{
    int x=3, y=-3, z=5;
    int someValues [] = {2, -6, 4, -4, 6, -2};

    public void init()
    {
        char y = 'y';
        z=10;
        System.out.println("Print 1 x,y,z, = "+x+" "+y+" "+z);
        y= sub1(x,y,z);
        System.out.println("Print 2 x,y,z, = "+x+" "+y+" "+z);
        x= sub2(x, someValues);
        System.out.println("Print 3 x,y,z, = "+x+" "+y+" "+z);
        for (int i=0; i<3; i++)
            System.out.println("Print "+(i+4)+" "+someValues[i*2]+" "+someValues[i*2+1]);
    }
    public char sub1(int a, char b, int c)
    {
        if (a>=c)
            return b;
        else
        {
            c=15;
            z=25;
            return 'z';
        }
    }
    public int sub2(int x, int [] anArray)
    {
        int y=0;
        for(int i=anArray.length-1; i>=0; i--)
        {
            if (anArray[i] > x)
            {
                anArray[i]=x;
                y++;
            }

        }
        x=100;
        return y;
    }

}

I'm having trouble understanding how the someValues array and anArray are used when generating this output. I've run it in Eclipse so I'm able to check my answers, but I'm not sure why the generated output results are what they are. Can someone explain this to me? Would appreciate it so much. Thanks

Body:
It is a long answer(s) and not an issue to solve...

BTW:

Print 1 x,y,z, = 3 y 10

because class variable x = 3: int x=3
then local variable char y = 'y' is used and z changed to 10 z=10;

Print 2 x,y,z, = 3 z 25
because class variable x still untouched. in sub1: 3 is not >= 10 (passed z), so else branch:

    `c=15;` does not change passed `x` Java is `pass-by-value`
    `z=25;` changes class variable `z` to 25
    return 'z';

then local variable y now is 'z'

after sub2 you have:

class variable x = 2

 class variable y =-3

 class variable z = 25

 local variable y = 'y'

UPDATED:     class variable someValues [] = {2, -6, 3, -4, 3, -2};

then follow last loop to get Print 4,5 and 6 from someValues as:

`Print 4 2 -6`
`Print 5 3 -4`
`Print 6 3 -2`

good luck!


问:
How to access a vector inside a vector?
So I have a vector of vectors type double. I basically need to be able to set 360 numbers to cosY, and then put those 360 numbers into cosineY[0], then get another 360 numbers that are calculated with a different a now, and put them into cosineY[1].Technically my vector is going to be cosineYa I then need to be able to take out just cosY for a that I specify...

My code is saying this:

```<code>for (int a = 0; a < 8; a++)
{
   for int n=0; n <= 360; n++
   {
      cosY[n] = cos(a*vectorOfY[n]);
   }
   cosineY.push_back(cosY);
 }
</code>```

which I hope is the correct way of actually setting it.

But then I need to take cosY for a that I specify, and calculate another another 360 vector, which will be stored in another vector again as a vector of vectors.

Right now I've got:

```<code>for (int a = 0; a < 8; a++
{
    for (int n = 0; n <= 360; n++)
    {
       cosProductPt[n] = (VectorOfY[n]*cosY[n]);
    }
    CosProductY.push_back(cosProductPt);
 }
</code>```

The VectorOfY is besically the amplitude of an input wave. What I am doing is trying to create a cosine wave with different frequencies (a). I am then calculation the product of the input and cosine wave at each frequency. I need to be able to access these 360 points for each frequency later on in the program, and right now also I need to calculate the addition of all elements in cosProductPt, for every frequency (stored in cosProductY), and store it in a vector dotProductCos[a].

I've been trying to work it out but I don't know how to access all the elements in a vector of vectors to add them. I've been trying to do this for the whole day without any results. Right now I know so little that I don't even know how I would display or access a vector inside a vector, but I need to use that access point for the addition.

Thank you for your help.

答:
```<code>for (int a = 0; a < 8; a++)
{
   for int n=0; n < 360; n++) // note traded in <= for <. I think you had an off by one
                              // error here.
   {
      cosY[n] = cos(a*vectorOfY[n]);
   }
   cosineY.push_back(cosY);
 }
</code>```

Is sound so long as cosY has been pre-allocated to contain at least 360 elements. You could

```<code>std::vector<std::vector<double>> cosineY;
std::vector<double> cosY(360); // strongly consider replacing the 360 with a well-named
                               // constant
for (int a = 0; a < 8; a++) // same with that 8
{
   for int n=0; n < 360; n++)
   {
      cosY[n] = cos(a*vectorOfY[n]);
   }
   cosineY.push_back(cosY);
 }
</code>```

for example, but this hangs on to cosY longer than you need to and could cause problems later, so I'd probably scope cosY by throwing the above code into a function.

```<code>std::vector<std::vector<double>> buildStageOne(std::vector<double> &vectorOfY)
{
    std::vector<std::vector<double>> cosineY;
    std::vector<double> cosY(NumDegrees);
    for (int a = 0; a < NumVectors; a++)
    {
       for int n=0; n < NumDegrees; n++)
       {
          cosY[n] = cos(a*vectorOfY[n]); // take radians into account if needed.
       }
       cosineY.push_back(cosY);
     }
    return cosineY;
}
</code>```

This looks horrible, returning the vector by value, but the vast majority of compilers will take advantage of Copy Elision or some other sneaky optimization to eliminate the copying.

Then I'd do almost the exact same thing for the second step.

```<code>std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
                                               std::vector<std::vector<double>> &cosineY)
{
    std::vector<std::vector<double>> CosProductY;
    for (int a = 0; a < numVectors; a++)
    {
        for (int n = 0; n < NumDegrees; n++)
        {
           cosProductPt[n] = (VectorOfY[n]*cosineY[a][n]);
        }
        CosProductY.push_back(cosProductPt);
     }
    return CosProductY;
}
</code>```

But we can make a couple optimizations

```<code>std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
                                               std::vector<std::vector<double>> &cosineY)
{
    std::vector<std::vector<double>> CosProductY;
    for (int a = 0; a < numVectors; a++)
    {
        // why risk constantly looking up cosineY[a]? grab it once and cache it
        std::vector<double> & cosY = cosineY[a]; // note the reference
        for (int n = 0; n < numDegrees; n++)
        {
           cosProductPt[n] = (VectorOfY[n]*cosY[n]);
        }
        CosProductY.push_back(cosProductPt);
     }
    return CosProductY;
}
</code>```

And the next is kind of an extension of the first:

```<code>std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
                                               std::vector<std::vector<double>> &cosineY)
{
    std::vector<std::vector<double>> CosProductY;
    std::vector<double> cosProductPt(360);

    for (std::vector<double> & cosY: cosineY) // range based for. Gets rid of
    {
        for (int n = 0; n < NumDegrees; n++)
        {
           cosProductPt[n] = (VectorOfY[n]*cosY[n]);
        }
        CosProductY.push_back(cosProductPt);
     }
    return CosProductY;
}
</code>```

We could do the same range-based for trick for the for (int n = 0; n < NumDegrees; n++), but since we are iterating multiple arrays here it's not all that helpful.

Title: How to access a vector inside a vector?

Body:
So I have a vector of vectors type double. I basically need to be able to set 360 numbers to cosY, and then put those 360 numbers into cosineY[0], then get another 360 numbers that are calculated with a different a now, and put them into cosineY[1].Technically my vector is going to be cosineYa I then need to be able to take out just cosY for a that I specify...

My code is saying this:

for (int a = 0; a < 8; a++)
{
   for int n=0; n <= 360; n++
   {
      cosY[n] = cos(a*vectorOfY[n]);
   }
   cosineY.push_back(cosY);
 }

which I hope is the correct way of actually setting it.

But then I need to take cosY for a that I specify, and calculate another another 360 vector, which will be stored in another vector again as a vector of vectors.

Right now I've got:

for (int a = 0; a < 8; a++
{
    for (int n = 0; n <= 360; n++)
    {
       cosProductPt[n] = (VectorOfY[n]*cosY[n]);
    }
    CosProductY.push_back(cosProductPt);
 }

The VectorOfY is besically the amplitude of an input wave. What I am doing is trying to create a cosine wave with different frequencies (a). I am then calculation the product of the input and cosine wave at each frequency. I need to be able to access these 360 points for each frequency later on in the program, and right now also I need to calculate the addition of all elements in cosProductPt, for every frequency (stored in cosProductY), and store it in a vector dotProductCos[a].

I've been trying to work it out but I don't know how to access all the elements in a vector of vectors to add them. I've been trying to do this for the whole day without any results. Right now I know so little that I don't even know how I would display or access a vector inside a vector, but I need to use that access point for the addition.

Thank you for your help.

Body:
for (int a = 0; a < 8; a++)
{
   for int n=0; n < 360; n++) // note traded in <= for <. I think you had an off by one
                              // error here.
   {
      cosY[n] = cos(a*vectorOfY[n]);
   }
   cosineY.push_back(cosY);
 }

Is sound so long as cosY has been pre-allocated to contain at least 360 elements. You could

std::vector<std::vector<double>> cosineY;
std::vector<double> cosY(360); // strongly consider replacing the 360 with a well-named
                               // constant
for (int a = 0; a < 8; a++) // same with that 8
{
   for int n=0; n < 360; n++)
   {
      cosY[n] = cos(a*vectorOfY[n]);
   }
   cosineY.push_back(cosY);
 }

for example, but this hangs on to cosY longer than you need to and could cause problems later, so I'd probably scope cosY by throwing the above code into a function.

std::vector<std::vector<double>> buildStageOne(std::vector<double> &vectorOfY)
{
    std::vector<std::vector<double>> cosineY;
    std::vector<double> cosY(NumDegrees);
    for (int a = 0; a < NumVectors; a++)
    {
       for int n=0; n < NumDegrees; n++)
       {
          cosY[n] = cos(a*vectorOfY[n]); // take radians into account if needed.
       }
       cosineY.push_back(cosY);
     }
    return cosineY;
}

This looks horrible, returning the vector by value, but the vast majority of compilers will take advantage of Copy Elision or some other sneaky optimization to eliminate the copying.

Then I'd do almost the exact same thing for the second step.

std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
                                               std::vector<std::vector<double>> &cosineY)
{
    std::vector<std::vector<double>> CosProductY;
    for (int a = 0; a < numVectors; a++)
    {
        for (int n = 0; n < NumDegrees; n++)
        {
           cosProductPt[n] = (VectorOfY[n]*cosineY[a][n]);
        }
        CosProductY.push_back(cosProductPt);
     }
    return CosProductY;
}

But we can make a couple optimizations

std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
                                               std::vector<std::vector<double>> &cosineY)
{
    std::vector<std::vector<double>> CosProductY;
    for (int a = 0; a < numVectors; a++)
    {
        // why risk constantly looking up cosineY[a]? grab it once and cache it
        std::vector<double> & cosY = cosineY[a]; // note the reference
        for (int n = 0; n < numDegrees; n++)
        {
           cosProductPt[n] = (VectorOfY[n]*cosY[n]);
        }
        CosProductY.push_back(cosProductPt);
     }
    return CosProductY;
}

And the next is kind of an extension of the first:

std::vector<std::vector<double>> buildStageTwo(std::vector<double> &vectorOfY,
                                               std::vector<std::vector<double>> &cosineY)
{
    std::vector<std::vector<double>> CosProductY;
    std::vector<double> cosProductPt(360);

    for (std::vector<double> & cosY: cosineY) // range based for. Gets rid of
    {
        for (int n = 0; n < NumDegrees; n++)
        {
           cosProductPt[n] = (VectorOfY[n]*cosY[n]);
        }
        CosProductY.push_back(cosProductPt);
     }
    return CosProductY;
}

We could do the same range-based for trick for the for (int n = 0; n < NumDegrees; n++), but since we are iterating multiple arrays here it's not all that helpful.


问:
Building triangle with nested loops
I'm trying to build a triangle using nested loops.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);```

I expected that each row is more than the last by only one "#" like this:

But this is the result I got:

答:
Try code below:

```<code>function generatePyramid() {
    var totalNumberofRows = 7;
    var output="";
    for (var i = 1; i <= totalNumberofRows; i++) {
        for (var j = 1; j <= i; j++) {
            output+= "#  ";
        }
        print(output);
        output="";
    }
}
generatePyramid();
</code>```

How it works: http://rextester.com/ULY85622

Title: Building triangle with nested loops

Body:
I'm trying to build a triangle using nested loops.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);

I expected that each row is more than the last by only one "#" like this:

But this is the result I got:

Body:
Try code below:

function generatePyramid() {
    var totalNumberofRows = 7;
    var output="";
    for (var i = 1; i <= totalNumberofRows; i++) {
        for (var j = 1; j <= i; j++) {
            output+= "#  ";
        }
        print(output);
        output="";
    }
}
generatePyramid();

How it works: http://rextester.com/ULY85622


问:
Groovy oneliner not able to print environment variable
I am trying this groovy one-line its not working. Any idea how to make this work?

```<code>groovy -e 'def env=System.getenv();println( env['HOME'])'

Caught: groovy.lang.MissingPropertyException: No such property: HOME for class: script_from_command_line
groovy.lang.MissingPropertyException: No such property: HOME for class: script_from_command_line
        at script_from_command_line.run(script_from_command_line:1)
</code>```

Thanks
SR

答:
```<code>groovy -e "def env=System.getenv();println( env['HOME'])"
</code>```

just use different quotes for string and for whole command

other ways

```<code>groovy -e "def env=System.getenv();println( env.HOME )"
groovy -e "println System.getenv().HOME"
groovy -e "println(System.env.HOME)"
</code>```

Body:
I am trying this groovy one-line its not working. Any idea how to make this work?

groovy -e 'def env=System.getenv();println( env['HOME'])'

Caught: groovy.lang.MissingPropertyException: No such property: HOME for class: script_from_command_line
groovy.lang.MissingPropertyException: No such property: HOME for class: script_from_command_line
        at script_from_command_line.run(script_from_command_line:1)

Thanks
SR

Body:
groovy -e "def env=System.getenv();println( env['HOME'])"

just use different quotes for string and for whole command

other ways

groovy -e "def env=System.getenv();println( env.HOME )"
groovy -e "println System.getenv().HOME"
groovy -e "println(System.env.HOME)"


问:
managing CORS with fetch API GET request
I have an end point at localhost:8080/enquiry

which renders the following JSON:

```<code>[{"_id":"5a283e4c5a36f4556af34742",
   "firstName":"bob",
   "surname":"hoskins",
   "telephoneNumber":939483948,
   "gender":"male",
   "dayOfBirth":17,
   "monthOfBirth":5,
   "yearOfBirth":1978,"comments":"hello",
   "emailAddress":"jimmsrrs@gmail.com",
   "createdAt":"2017-12-06T19:00:28.401Z"}]
</code>```

I have an action creator that looks like this

```<code>export const receiveEnquiries = enquiries => ({
    type: RECEIVE_ENQUIRIES,
    enquiries

  });
export const fetchEnquiries = () => dispatch => (
    enquiryAPIUtil
        .fetchEnquiries() // this is the fetch call in api.js below
        .then((enquiries) => {dispatch(receiveEnquiries(enquiries))})
    );
</code>```

I have a fetch request that looks like this in api.js :

```<code>export const fetchEnquiries = () =>
    fetch(`${api}/enquiry`, { headers })
    .then(res => {
        res.json()
        console.log("res",res)
    })
    .then(data => console.log("data",data))
</code>```

In the console instead of logging the JSON above it logs the following:

```<code>res Response {type: "cors", url: "http://localhost:8080/enquiry",
redirected: false, status: 200, ok: true, …}
</code>```

In the express server.js I have

```<code> const cors = require('cors')
 app.use(cors())
</code>```

(As well as the code that renders the JSON)

Im wondering if it is more likely that I am doing something wrong on the client side of server side?

答:
res.json() returns a promise of an object parsed from JSON.

You ignore its returned object, so you don't get any JSON.

Body:
I have an end point at localhost:8080/enquiry

which renders the following JSON:

[{"_id":"5a283e4c5a36f4556af34742",
   "firstName":"bob",
   "surname":"hoskins",
   "telephoneNumber":939483948,
   "gender":"male",
   "dayOfBirth":17,
   "monthOfBirth":5,
   "yearOfBirth":1978,"comments":"hello",
   "emailAddress":"jimmsrrs@gmail.com",
   "createdAt":"2017-12-06T19:00:28.401Z"}]

I have an action creator that looks like this

export const receiveEnquiries = enquiries => ({
    type: RECEIVE_ENQUIRIES,
    enquiries

  });
export const fetchEnquiries = () => dispatch => (
    enquiryAPIUtil
        .fetchEnquiries() // this is the fetch call in api.js below
        .then((enquiries) => {dispatch(receiveEnquiries(enquiries))})
    );

I have a fetch request that looks like this in api.js :

export const fetchEnquiries = () =>
    fetch(`${api}/enquiry`, { headers })
    .then(res => {
        res.json()
        console.log("res",res)
    })
    .then(data => console.log("data",data))

In the console instead of logging the JSON above it logs the following:

res Response {type: "cors", url: "http://localhost:8080/enquiry",
redirected: false, status: 200, ok: true, …}

In the express server.js I have

 const cors = require('cors')
 app.use(cors())

(As well as the code that renders the JSON)

Im wondering if it is more likely that I am doing something wrong on the client side of server side?


问:
numpy.memap, Pandas dataframe and seaborn boxplot Troubles
I'm running an analysis over several large datasets (in total much bigger than my RAM).
To facilitate my work, I load the datasets using numpy.memmap (after having saved them to individual .npy files generated from tomographic datasets).

After extracting several values from the datasets I collect these values in a Pandas dataframe.
The values show up nicely when I look at them (for example via df.head()).

I would now like to visualize the values with something like seaborn.boxplot(data=df, x='Treatment', y='Tumor_Vol', hue='Experiment_Day'), but I get the error that

```<code>ValueError: List of boxplot statistics and `positions` values must have same the length
</code>```

It seems to me that this is due to the memory-mapped values, since the exact same command works when I save the dataframe to a CSV file and load it back from disk (which is my current workaround).

So---for lack of better words---is there a way I can un-memorymap values and save them as 'real' values to a dataframe?

答:
I have been running into the same kind of very weird bug. This shows up only on a jupyter notebook though.

I have a simple dataframe which is plotted okay with swarmplot but not with boxplot (on a notebook but the same code works on the terminal). It very weird because some other dataframe are plotted fine with the same code.

My dataframe:

```<code>    sample  color   right-left  (right-left)/right
0   OPAR19_r1c3     Blue    1   0.000334448
1   OPAR19_r1c3     Green   305     0.255444
2   OPAR19_r1c3     Red     15  0.0205479
3   OPAR19_r2c6     Blue    82  0.028063
4   OPAR19_r2c6     Green   260     0.216847
5   OPAR19_r2c6     Red     14  0.0183246
6   OPAR19_r1c1     Blue    75  0.0251931
7   OPAR19_r1c1     Green   -13     -0.0143488
8   OPAR19_r1c1     Red     10  0.0137741
9   OPAR19_r1c4     Blue    -38     -0.0131579
10  OPAR19_r1c4     Green   117     0.110169
11  OPAR19_r1c4     Red     0   0
12  OPAR19_r1c6     Blue    7   0.00239153
13  OPAR19_r1c6     Green   -3  -0.00295858
14  OPAR19_r1c6     Red     -46     -0.0640669
15  OPAR19_r2c4     Blue    95  0.0315824
16  OPAR19_r2c4     Green   191     0.163668
17  OPAR19_r2c4     Red     36  0.0447761
18  OPAR19_r2c5     Blue    48  0.0164215
19  OPAR19_r2c5     Green   165     0.154639
20  OPAR19_r2c5     Red     -4  -0.00542005
21  OPAR19_r1c5     Blue    199     0.0655468
22  OPAR19_r1c5     Green   262     0.223169
23  OPAR19_r1c5     Red     103     0.141678
24  OPAR19_r1c2     Blue    102     0.0340681
25  OPAR19_r1c2     Green   198     0.179837
26  OPAR19_r1c2     Red     75  0.0955414
27  OPAR19_r2c1     Blue    221     0.0742857
28  OPAR19_r2c1     Green   99  0.108791
29  OPAR19_r2c1     Red     11  0.0147453
30  OPAR19_r2c2     Blue    159     0.0526664
31  OPAR19_r2c2     Green   64  0.0724802
32  OPAR19_r2c2     Red     -21     -0.0276316
33  OPAR19_r2c3     Blue    16  0.00536733
34  OPAR19_r2c3     Green   84  0.0769936
35  OPAR19_r2c3     Red     -49     -0.0639687
</code>```

This plot fails on the notebook but not on a python file

```<code>sns.boxplot(data=df_out2,x='color',y='right-left')
</code>```

here is the error:

```<code>ValueError: List of boxplot statistics and `positions` values must have same the length
</code>```

While the equivalent plot with swarmplot or stripplot works fine:

```<code>sns.swarmplot(data=df_out2,x='color',y='right-left')
</code>```

Body:
I'm running an analysis over several large datasets (in total much bigger than my RAM).
To facilitate my work, I load the datasets using numpy.memmap (after having saved them to individual .npy files generated from tomographic datasets).

After extracting several values from the datasets I collect these values in a Pandas dataframe.
The values show up nicely when I look at them (for example via df.head()).

I would now like to visualize the values with something like seaborn.boxplot(data=df, x='Treatment', y='Tumor_Vol', hue='Experiment_Day'), but I get the error that

ValueError: List of boxplot statistics and `positions` values must have same the length

It seems to me that this is due to the memory-mapped values, since the exact same command works when I save the dataframe to a CSV file and load it back from disk (which is my current workaround).

So---for lack of better words---is there a way I can un-memorymap values and save them as 'real' values to a dataframe?

Body:
I have been running into the same kind of very weird bug. This shows up only on a jupyter notebook though.

I have a simple dataframe which is plotted okay with swarmplot but not with boxplot (on a notebook but the same code works on the terminal). It very weird because some other dataframe are plotted fine with the same code.

My dataframe:

    sample  color   right-left  (right-left)/right
0   OPAR19_r1c3     Blue    1   0.000334448
1   OPAR19_r1c3     Green   305     0.255444
2   OPAR19_r1c3     Red     15  0.0205479
3   OPAR19_r2c6     Blue    82  0.028063
4   OPAR19_r2c6     Green   260     0.216847
5   OPAR19_r2c6     Red     14  0.0183246
6   OPAR19_r1c1     Blue    75  0.0251931
7   OPAR19_r1c1     Green   -13     -0.0143488
8   OPAR19_r1c1     Red     10  0.0137741
9   OPAR19_r1c4     Blue    -38     -0.0131579
10  OPAR19_r1c4     Green   117     0.110169
11  OPAR19_r1c4     Red     0   0
12  OPAR19_r1c6     Blue    7   0.00239153
13  OPAR19_r1c6     Green   -3  -0.00295858
14  OPAR19_r1c6     Red     -46     -0.0640669
15  OPAR19_r2c4     Blue    95  0.0315824
16  OPAR19_r2c4     Green   191     0.163668
17  OPAR19_r2c4     Red     36  0.0447761
18  OPAR19_r2c5     Blue    48  0.0164215
19  OPAR19_r2c5     Green   165     0.154639
20  OPAR19_r2c5     Red     -4  -0.00542005
21  OPAR19_r1c5     Blue    199     0.0655468
22  OPAR19_r1c5     Green   262     0.223169
23  OPAR19_r1c5     Red     103     0.141678
24  OPAR19_r1c2     Blue    102     0.0340681
25  OPAR19_r1c2     Green   198     0.179837
26  OPAR19_r1c2     Red     75  0.0955414
27  OPAR19_r2c1     Blue    221     0.0742857
28  OPAR19_r2c1     Green   99  0.108791
29  OPAR19_r2c1     Red     11  0.0147453
30  OPAR19_r2c2     Blue    159     0.0526664
31  OPAR19_r2c2     Green   64  0.0724802
32  OPAR19_r2c2     Red     -21     -0.0276316
33  OPAR19_r2c3     Blue    16  0.00536733
34  OPAR19_r2c3     Green   84  0.0769936
35  OPAR19_r2c3     Red     -49     -0.0639687

This plot fails on the notebook but not on a python file

sns.boxplot(data=df_out2,x='color',y='right-left')

here is the error:

ValueError: List of boxplot statistics and `positions` values must have same the length

While the equivalent plot with swarmplot or stripplot works fine:

sns.swarmplot(data=df_out2,x='color',y='right-left')


问:
Invoke of ListView runs sub twice
I have been running the following code for a couple days fine but after doing some debugging yesterday I found out that the Sub has been firing twice.  Some background - This is a postage app that ships all of our packages. I neede to add a listview to the main form to show various rates that are returned from Easypost. When I first add the listview the app ran great from debug but after a compile it would completely hang after the list view was populated. So after a couple days of searching I added the invoke method which allowed the app GUI to continue after the listview was populated. So first I see if rates are returned and see that when it hits the lvRates.InvokeRequired it does the invoke and and then does the EasyPostGetServices a 2nd time which waste resources and creates to shipments at easypost loading the 2nd rates returned.

```<code>Private Sub GetEasyPostServices()

    EasyPostGetServices(dictEPFromAddress, dictEPToAddress, dictEPPackage)

    If EasyPostShipment.rates.Count > 0 Then
        If lvRates.InvokeRequired Then
            lvRates.Invoke(New MethodInvoker(AddressOf GetEasyPostServices))
        Else
            For Each rate As Rate In EasyPostShipment.rates
                lvRates.Items.Add(New ListViewItem({rate.carrier, rate.rate, UCase(rate.service), rate.id}))
            Next
        End If

    Else
        MsgBox("Based on your inputs or preferences, no shipping services were available. Shipping services shown ignore your preferences. If none are shown, there are no shipping services available for this order.")
    End If
End Sub
</code>```

My question is why is the code running twice and how do I prevent it from happening. I have moved the invoke around but everything else I try the GUI freezes when run from exe.

答:
This was based on your original question. I've added a BackgroundWorker in a button click to cause GetEasyPostServices to start running on a non-UI thread. The crux here is how to properly invoke UI calls. The three methods at the bottom demonstrate that.

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' this method is running on the UI thread as it handles a UI event
    Dim bw As New System.ComponentModel.BackgroundWorker()
    AddHandler bw.DoWork, New System.ComponentModel.DoWorkEventHandler(Sub(oo, ee) GetEasyPostServices())
    ' this call causes GetEasyPostServices to run on a non-UI thread
    bw.RunWorkerAsync()
End Sub

Private Sub GetEasyPostServices()
    ' running on a non-UI thread. Any UI calls must be invoked
    Cursor.Current = Cursors.WaitCursor
    Try
        Dim frAddress As New Dictionary(Of String, Object)() From {
            {"street1", "12345 Hill Dr"},
            {"street2", ""},
            {"city", "sometown"}}

        Dim toAddress As New Dictionary(Of String, Object)() From {
            {"street1", sAdd1},
            {"city", sCity},
            {"state", sRegion},
            {"verifications", New List(Of String)() From {"delivery"}}}

        Dim package As New Dictionary(Of String, Object)
        If GlobalVariables.giLength > 0 Then
            package.Add("length", GlobalVariables.giLength.ToString)
            package.Add("width", GlobalVariables.giWidth.ToString)
            package.Add("height", GlobalVariables.giHeight.ToString)
            package.Add("weight", (sLbs * 16) + sOz)
        End If

        EasyPostGetServices(frAddress, toAddress, package)

        If EasyPostShipment.rates.Count > 0 Then
            ' hide the UI invocation logic in methods
            updateListView()
        Else
            MsgBox("Based on your inputs or preferences, no shipping services were available. Shipping services shown ignore your preferences. If none are shown, there are no shipping services available for this order.")
            clearAndFocusTbOrder()
        End If
    Finally
        Cursor.Current = Cursors.Default
    End Try
End Sub

' these methods manage their own UI invocation.

Private Sub updateListView()
    If lvRates.InvokeRequired Then
        lvRates.Invoke(New Action(AddressOf updateListView))
    Else
        lvRates.Visible = True
        lvRates.Items.Clear()
        For Each rate As Rate In EasyPostShipment.rates
            lvRates.Items.Add(New ListViewItem({rate.carrier, rate.rate, UCase(rate.service), rate.id}))
        Next
        SortListView()
        lvRates.Items(0).Selected = True
        Button1.Visible = True
    End If
End Sub

Private Sub SortListView()
    If lvRates.InvokeRequired Then
        lvRates.Invoke(New Action(AddressOf SortListView))
    Else
        lvRates.Sort()
    End If
End Sub

Private Sub clearAndFocusTbOrder()
    If tbOrderID.InvokeRequired Then
        tbOrderID.Invoke(New Action(AddressOf clearAndFocusTbOrder))
    Else
        tbOrderID.Clear()
        tbOrderID.Focus()
    End If
End Sub
</code>```

It's all about what, where, and why you invoke. In your example it wasn't clear if GetEasyPostServices started on the UI or not. I caused it not to so I could demonstrate how to properly invoke the UI calls. You then would need to invoke UI calls because it's not currently on the UI thread. That's the "why".

Also, it's key to run a minimal amount of code on the UI thread to prevent unnecessary processing and hanging the UI thread. Your original configuration ran all your code once, then ran it all again, on the UI thread.

Title: Invoke of ListView runs sub twice

Body:
I have been running the following code for a couple days fine but after doing some debugging yesterday I found out that the Sub has been firing twice.  Some background - This is a postage app that ships all of our packages. I neede to add a listview to the main form to show various rates that are returned from Easypost. When I first add the listview the app ran great from debug but after a compile it would completely hang after the list view was populated. So after a couple days of searching I added the invoke method which allowed the app GUI to continue after the listview was populated. So first I see if rates are returned and see that when it hits the lvRates.InvokeRequired it does the invoke and and then does the EasyPostGetServices a 2nd time which waste resources and creates to shipments at easypost loading the 2nd rates returned.

Private Sub GetEasyPostServices()

    EasyPostGetServices(dictEPFromAddress, dictEPToAddress, dictEPPackage)

    If EasyPostShipment.rates.Count > 0 Then
        If lvRates.InvokeRequired Then
            lvRates.Invoke(New MethodInvoker(AddressOf GetEasyPostServices))
        Else
            For Each rate As Rate In EasyPostShipment.rates
                lvRates.Items.Add(New ListViewItem({rate.carrier, rate.rate, UCase(rate.service), rate.id}))
            Next
        End If

    Else
        MsgBox("Based on your inputs or preferences, no shipping services were available. Shipping services shown ignore your preferences. If none are shown, there are no shipping services available for this order.")
    End If
End Sub

My question is why is the code running twice and how do I prevent it from happening. I have moved the invoke around but everything else I try the GUI freezes when run from exe.

Body:
This was based on your original question. I've added a BackgroundWorker in a button click to cause GetEasyPostServices to start running on a non-UI thread. The crux here is how to properly invoke UI calls. The three methods at the bottom demonstrate that.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' this method is running on the UI thread as it handles a UI event
    Dim bw As New System.ComponentModel.BackgroundWorker()
    AddHandler bw.DoWork, New System.ComponentModel.DoWorkEventHandler(Sub(oo, ee) GetEasyPostServices())
    ' this call causes GetEasyPostServices to run on a non-UI thread
    bw.RunWorkerAsync()
End Sub

Private Sub GetEasyPostServices()
    ' running on a non-UI thread. Any UI calls must be invoked
    Cursor.Current = Cursors.WaitCursor
    Try
        Dim frAddress As New Dictionary(Of String, Object)() From {
            {"street1", "12345 Hill Dr"},
            {"street2", ""},
            {"city", "sometown"}}

        Dim toAddress As New Dictionary(Of String, Object)() From {
            {"street1", sAdd1},
            {"city", sCity},
            {"state", sRegion},
            {"verifications", New List(Of String)() From {"delivery"}}}

        Dim package As New Dictionary(Of String, Object)
        If GlobalVariables.giLength > 0 Then
            package.Add("length", GlobalVariables.giLength.ToString)
            package.Add("width", GlobalVariables.giWidth.ToString)
            package.Add("height", GlobalVariables.giHeight.ToString)
            package.Add("weight", (sLbs * 16) + sOz)
        End If

        EasyPostGetServices(frAddress, toAddress, package)

        If EasyPostShipment.rates.Count > 0 Then
            ' hide the UI invocation logic in methods
            updateListView()
        Else
            MsgBox("Based on your inputs or preferences, no shipping services were available. Shipping services shown ignore your preferences. If none are shown, there are no shipping services available for this order.")
            clearAndFocusTbOrder()
        End If
    Finally
        Cursor.Current = Cursors.Default
    End Try
End Sub

' these methods manage their own UI invocation.

Private Sub updateListView()
    If lvRates.InvokeRequired Then
        lvRates.Invoke(New Action(AddressOf updateListView))
    Else
        lvRates.Visible = True
        lvRates.Items.Clear()
        For Each rate As Rate In EasyPostShipment.rates
            lvRates.Items.Add(New ListViewItem({rate.carrier, rate.rate, UCase(rate.service), rate.id}))
        Next
        SortListView()
        lvRates.Items(0).Selected = True
        Button1.Visible = True
    End If
End Sub

Private Sub SortListView()
    If lvRates.InvokeRequired Then
        lvRates.Invoke(New Action(AddressOf SortListView))
    Else
        lvRates.Sort()
    End If
End Sub

Private Sub clearAndFocusTbOrder()
    If tbOrderID.InvokeRequired Then
        tbOrderID.Invoke(New Action(AddressOf clearAndFocusTbOrder))
    Else
        tbOrderID.Clear()
        tbOrderID.Focus()
    End If
End Sub

It's all about what, where, and why you invoke. In your example it wasn't clear if GetEasyPostServices started on the UI or not. I caused it not to so I could demonstrate how to properly invoke the UI calls. You then would need to invoke UI calls because it's not currently on the UI thread. That's the "why".

Also, it's key to run a minimal amount of code on the UI thread to prevent unnecessary processing and hanging the UI thread. Your original configuration ran all your code once, then ran it all again, on the UI thread.


问:
What are the main purposes of std::forward and which problems does it solve?
In perfect forwarding, std::forward is used to convert the named rvalue references t1 and t2 to unnamed rvalue references. What is the purpose of doing that? How would that affect the called function inner if we leave t1 & t2 as lvalues?

```<code>template <typename T1, typename T2>
void outer(T1&& t1, T2&& t2)
{
    inner(std::forward<T1>(t1), std::forward<T2>(t2));
}
</code>```

答:
It may be worthwhile to emphasize that forward has to be used in tandem with an outer method with forwarding/universal reference. Using forward by itself as the following statements is allowed, but does no good other than causing confusion. The standard committee may want to disable such flexibility otherwise why don't we just use static_cast instead?

```<code>     std::forward<int>(1);
     std::forward<std::string>("Hello");
</code>```

In my opinion, move and forward are design patterns which are natural outcomes after r-value reference type is introduced. We should not name a method assuming it is correctly used unless incorrect usage is forbidden.

ContentLicense: CC BY-SA 4.0

Body:
In perfect forwarding, std::forward is used to convert the named rvalue references t1 and t2 to unnamed rvalue references. What is the purpose of doing that? How would that affect the called function inner if we leave t1 & t2 as lvalues?

template <typename T1, typename T2>
void outer(T1&& t1, T2&& t2)
{
    inner(std::forward<T1>(t1), std::forward<T2>(t2));
}

Body:
It may be worthwhile to emphasize that forward has to be used in tandem with an outer method with forwarding/universal reference. Using forward by itself as the following statements is allowed, but does no good other than causing confusion. The standard committee may want to disable such flexibility otherwise why don't we just use static_cast instead?

     std::forward<int>(1);
     std::forward<std::string>("Hello");

In my opinion, move and forward are design patterns which are natural outcomes after r-value reference type is introduced. We should not name a method assuming it is correctly used unless incorrect usage is forbidden.


问:
Programmatically generate new sinks based on database entries
I'm building a small app that models city public transport network. The idea is that each bus stop is a Sink and listens to messages from other bus stops, thus, calculating times the bus will show up.
Bus stops with unique ids are stored in the database and I need to generate and run exactly the number of sinks with unique ids. How do I do that?

My guess is that the task that can be done using Spring Cloud Data Flow that will launch .jar files using (--id) property that'll be injected with @Value notation. But I can't understand how to implement that.

Also found this but it didn't help.

答:
You got some of the concepts correctly, but your implementation may need some help.

So Spring Cloud Dataflow is an orchestration engine that deploys boot applications and connects them using a middleware.

Those apps can be Streaming apps, which mean they use Spring Cloud Stream as an abstraction layer to communicate with a middleware (Rabbit or Kafka), and in its core it has three types of apps: Sources (data emitters), Processors (data transformation) and sinks (data receivers)

You use dataflow to combine those and deploy to a runtime (Local, CloudFoundry, K8S, YARN)

So, yes SCDF can be used for your assignment, however you do not want to create one sink per bus, this is abusing your resources.

You can have a simple stream that captures the data from your buses (the source), maybe do some transformation and sinks it to a DB

You can then create a tap that listens to the messages stored in a DB if you are interested in processing them.

You can tap that information and have a client that broadcasts it downstream (your display at each bus stop)

So for example you can have just one single sink, but have a websocket for example where each client connects and passes an id. You can then forward the events received filtered by that id to this specific client.

This is a much more efficient way to deal with that.


问:
Numpy value error - the truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Edit: Question updated - I should have asked:

Why is this:

```<code>new_x = x[(0<x<10) & (20<x<40)]
</code>```

giving me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"?

The original question I posted did not reflect the problem I was having (apologies - my actual conditions are more complicated and I had oversimplified it). Original question below:

I have a numpy array x and I want to create a new array of x elements
  satisfying x>0 and x<10. I have tried all the following:

```<code>new_x = x[(x>0) and (x<10)]

new_x = x[(x>0) & (x<10)]

new_x = x[np.logical_and(x>0, x<10)]

new_x = x[np.where(x>0, x<10)]

new_x = x[np.all(x>0, x<10)]

new_x = x[np.all((x>0) and (x<10))]

new_x = x[np.all(x>0) and np.all(x<10)]

new_x = x[np.any(x>0, x<10)]
</code>```

and they all give the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have ran out of ideas. I realise this may be a duplicate question
  but I have consulted
  this
  and
  this
  and many others which did not help as I keep getting the same value
  error.

Edit: Fixed typo (x<0 and x>10) --> (x>0 and x<10)

Body:
Edit: Question updated - I should have asked:

Why is this:

new_x = x[(0<x<10) & (20<x<40)]

giving me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"?

The original question I posted did not reflect the problem I was having (apologies - my actual conditions are more complicated and I had oversimplified it). Original question below:

I have a numpy array x and I want to create a new array of x elements
  satisfying x>0 and x<10. I have tried all the following:

new_x = x[(x>0) and (x<10)]

new_x = x[(x>0) & (x<10)]

new_x = x[np.logical_and(x>0, x<10)]

new_x = x[np.where(x>0, x<10)]

new_x = x[np.all(x>0, x<10)]

new_x = x[np.all((x>0) and (x<10))]

new_x = x[np.all(x>0) and np.all(x<10)]

new_x = x[np.any(x>0, x<10)]

and they all give the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have ran out of ideas. I realise this may be a duplicate question
  but I have consulted
  this
  and
  this
  and many others which did not help as I keep getting the same value
  error.

Edit: Fixed typo (x<0 and x>10) --> (x>0 and x<10)

Body:
I'm confused with the logical statements.  How can a value be both less than 0 and greater than 10?

In [1]: import numpy as np

In [2]: x = np.arange(-10,20)

In [3]: x
Out[3]:
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
     3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,

In [5]: x[(x<0) & (x>10)]
Out[5]: array([], dtype=int64)

In [6]: x[(x<0) | (x>10)]
Out[6]:
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,  11,  12,  13,
    14,  15,  16,  17,  18,  19])


问:
Google Play <compatible-screens> blocking out Samsung devices when their resolution is changed
Recently we've had issues where users can't download our app from the Google Play store due to the message "Your device isn't compatible with this version", even though the device is listed as compatible on the device manager of the app release and the app used to be compatible.

We found this to only be happening with Samsung devices E.G. S7, S8 and S6 Edge+ when the screen resolution option is changed in the device settings.

Our manifest currently specifies the following screen support. This works for the Galaxy S7 in all screen resolutions but will not work on the S6 Edge with WQHD resolution, the Google Play store says "Your device isn't compatible with this version" until a different resolution is selected.

<compatible-screens>
  <screen android:screenSize="small" android:screenDensity="280" />
  <screen android:screenSize="small" android:screenDensity="xhdpi" />
  <screen android:screenSize="small" android:screenDensity="360" />
  <screen android:screenSize="small" android:screenDensity="420" />
  <screen android:screenSize="small" android:screenDensity="xxhdpi" />
  <screen android:screenSize="small" android:screenDensity="560" />
  <screen android:screenSize="small" android:screenDensity="xxxhdpi" />

  <screen android:screenSize="normal" android:screenDensity="ldpi" />
  <screen android:screenSize="normal" android:screenDensity="mdpi" />
  <screen android:screenSize="normal" android:screenDensity="hdpi" />
  <screen android:screenSize="normal" android:screenDensity="280" />
  <screen android:screenSize="normal" android:screenDensity="xhdpi" />
  <screen android:screenSize="normal" android:screenDensity="360" />
  <screen android:screenSize="normal" android:screenDensity="420" />
  <screen android:screenSize="normal" android:screenDensity="xxhdpi" />
  <screen android:screenSize="normal" android:screenDensity="xxxhdpi" />
  <screen android:screenSize="normal" android:screenDensity="480" />
  <screen android:screenSize="normal" android:screenDensity="560" />
  <screen android:screenSize="normal" android:screenDensity="640" />
</compatible-screens>```

Our app is designed for handsets only and must not be available to tablets until it is ready.

Has anyone else had these issues or know of a fix? We really can't support tablet at the moment, so removing the compatible screens declaration is not an option right now (we tried adding the require telephony tag, but then we'd still be supporting 500 tablets).

答:
The fragmentation in android devices is huge, i have seen that some users define <compatible-screens> in their apps, but sometimes when a new device is released with new density or the screen resolution is changed by the users, they can´t download the app from Google Play Store.

I used to set the definition of compatible-screens in my AndroidManifest.xml

```<code><!-- just handsets allowed -->
<compatible-screens>
  ...
  ...
  ...
</compatible-screens>
</code>```

but at the end to avoid the message "Your device isn't compatible with this version" and filtering from Google Play for certain devices, i have deleted the constraint <compatible-screens> from my AndroidManifest.xml in all my apps.

If you want to exclude only tablets, i used this configuration based on  this answer by Mark Murphy.

```<code><compatible-screens>
    <!-- all small size screens -->
    <screen android:screenSize="small" android:screenDensity="ldpi" />
    <screen android:screenSize="small" android:screenDensity="mdpi" />
    <screen android:screenSize="small" android:screenDensity="hdpi" />
    <screen android:screenSize="small" android:screenDensity="xhdpi" />
    <screen android:screenSize="small" android:screenDensity="xxhdpi" />
    <!-- all normal size screens -->
    <screen android:screenSize="normal" android:screenDensity="ldpi" />
    <screen android:screenSize="normal" android:screenDensity="mdpi" />
    <screen android:screenSize="normal" android:screenDensity="hdpi" />
    <screen android:screenSize="normal" android:screenDensity="xhdpi" />
    <screen android:screenSize="normal" android:screenDensity="xxhdpi" />
</compatible-screens>
</code>```

Body:
Recently we've had issues where users can't download our app from the Google Play store due to the message "Your device isn't compatible with this version", even though the device is listed as compatible on the device manager of the app release and the app used to be compatible.

We found this to only be happening with Samsung devices E.G. S7, S8 and S6 Edge+ when the screen resolution option is changed in the device settings.

Our manifest currently specifies the following screen support. This works for the Galaxy S7 in all screen resolutions but will not work on the S6 Edge with WQHD resolution, the Google Play store says "Your device isn't compatible with this version" until a different resolution is selected.

<compatible-screens>
  <screen android:screenSize="small" android:screenDensity="280" />
  <screen android:screenSize="small" android:screenDensity="xhdpi" />
  <screen android:screenSize="small" android:screenDensity="360" />
  <screen android:screenSize="small" android:screenDensity="420" />
  <screen android:screenSize="small" android:screenDensity="xxhdpi" />
  <screen android:screenSize="small" android:screenDensity="560" />
  <screen android:screenSize="small" android:screenDensity="xxxhdpi" />

  <screen android:screenSize="normal" android:screenDensity="ldpi" />
  <screen android:screenSize="normal" android:screenDensity="mdpi" />
  <screen android:screenSize="normal" android:screenDensity="hdpi" />
  <screen android:screenSize="normal" android:screenDensity="280" />
  <screen android:screenSize="normal" android:screenDensity="xhdpi" />
  <screen android:screenSize="normal" android:screenDensity="360" />
  <screen android:screenSize="normal" android:screenDensity="420" />
  <screen android:screenSize="normal" android:screenDensity="xxhdpi" />
  <screen android:screenSize="normal" android:screenDensity="xxxhdpi" />
  <screen android:screenSize="normal" android:screenDensity="480" />
  <screen android:screenSize="normal" android:screenDensity="560" />
  <screen android:screenSize="normal" android:screenDensity="640" />
</compatible-screens>

Our app is designed for handsets only and must not be available to tablets until it is ready.

Has anyone else had these issues or know of a fix? We really can't support tablet at the moment, so removing the compatible screens declaration is not an option right now (we tried adding the require telephony tag, but then we'd still be supporting 500 tablets).

Body:
The fragmentation in android devices is huge, i have seen that some users define <compatible-screens> in their apps, but sometimes when a new device is released with new density or the screen resolution is changed by the users, they can´t download the app from Google Play Store.

I used to set the definition of compatible-screens in my AndroidManifest.xml

<!-- just handsets allowed -->
<compatible-screens>
  ...
  ...
  ...
</compatible-screens>

but at the end to avoid the message "Your device isn't compatible with this version" and filtering from Google Play for certain devices, i have deleted the constraint <compatible-screens> from my AndroidManifest.xml in all my apps.

If you want to exclude only tablets, i used this configuration based on  this answer by Mark Murphy.

<compatible-screens>
    <!-- all small size screens -->
    <screen android:screenSize="small" android:screenDensity="ldpi" />
    <screen android:screenSize="small" android:screenDensity="mdpi" />
    <screen android:screenSize="small" android:screenDensity="hdpi" />
    <screen android:screenSize="small" android:screenDensity="xhdpi" />
    <screen android:screenSize="small" android:screenDensity="xxhdpi" />
    <!-- all normal size screens -->
    <screen android:screenSize="normal" android:screenDensity="ldpi" />
    <screen android:screenSize="normal" android:screenDensity="mdpi" />
    <screen android:screenSize="normal" android:screenDensity="hdpi" />
    <screen android:screenSize="normal" android:screenDensity="xhdpi" />
    <screen android:screenSize="normal" android:screenDensity="xxhdpi" />
</compatible-screens>


问:
How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?
Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page.  I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the .designer file.  I'm using Visual Studio 2008

EDIT: Sorry I should have noted I've already tried:

Closing & re-opening all the files & Visual Studio

Making a change to a runat="server" control on the page

Deleting & re-adding the page directive

答:
I recently saw that I was having the same problem.  Visual Studio 2010 was refusing to update the designer file.

As it turns out, VS doesn't modify the designer file for a page that uses CodeFile (run off of pages) instead of CodeBehind (DLL).  This is true no matter how many times you close VS, reload the project, re-create the control(s), or modify a file.  Nothing would prompt VS to regenerate the designer.  It's as if it doesn't create the designer file for CodeFile pages but does require it to be there.

I changed it to CodeBehind and saved the page.  The designer file updated immediately.  Then I just changed it back and everything was still golden.  This behavior seems to be new with VS 2010 / .NET 4.0 as VS 2008 by default didn't suffer from this.

It's this part:

```<code><%@ Page Language="vb" AutoEventWireup="false" CodeFile="YourPage.aspx.vb" Inherits="YourPageClass" %>
</code>```

Change CodeFile to CodeBehind, save, and then revert.

OwnerDisplayName: Glenn Slaven

ContentLicense: CC BY-SA 2.5

Body:
I recently saw that I was having the same problem.  Visual Studio 2010 was refusing to update the designer file.

As it turns out, VS doesn't modify the designer file for a page that uses CodeFile (run off of pages) instead of CodeBehind (DLL).  This is true no matter how many times you close VS, reload the project, re-create the control(s), or modify a file.  Nothing would prompt VS to regenerate the designer.  It's as if it doesn't create the designer file for CodeFile pages but does require it to be there.

I changed it to CodeBehind and saved the page.  The designer file updated immediately.  Then I just changed it back and everything was still golden.  This behavior seems to be new with VS 2010 / .NET 4.0 as VS 2008 by default didn't suffer from this.

It's this part:

<%@ Page Language="vb" AutoEventWireup="false" CodeFile="YourPage.aspx.vb" Inherits="YourPageClass" %>

Change CodeFile to CodeBehind, save, and then revert.


问:
Plotting 1D Time Series from 2D Hourly DataFrame
I'm trying to plot a year's worth of utility data downloaded from my utility provider. The data is provided in a matrix where each row is a different day (most recent at the top), and each column is an hour of the day (11:00 AM, 12:00 PM, 1:00 PM, etc). I'd like to transform this 2D DataFrame into a 1D Timeseries, then plot the series.

Using .stack() gets me close, but I can't seem to create a datetime from the date and time column after they are stacked. Also, when plotted it plots the hours correctly from left to right, but the dates descend from left to right. For example it plots the 25th (1am, 2am 3am, etc), 24th (1am, 2am, 3am, etc), 23rd (1am, 2am, 3am, etc). I'm sure this will fix itself after a true datetime is created.

The code below generates a small sample df, but in the real data set all 24 hours are columns and all dates of the year are rows.

```<code>df=pd.DataFrame({'Date':['06/25/17','06/24/17','06/23/17'], '12:00 AM':
[1,2,3],'1:00 AM':[4,5,6],'2:00 AM':[7,8,9],})
df.set_index(['Date'], inplace = True)
df
</code>```

The goal would be to have a series where the index is the time series and the utility usage is the data.

Thank you!

答:
I think you need to unstack your data frame, concatenate the columns Date and level_0 to make a time stamp. Then set the index to the timestamp and drop the extra columns.

```<code>df=pd.DataFrame({'Date':['06/25/17','06/24/17','06/23/17'], '12:00 AM':
[1,2,3],'1:00 AM':[4,5,6],'2:00 AM':[7,8,9],})
df.set_index(['Date'], inplace = True)

#Unstack and reset index
df = df.unstack().reset_index()

#concatenate timestamp and convert to datetime
df['Timestamp'] = df['Date'] + ' '+ df['level_0']
df['Timestamp'] = pd.to_datetime(df['Timestamp'],format="%m/%d/%y %I:%M %p")
df =df.sort_values(by='Timestamp')
df = df.set_index('Timestamp')

#drop extra columns
df = df.drop(['Date','level_0'],axis=1)
</code>```

returns df looking like:

```<code>                     0
Timestamp
2017-06-23 00:00:00  3
2017-06-23 01:00:00  6
2017-06-23 02:00:00  9
2017-06-24 00:00:00  2
2017-06-24 01:00:00  5
2017-06-24 02:00:00  8
2017-06-25 00:00:00  1
2017-06-25 01:00:00  4
2017-06-25 02:00:00  7
</code>```

You could then plot your time series with

```<code>df.plot()
</code>```

Yielding:

Body:
I'm trying to plot a year's worth of utility data downloaded from my utility provider. The data is provided in a matrix where each row is a different day (most recent at the top), and each column is an hour of the day (11:00 AM, 12:00 PM, 1:00 PM, etc). I'd like to transform this 2D DataFrame into a 1D Timeseries, then plot the series.

Using .stack() gets me close, but I can't seem to create a datetime from the date and time column after they are stacked. Also, when plotted it plots the hours correctly from left to right, but the dates descend from left to right. For example it plots the 25th (1am, 2am 3am, etc), 24th (1am, 2am, 3am, etc), 23rd (1am, 2am, 3am, etc). I'm sure this will fix itself after a true datetime is created.

The code below generates a small sample df, but in the real data set all 24 hours are columns and all dates of the year are rows.

df=pd.DataFrame({'Date':['06/25/17','06/24/17','06/23/17'], '12:00 AM':
[1,2,3],'1:00 AM':[4,5,6],'2:00 AM':[7,8,9],})
df.set_index(['Date'], inplace = True)
df

The goal would be to have a series where the index is the time series and the utility usage is the data.

Thank you!

Body:
I think you need to unstack your data frame, concatenate the columns Date and level_0 to make a time stamp. Then set the index to the timestamp and drop the extra columns.

df=pd.DataFrame({'Date':['06/25/17','06/24/17','06/23/17'], '12:00 AM':
[1,2,3],'1:00 AM':[4,5,6],'2:00 AM':[7,8,9],})
df.set_index(['Date'], inplace = True)

#Unstack and reset index
df = df.unstack().reset_index()

#concatenate timestamp and convert to datetime
df['Timestamp'] = df['Date'] + ' '+ df['level_0']
df['Timestamp'] = pd.to_datetime(df['Timestamp'],format="%m/%d/%y %I:%M %p")
df =df.sort_values(by='Timestamp')
df = df.set_index('Timestamp')

#drop extra columns
df = df.drop(['Date','level_0'],axis=1)

returns df looking like:

                     0
Timestamp
2017-06-23 00:00:00  3
2017-06-23 01:00:00  6
2017-06-23 02:00:00  9
2017-06-24 00:00:00  2
2017-06-24 01:00:00  5
2017-06-24 02:00:00  8
2017-06-25 00:00:00  1
2017-06-25 01:00:00  4
2017-06-25 02:00:00  7

You could then plot your time series with

df.plot()

Yielding:


问:
Two output file names resolved to the same output path migration.init in mvc
I am working in MVC and running with this problem "Two output file names resolved to the same output path '..\migration.init.resources'"
At first i run this command "Enable-Migrations" successfully after making changes in code i  run "Add-Migration init" in console an error occur " project failed to build" with "Two output file names resolved to the same output path '..\migration.init.resources'"

I have deleted all migration.resouces files from obj folder, unload, reload and also restart the project but all goes with same error

答:
I faced the same issue and solved :

1. Delete the Migrations Folder

2. Delete the line of code which uses Migrations.Configuration Namespace in Global.asax.cs file

3. Use Code First Migration to generate the new Migrations file and Folder.


问:
Installing bootstrap 3 with meteor
I've read a lot of posts about how bootstrap can be included in your meteor project and more recently, I've seen people using

```<code>meteor add mizzao:bootstrap-3
</code>```

like in this anwser.

The thing is when I try to do it I get the following error :

```<code>mizzao:bootstrap-3: no such package
</code>```

Is there another version I need to use or is there another way to add bootstrap 3 to a meteor project.

答:
I actually set up mizzao:bootstrap-3 a long time ago, but this was for a much older version of Meteor.

Starting from Meteor 1.3 which offers first-class npm support, the recommended approach is to install Bootstrap directly from npm, which doesn't depend on any poorly-maintained (ahem) shim packages:

```<code>$ meteor npm install --save bootstrap
</code>```

(This also saves bootstrap in your package.json file so others can install it with meteor npm install.)

Then, in any client-side JS file (e.g. /client/main.js):

```<code>import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
</code>```

If you're interested in more customized Bootstrap installs using SASS/SCSS, etc. check out this post.

Title: Installing bootstrap 3 with meteor

Body:
I've read a lot of posts about how bootstrap can be included in your meteor project and more recently, I've seen people using

meteor add mizzao:bootstrap-3

like in this anwser.

The thing is when I try to do it I get the following error :

mizzao:bootstrap-3: no such package

Is there another version I need to use or is there another way to add bootstrap 3 to a meteor project.

Body:
I actually set up mizzao:bootstrap-3 a long time ago, but this was for a much older version of Meteor.

Starting from Meteor 1.3 which offers first-class npm support, the recommended approach is to install Bootstrap directly from npm, which doesn't depend on any poorly-maintained (ahem) shim packages:

$ meteor npm install --save bootstrap

(This also saves bootstrap in your package.json file so others can install it with meteor npm install.)

Then, in any client-side JS file (e.g. /client/main.js):

import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';

If you're interested in more customized Bootstrap installs using SASS/SCSS, etc. check out this post.