问:
Observables involving other observable
I have an issue where one of my observables depends on another observable, but when the parent observable is updated, the child does not appear to be updated.

ClientService (parent)

```<code>@Injectable()
export class ClientService {

  private client =  new BehaviorSubject("");
  clientStream$ = this.client.asObservable();

  }
}
</code>```

CommentService (child)

```<code>@Injectable()
export class CommentsProvider {
  private client$: Observable<any>;
  private comments = new BehaviorSubject([]);
  comments$: Observable<any[]>

  constructor(private clientService: ClientService) {
    this.initializeComments()
  }

  initializeComments() {
    this.client$ = this.clientService.clientStream$
    this.comments$ = this.comments.asObservable()

    this.client$.subscribe( client => {
      for ( let comment of client.comments ) {
        this.addComment(comment)
      }
    })
  }

  addComment(comment) {
    let commentArray = _.cloneDeep(this.comments.getValue());
    commentArray.push(comment)
    this.comments.next(commentArray)
  }

  getComments() : Observable<any[]> {
    return this.comments$
  }
}
</code>```

And in my view component I call:

```<code>`this.comments$ = this.commentService.getComments();`
</code>```

and display the results using:

```<code>*ngIf="this.comments$ | async as comments ..."
</code>```

If I make a call to addComment(), the array is updated, however, when I add a comment to client.comments, the array is not updated.  Would there be a way to notify subscribers of the change to client.comments?

答:
I may be missing something, but there's nothing in ClientService to add to the BehaviorSubject.  </p>

<pre class="lang-js prettyprint-override"><code>@Injectable()
export class ClientService {

  private client =  new BehaviorSubject("");
  clientStream$ = this.client.asObservable();

  }
}
</code>```

<p>Variable <code>client</code> is private, so can't be accessed outside the class.<br>
<code>clientStream$</code> is <code>asObservable()</code>, so you can't <code>.next(newVale)</code> to give it new value (at least I think that's the point of asObservable).<br>
Did you only paste part of ClientService? - there's two closing curley's but only one opening curley.</p>

<p>Maybe add this method to ClientService,</p>

<pre class="lang-js prettyprint-override"><code>addClient(newClient) {
  client.next(newClient);
}
</code>```

Title: Observables involving other observable

Body:
I have an issue where one of my observables depends on another observable, but when the parent observable is updated, the child does not appear to be updated.

ClientService (parent)

@Injectable()
export class ClientService {

  private client =  new BehaviorSubject("");
  clientStream$ = this.client.asObservable();

  }
}

CommentService (child)

@Injectable()
export class CommentsProvider {
  private client$: Observable<any>;
  private comments = new BehaviorSubject([]);
  comments$: Observable<any[]>

  constructor(private clientService: ClientService) {
    this.initializeComments()
  }

  initializeComments() {
    this.client$ = this.clientService.clientStream$
    this.comments$ = this.comments.asObservable()

    this.client$.subscribe( client => {
      for ( let comment of client.comments ) {
        this.addComment(comment)
      }
    })
  }

  addComment(comment) {
    let commentArray = _.cloneDeep(this.comments.getValue());
    commentArray.push(comment)
    this.comments.next(commentArray)
  }

  getComments() : Observable<any[]> {
    return this.comments$
  }
}

And in my view component I call:

`this.comments$ = this.commentService.getComments();`

and display the results using:

*ngIf="this.comments$ | async as comments ..."

If I make a call to addComment(), the array is updated, however, when I add a comment to client.comments, the array is not updated.  Would there be a way to notify subscribers of the change to client.comments?

Body:
I may be missing something, but there's nothing in ClientService to add to the BehaviorSubject.

@Injectable()
export class ClientService {

  private client =  new BehaviorSubject("");
  clientStream$ = this.client.asObservable();

  }
}

Variable client is private, so can't be accessed outside the class.

clientStream$ is asObservable(), so you can't .next(newVale) to give it new value (at least I think that's the point of asObservable).

Did you only paste part of ClientService? - there's two closing curley's but only one opening curley.

Maybe add this method to ClientService,

addClient(newClient) {
  client.next(newClient);
}


来源: stackexchange

问:
How do I convert a document from Latex into Microsoft Word 2003?
I need to find a way to quickly convert a latex document into a Microsoft Word 2003 document.

I'm using Kile to edit latex documents on Ubuntu at present.

I can do it the following way:

```<code>latex filename.tex
tex4ht filename.tex
mk4ht oolatex filename.tex
</code>```

then I have to open the resulting filename.odt document in OpenOffice and save as a Word Document.

Is there anyway I do this in a single step?

I can write a program to run the initial three lines, I'm more interested in the  conversion from odt to doc without using openoffice.

It would be even better if I could find a way to convert straight from filename.tex to filename.doc

答: I tried many free solutions, but my LaTeX document was too complicated.  In the end, commercially available GrindEQ did the best job by far.  If you only need to do this once, you can use the demo version.</p>

ContentLicense: CC BY-SA 2.5

Body:
I need to find a way to quickly convert a latex document into a Microsoft Word 2003 document.

I'm using Kile to edit latex documents on Ubuntu at present.

I can do it the following way:

latex filename.tex
tex4ht filename.tex
mk4ht oolatex filename.tex

then I have to open the resulting filename.odt document in OpenOffice and save as a Word Document.

Is there anyway I do this in a single step?

I can write a program to run the initial three lines, I'm more interested in the  conversion from odt to doc without using openoffice.

It would be even better if I could find a way to convert straight from filename.tex to filename.doc


问:
stop javascript loop, setTimeout
This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

```<code>setTimeout(function() {
createSnow(20);
loop();
}, 10000)
</code>```

here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

答:
What you'll want to do is create a "timer", finding the difference between when you started and the current time.

I'm not sure if you wanted createSnow(20) inside of the loop or not, so I put it before, as initialization.

```<code>createSnow(20);

const start = new Date();
while(new Date() - start < 10000) {
  loop();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: stop javascript loop, setTimeout

Body:
This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

setTimeout(function() {
createSnow(20);
loop();
}, 10000)

here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

Body:
What you'll want to do is create a "timer", finding the difference between when you started and the current time.

I'm not sure if you wanted createSnow(20) inside of the loop or not, so I put it before, as initialization.

createSnow(20);

const start = new Date();
while(new Date() - start < 10000) {
  loop();
}


问:
Paypal IPN, where to put my order id in paypal sdk (android) to verify payment through my server?
I implemented Paypal payment to my Android App(like here: http://androiddevelopmentanddiscussion.blogspot.de/2014/05/paypal-integration-in-android.html) .

First, I contact my server to get an order_id to my Android device. After that the user is able to make payment with Paypal (sandbox),  I can see that the payment was successful and my Android client gets a response back from Paypal("PaymentConfirmation info received from PayPal") together with a paypal "confirm" object.

I could then use that confirm object to send it back to my server and mark the payment as succeeded(for that I would use the order_id). But there is a problem.

What happens, if the internet connection gets interrupted? I would not be able to mark the payment as succeeded into my server database. I know, that there is the possibility to get a IPN message from Paypal to my server and could use that to mark payment as succeed. But how could I pass the order_id into my payment, so that the IPN message, which is sent by Paypal after successful payment to my server, contains that order_id?

I need that order_id to identify my customer and the order... I could not find any useful information regarding that topic. I do not know how to achieve that. I can only pass following information to my Payment:

```<code>  if(pressed.getId() == R.id.button1){
   thingToBuy = new PayPalPayment(new BigDecimal("8"), "USD", "Painting 1", PayPalPayment.PAYMENT_INTENT_SALE);
</code>```

Any tips are much appreciated. (sorry for my english, I am not a native english speaker)

答:
There is a method called "invoiceNumber" in PaypalPayment class to set the invoice number.

You can use it to set the invoice number so the IPN can fire it back to your server.

i.e.

String yourOrderNumber = "test";
thingToBuy.invoiceNumber(yourOrderNumber);

BTW, if you pass the result object back to the server, you may need to verify your payment. Things you may consider to avoid fraud (according to the paypal document)

Is the proof of payment authentic?

Am I the recipient of the payment?

Are the amount and currency correct?

Has the payment been previously used?

In my experience, what I did was to leave the IPN do the confirm payment part.

Hope it helps.

Body:
I implemented Paypal payment to my Android App(like here: http://androiddevelopmentanddiscussion.blogspot.de/2014/05/paypal-integration-in-android.html) .

First, I contact my server to get an order_id to my Android device. After that the user is able to make payment with Paypal (sandbox),  I can see that the payment was successful and my Android client gets a response back from Paypal("PaymentConfirmation info received from PayPal") together with a paypal "confirm" object.

I could then use that confirm object to send it back to my server and mark the payment as succeeded(for that I would use the order_id). But there is a problem.

What happens, if the internet connection gets interrupted? I would not be able to mark the payment as succeeded into my server database. I know, that there is the possibility to get a IPN message from Paypal to my server and could use that to mark payment as succeed. But how could I pass the order_id into my payment, so that the IPN message, which is sent by Paypal after successful payment to my server, contains that order_id?

I need that order_id to identify my customer and the order... I could not find any useful information regarding that topic. I do not know how to achieve that. I can only pass following information to my Payment:

  if(pressed.getId() == R.id.button1){
   thingToBuy = new PayPalPayment(new BigDecimal("8"), "USD", "Painting 1", PayPalPayment.PAYMENT_INTENT_SALE);

Any tips are much appreciated. (sorry for my english, I am not a native english speaker)


问:
Change navigation bar icon color on Android
I need to change the navigation bar on android. Just like the 'light' variant on the right in the image below
as given in https://www.google.co.in/design/spec/layout/structure.html#structure-system-bars.

Now, I can change the background of the navigation bar by using

"android:navigationBarColor"

I get

but there seems to be no way changing the button color to dark.

Anyone has the idea how to do it.

PS:

While researching in AOSP for the classes responsible for NavigationButtons, I could find NavigationBarView.java, PhoneStatusBar.java, PhoneWindowManager.java, navigation_bar.xml.

I was thinking of get reference of the drawable for the navigationbar buttons like ic_sysbar_recent and change their tint. But these are private and I cannot get their reference.

Also, I have seen people using xposed library to do it L-NAVBAR, but I don't want to use any external library.

答:
If you are using API 27 (Android 8.1) or greater, you can achieve it with this in your theme:

```<code><item name="android:windowLightNavigationBar">true</item>
</code>```

You can create a folder called values-v27 and place a version of your theme (in styles.xml) with a light navigation bar and the above code to get dark navigation bar buttons.

This way, users with Android 8.0 or lower will get the standard (black) navigation bar while users with Android 8.1 or greater will get a white navbar with dark buttons.

Body:
If you are using API 27 (Android 8.1) or greater, you can achieve it with this in your theme:

<item name="android:windowLightNavigationBar">true</item>

You can create a folder called values-v27 and place a version of your theme (in styles.xml) with a light navigation bar and the above code to get dark navigation bar buttons.

This way, users with Android 8.0 or lower will get the standard (black) navigation bar while users with Android 8.1 or greater will get a white navbar with dark buttons.


问:
how to set z-index of dialog box higher than you tube video using jquery?
I'm providing an interface where user can integrate You tube videos in their web pages. I could integrate the video, but to provide edit property function, I tried to add a Span with text "Edit Properties" . But, I could not make it to display over the you tube object. Also, the dialog boxes (Jquery Dialog) also are displayed behind the you tube control. How can I make the dialog boxes to overlap the you tub object ?</p>

答: Set the wmode to transparent. <param name=wmode value=transparent> for object and <embed wmode=transparent>


问:
C# How to turn String with Carriage Return symbols in to an array
I am calling some external method that returns a string like this.

```<code>"[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]"
</code>```

How do I turn this in to an Array with the values 1,2,3 ?

Should I be trying to split/substring methods to do this, or is there some kind of built in .net method that can do this?

I have tried,

```<code>string theStringResult = Class.ExternalMethod();
theStringResult.ToArray()
</code>```

答:
The returned string appears to be a JSON array made up of strings.

The line breaks are part of a pretty print version of the JSON string which,  when not escaped, would look like this...

[
  "0",
  "1",
  "2"
]
```

<p>You can use Newtonsoft's Json.Net to parse and deserialize the returned string into a strongly typed object.</p>

```string theStringResult = Class.ExternalMethod();
string[] array = JsonConver.DeserializeObject<string[]>(theStringResult);
```

The above should produce the desired result

Body:
I am calling some external method that returns a string like this.

"[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]"

How do I turn this in to an Array with the values 1,2,3 ?

Should I be trying to split/substring methods to do this, or is there some kind of built in .net method that can do this?

I have tried,

string theStringResult = Class.ExternalMethod();
theStringResult.ToArray()

Body:
The returned string appears to be a JSON array made up of strings.

The line breaks are part of a pretty print version of the JSON string which,  when not escaped, would look like this...

[
  "0",
  "1",
  "2"
]

You can use Newtonsoft's Json.Net to parse and deserialize the returned string into a strongly typed object.

string theStringResult = Class.ExternalMethod();
string[] array = JsonConver.DeserializeObject<string[]>(theStringResult);

The above should produce the desired result


问:
Updating someone else's codebase from revision 49 to current
So I dealt with all the stuff that name errored, but there are still problems

Here's what the page should look like http://hamishtodd1.github.io/conferencing/glmol/minExample/nativeVersion/

And here's where I've gotten to
http://hamishtodd1.github.io/conferencing/glmol/minExample/

If you mousewheel a bit you can see some triangles glitched up stuff, so at least there's something, and I'm guessing I need to get onto turning face4's into two face3's. But I don't think that'll get this all the way, are there any general changes I definitely need to make because of revision differences?

Here's the file that matters the most, if it helps https://github.com/hamishtodd1/hamishtodd1.github.io/blob/master/conferencing/glmol/minExample/GLmol.js

答:
https://github.com/mrdoob/three.js/wiki/Migration-Guide

There are a lot of updates across so many versions, maybe you can see the migration guide for three.js


问:
Get an employees start and end date for each position from an employee history table
I need to have in one sql query an output in one line that has the start date and end date of each position for an employee.

Current table structure is:

```<code>| EMP_ID | SYST_LOGIN | TEAM | POSITION | LOCATION | START_DATE | END_DATE |
|--------|------------|------|----------|----------|------------|----------|
| 123456 | FNAM.LNAM  | A    | POS1     | LOC1     | 01-JAN-17  | 31-JAN-17|
| 123456 | FNAM.LNAM  | A    | POS1     | LOC2     | 01-FEB-17  | 15-FEB-17|
| 123456 | FNAM.LNAM  | B    | POS1     | LOC2     | 16-FEB-17  | 15-MAR-17|
| 123465 | FNAM.LNAM  | C    | POS2     | LOC2     | 16-MAR-17  | NULL     |
</code>```

I need the out put to be:

```<code>| EMP_ID | SYST_LOGIN | POSITION | LOCATION | START_DATE | END_DATE  |
|--------|------------|----------|----------|------------|-----------|
| 123456 | FNAM.LNAM  | POS1     | LOC2     | 01-JAN-17  | 15-MAR-17 |
| 123465 | FNAM.LNAM  | POS2     | LOC2     | 16-MAR-17  | NULL      |
</code>```

A new employee table was built and the business is requested that all changes to an employee create a new record in the table opposed to just updating the new location.  So now I want to look at an employees position and know the start date and end date.  Thank you for your help.

Gordon Linoff's query below worked for this.

****Updated second scenario that I ran into****

```<code>| EMP_ID | SYST_LOGIN | TEAM | POSITION | LOCATION | START_DATE | END_DATE |
|--------|------------|------|----------|----------|------------|----------|
| 123456 | FNAM.LNAM  | A    | POS1     | LOC1     | 01-JAN-17  | 31-JAN-17|
| 123456 | FNAM.LNAM  | A    | POS1     | LOC2     | 01-FEB-17  | 15-FEB-17|
| 123456 | FNAM.LNAM  | B    | POS1     | LOC2     | 16-FEB-17  | NULL     |
</code>```

Using Gordon Linoff's query he gave below:

select EMP_ID, SYST_LOGIN, POSITION, LOCATION,
       min(start_date) as start_date, max(end_date) as end_date
from t
group by EMP_ID, SYST_LOGIN, POSITION, LOCATION

Using this I get the following results:

```<code> | EMP_ID | SYST_LOGIN | POSITION | LOCATION | START_DATE | END_DATE  |
 |--------|------------|----------|----------|------------|-----------|
 | 123456 | FNAM.LNAM  | POS1     | LOC2     | 01-JAN-17  | 15-FEB-17 |
</code>```

Due to the fact the employee is still active the END_DATE on the last record is NULL and is not used when using max(END_DATE).

答:
Assuming there are no gaps, then this is just aggregation:</p>

```<code>select EMP_ID, SYST_LOGIN, POSITION, LOCATION,
       min(start_date) as start_date, max(end_date) as end_date
from t
group by EMP_ID, SYST_LOGIN, POSITION, LOCATION;
</code>```

Body:
I need to have in one sql query an output in one line that has the start date and end date of each position for an employee.

Current table structure is:

| EMP_ID | SYST_LOGIN | TEAM | POSITION | LOCATION | START_DATE | END_DATE |
|--------|------------|------|----------|----------|------------|----------|
| 123456 | FNAM.LNAM  | A    | POS1     | LOC1     | 01-JAN-17  | 31-JAN-17|
| 123456 | FNAM.LNAM  | A    | POS1     | LOC2     | 01-FEB-17  | 15-FEB-17|
| 123456 | FNAM.LNAM  | B    | POS1     | LOC2     | 16-FEB-17  | 15-MAR-17|
| 123465 | FNAM.LNAM  | C    | POS2     | LOC2     | 16-MAR-17  | NULL     |

I need the out put to be:

| EMP_ID | SYST_LOGIN | POSITION | LOCATION | START_DATE | END_DATE  |
|--------|------------|----------|----------|------------|-----------|
| 123456 | FNAM.LNAM  | POS1     | LOC2     | 01-JAN-17  | 15-MAR-17 |
| 123465 | FNAM.LNAM  | POS2     | LOC2     | 16-MAR-17  | NULL      |

A new employee table was built and the business is requested that all changes to an employee create a new record in the table opposed to just updating the new location.  So now I want to look at an employees position and know the start date and end date.  Thank you for your help.

Gordon Linoff's query below worked for this.

****Updated second scenario that I ran into****

| EMP_ID | SYST_LOGIN | TEAM | POSITION | LOCATION | START_DATE | END_DATE |
|--------|------------|------|----------|----------|------------|----------|
| 123456 | FNAM.LNAM  | A    | POS1     | LOC1     | 01-JAN-17  | 31-JAN-17|
| 123456 | FNAM.LNAM  | A    | POS1     | LOC2     | 01-FEB-17  | 15-FEB-17|
| 123456 | FNAM.LNAM  | B    | POS1     | LOC2     | 16-FEB-17  | NULL     |

Using Gordon Linoff's query he gave below:

select EMP_ID, SYST_LOGIN, POSITION, LOCATION,
       min(start_date) as start_date, max(end_date) as end_date
from t
group by EMP_ID, SYST_LOGIN, POSITION, LOCATION

Using this I get the following results:

 | EMP_ID | SYST_LOGIN | POSITION | LOCATION | START_DATE | END_DATE  |
 |--------|------------|----------|----------|------------|-----------|
 | 123456 | FNAM.LNAM  | POS1     | LOC2     | 01-JAN-17  | 15-FEB-17 |

Due to the fact the employee is still active the END_DATE on the last record is NULL and is not used when using max(END_DATE).

Body:
Assuming there are no gaps, then this is just aggregation:

select EMP_ID, SYST_LOGIN, POSITION, LOCATION,
       min(start_date) as start_date, max(end_date) as end_date
from t
group by EMP_ID, SYST_LOGIN, POSITION, LOCATION;


问:
C array sorting ignoring special characters
```<code>char temp[size];
int b, z;
for (b = 0; b < size; b++) {
    for (z = 0; z < size; z++) {
        if (strcmp(processNames[b], processNames[z]) < 0) {
            strcpy(temp, processNames[b]);
            strcpy(processNames[b], processNames[z]);
            strcpy(processNames[z], temp);
        }
    }
}
</code>```

I'm sorting a list of char ** processNames;

I want it to sort like this:

```<code>abc
bee
george
(sally)
saw
thomas
zebra
</code>```

However, it is sorting it like this:

```<code>(sally)
abc
bee
george
saw
thomas
zebra
</code>```

Thanks, I'm not sure how to negate the special characters and only sort on alphabet. Thanks!

答:
You can pre-process the string and use strcmp to compare the processed string:

```<code>// Inside the two-layer for loop
char newb[size], newz[size];
int ib, iz, tb = 0, tz = 0;
for (ib = 0; processNames[b][ib] != '\0'; ib++){
    if (isalpha(processNames[b][ib])) {
        newb[tb++] = processNames[b][ib];
    }
}
newb[tb] = 0;
for (iz = 0; processNames[z][iz] != '\0'; iz++){
    if (isalpha(processNames[z][iz])) {
        newz[tz++] = processNames[z][iz];
    }
}
newz[tz] = 0;

if (strcmp(newb, newz)) {
    // swap the ORIGINAL string here
}
</code>```

The above code is what I came up with at first. It is very inefficient and is not recommended. Alternatively, you can write your own mystrcmp() implementation:

```<code>int mystrcmp(const char* a, const char *b){
    while (*a && *b) {
        while (*a && !isalpha(*a)) a++;
        while (*b && !isalpha(*b)) b++;
        if (*a - *b) return *a - *b;
        a++, b++;
    }
    return *a - *b;
}
</code>```

Body:
char temp[size];
int b, z;
for (b = 0; b < size; b++) {
    for (z = 0; z < size; z++) {
        if (strcmp(processNames[b], processNames[z]) < 0) {
            strcpy(temp, processNames[b]);
            strcpy(processNames[b], processNames[z]);
            strcpy(processNames[z], temp);
        }
    }
}

I'm sorting a list of char ** processNames;

I want it to sort like this:

abc
bee
george
(sally)
saw
thomas
zebra

However, it is sorting it like this:

(sally)
abc
bee
george
saw
thomas
zebra

Thanks, I'm not sure how to negate the special characters and only sort on alphabet. Thanks!

Body:
You can pre-process the string and use strcmp to compare the processed string:

// Inside the two-layer for loop
char newb[size], newz[size];
int ib, iz, tb = 0, tz = 0;
for (ib = 0; processNames[b][ib] != '\0'; ib++){
    if (isalpha(processNames[b][ib])) {
        newb[tb++] = processNames[b][ib];
    }
}
newb[tb] = 0;
for (iz = 0; processNames[z][iz] != '\0'; iz++){
    if (isalpha(processNames[z][iz])) {
        newz[tz++] = processNames[z][iz];
    }
}
newz[tz] = 0;

if (strcmp(newb, newz)) {
    // swap the ORIGINAL string here
}

The above code is what I came up with at first. It is very inefficient and is not recommended. Alternatively, you can write your own mystrcmp() implementation:

int mystrcmp(const char* a, const char *b){
    while (*a && *b) {
        while (*a && !isalpha(*a)) a++;
        while (*b && !isalpha(*b)) b++;
        if (*a - *b) return *a - *b;
        a++, b++;
    }
    return *a - *b;
}


问:
How to create a user in postgres and to give grantall privileges
I'm new to PostgreSQL and I have created a postgres instance in the AWS RDS and I have also created a new user. Now I would like to grant all privileges to that user for creating new databases and to perform all admin operations.

I have found the below query to do that but it was providing access only to a particular database and that user is unable to create a new database.

```<code>GRANT ALL ON DATABASE workflow TO cnwrkstag;
</code>```

I have also tried to provide access as a super user of RDS but I'm getting an error as I am unable to so because it should be a super user.

Can anyone help me with this?

答:
You must be very careful with the super users, you can doit this way:

```<code>ALTER ROLE role_name SUPERUSER;
</code>```

Or

```<code>ALTER USER user_name SUPERUSER;
</code>```

Here is the documentation:

Alter-role

Body:
I'm new to PostgreSQL and I have created a postgres instance in the AWS RDS and I have also created a new user. Now I would like to grant all privileges to that user for creating new databases and to perform all admin operations.

I have found the below query to do that but it was providing access only to a particular database and that user is unable to create a new database.

GRANT ALL ON DATABASE workflow TO cnwrkstag;

I have also tried to provide access as a super user of RDS but I'm getting an error as I am unable to so because it should be a super user.

Can anyone help me with this?

Body:
You must be very careful with the super users, you can doit this way:

ALTER ROLE role_name SUPERUSER;

Or

ALTER USER user_name SUPERUSER;

Here is the documentation:

Alter-role


问:
How to change IsPassive="true" to false in travelocity (saml test 2.0) with WSO2 IS
I am getting by default IsPassive="true" in saml request which is not allowing to test further. Can anyone please let me know how to disable it?

Sample Request & response

```<code><samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
                    AssertionConsumerServiceURL="XXXXXX"
                    Destination="XXXX/samlsso"
                    ForceAuthn="false"
                    ID="0"
                    IsPassive="true"
                    IssueInstant="2017-11-14T04:33:32.667Z"
                    ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
                    Version="2.0"
                    >
    <samlp:Issuer xmlns:samlp="urn:oasis:names:tc:SAML:2.0:assertion">XXX_SIT</samlp:Issuer>
    <saml2p:NameIDPolicy xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
                         AllowCreate="true"
                         Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
                         SPNameQualifier="Issuer"
                         />
    <saml2p:RequestedAuthnContext xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
                                  Comparison="exact"
                                  >
        <saml:AuthnContextClassRef xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
    </saml2p:RequestedAuthnContext>
</samlp:AuthnRequest>

<saml2p:Response Destination="XXXXX"
                 ID="makcbhpbkmpgheepeaibnbmolnhalmdchlpfjiij"
                 InResponseTo="0"
                 IssueInstant="2017-11-14T04:33:31.297Z"
                 Version="2.0"
                 xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
                 >
    <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
                  xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
                  >localhost</saml2:Issuer>
    <saml2p:Status>
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder">
            <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:NoPassive" />
        </saml2p:StatusCode>
        <saml2p:StatusMessage>Cannot authenticate Subject in Passive Mode</saml2p:StatusMessage>
    </saml2p:Status>
</saml2p:Response>
</code>```

答:
You cannot disable the passive request from a config but you can bypass it if you directly access the http://localhost:8080/travelocity.com/index.jsp page.

In travelocity, the passive authentication request is sent while accessing the root context of the app e.g: http://localhost:8080/travelocity.com. The purpose of this call is to check whether the user already has an authenticated session with the IS. If the user has an authenticated session, IS will return a SAML response with an assertion and travelocity will be redirected to home.jsp. If the user doesn't have an authecticated session,  IS will return the SAML response you have mentioned above ("Cannot authenticate Subject in Passive Mode"). Once travelocity receives this response it should be redirected to index.jsp where you will have different options to authenticate with SAML.

The login options you see there doesn't use passive SAML authentication requests.

Body:
I am getting by default IsPassive="true" in saml request which is not allowing to test further. Can anyone please let me know how to disable it?

Sample Request & response

<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
                    AssertionConsumerServiceURL="XXXXXX"
                    Destination="XXXX/samlsso"
                    ForceAuthn="false"
                    ID="0"
                    IsPassive="true"
                    IssueInstant="2017-11-14T04:33:32.667Z"
                    ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
                    Version="2.0"
                    >
    <samlp:Issuer xmlns:samlp="urn:oasis:names:tc:SAML:2.0:assertion">XXX_SIT</samlp:Issuer>
    <saml2p:NameIDPolicy xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
                         AllowCreate="true"
                         Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
                         SPNameQualifier="Issuer"
                         />
    <saml2p:RequestedAuthnContext xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
                                  Comparison="exact"
                                  >
        <saml:AuthnContextClassRef xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
    </saml2p:RequestedAuthnContext>
</samlp:AuthnRequest>

<saml2p:Response Destination="XXXXX"
                 ID="makcbhpbkmpgheepeaibnbmolnhalmdchlpfjiij"
                 InResponseTo="0"
                 IssueInstant="2017-11-14T04:33:31.297Z"
                 Version="2.0"
                 xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
                 >
    <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
                  xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
                  >localhost</saml2:Issuer>
    <saml2p:Status>
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder">
            <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:NoPassive" />
        </saml2p:StatusCode>
        <saml2p:StatusMessage>Cannot authenticate Subject in Passive Mode</saml2p:StatusMessage>
    </saml2p:Status>
</saml2p:Response>


问:
Converting an IEnumerable<string> to IEnumerable<ListItem>
I'm getting this error which while trying to use the yield return feature in C#. The error appears on the select inside visual studio and I don't really understand it. In my mind I'm converting a string to a ListItem and then returning the lot as an IEnumerable. My understanding of yield return and IEnumerable might very well be off the mark so any help would be appreciated. The commented code is the old school way of doing it which does work properly.

Cannot implicitly convert type
  'System.Collections.Generic.IEnumerable'
  to
  'System.Web.UI.WebControls.ListItem'

```<code>public partial class CloseIncident : System.Web.UI.Page
{
    private ClevelandIncidentRepository repo = new ClevelandIncidentRepository();

    protected void Page_Load(object sender, EventArgs e)
    {
        SetDropDown(InitialType, repo.GetMainTypes());
    }

    private void SetDropDown(DropDownList dropDown, IEnumerable<string> items)
    {
        dropDown.Items.Clear();
        dropDown.Text = string.Empty;
        dropDown.Enabled = items.Count() > 0;

        dropDown.Items.AddRange(ToListItem(items).ToArray());
    }

    private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        yield return from result in results
                     select new ListItem(result);

        //List<ListItem> items = new List<ListItem>();

        //items.AddRange(from result in results
        //               select new ListItem(result));

        //return items;
    }
}
</code>```

答: yield return should refer to a single ListItem which would be returned in a 'lazy' way when the IEnumerable is iterated. Your linq expression is of type IEnumerable so there is a mismatch. </p>

ContentLicense: CC BY-SA 4.0

Body:
I'm getting this error which while trying to use the yield return feature in C#. The error appears on the select inside visual studio and I don't really understand it. In my mind I'm converting a string to a ListItem and then returning the lot as an IEnumerable. My understanding of yield return and IEnumerable might very well be off the mark so any help would be appreciated. The commented code is the old school way of doing it which does work properly.

Cannot implicitly convert type
  'System.Collections.Generic.IEnumerable'
  to
  'System.Web.UI.WebControls.ListItem'

public partial class CloseIncident : System.Web.UI.Page
{
    private ClevelandIncidentRepository repo = new ClevelandIncidentRepository();

    protected void Page_Load(object sender, EventArgs e)
    {
        SetDropDown(InitialType, repo.GetMainTypes());
    }

    private void SetDropDown(DropDownList dropDown, IEnumerable<string> items)
    {
        dropDown.Items.Clear();
        dropDown.Text = string.Empty;
        dropDown.Enabled = items.Count() > 0;

        dropDown.Items.AddRange(ToListItem(items).ToArray());
    }

    private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        yield return from result in results
                     select new ListItem(result);

        //List<ListItem> items = new List<ListItem>();

        //items.AddRange(from result in results
        //               select new ListItem(result));

        //return items;
    }
}


问:
div height calc(100% - 50px) not working
https://codepen.io/joshuajazleung/pen/EbbgBN

```<code><div class="outer">
  <div class="inner">
    <img src="https://placehold.it/300x200" alt="">
    <div>Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio animi harum impedit ex esse labore, placeat, tempore sapiente nisi cupiditate fugiat soluta ullam dicta ducimus accusamus tenetur consequuntur nesciunt earum!</div>
  </div>
</div>

.outer {
  background: red;
  position: relative;
  height: calc(100% - 60px);
}

.inner {
  position: relative;
  top: -100px;
}
</code>```

since .inner is moved to top a little bit, to reduce .outer overall space, I use

```<code>height: calc(100% - 50px); // my logic is that it's div's height minus 50px
</code>```

But it's not working, wondering why?

答:
Not really clear what you are after, but if you use a height setting which contains percentage values, the parent element of that element needs to have a defined height definition in order have a reference for the percentage amount. In your case, that's the body, whose parent again is the html element, so you should add this CSS:

```<code>html, body {
  height: 100%;
}
</code>```

https://codepen.io/anon/pen/XzzNbN

Body:
https://codepen.io/joshuajazleung/pen/EbbgBN

Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio animi harum impedit ex esse labore, placeat, tempore sapiente nisi cupiditate fugiat soluta ullam dicta ducimus accusamus tenetur consequuntur nesciunt earum!

.outer {
  background: red;
  position: relative;
  height: calc(100% - 60px);
}

.inner {
  position: relative;
  top: -100px;
}

since .inner is moved to top a little bit, to reduce .outer overall space, I use

height: calc(100% - 50px); // my logic is that it's div's height minus 50px

But it's not working, wondering why?

Body:
Not really clear what you are after, but if you use a height setting which contains percentage values, the parent element of that element needs to have a defined height definition in order have a reference for the percentage amount. In your case, that's the body, whose parent again is the html element, so you should add this CSS:

html, body {
  height: 100%;
}

https://codepen.io/anon/pen/XzzNbN


问:
How to make inline function only take up one copy's worth of memory space in executable file
Is there a way to make an inline function (which has certainly been inlined by the compiler), which is present in multiple locations in the program, only take up as much memory in the executable file as if it were not inline and/or only had one inlined instance? Theoretically, this should be possible, since the function would just have to be loaded from memory once, and its loaded contents (in RAM and/or cache) would be copied to the other necessary locations in RAM in order to both increase performance and reduce space taken in the hard drive. Android is what I am mainly concerned about, but I would be grateful to hear answers about other operating systems other than android as well.  </p>

答: The whole point of inlining is that it allows the compiler to change, specialize, and optimize the function based on the other code around it. This means each inlined "copy" ends up different, operating on different registers and memory offsets and with different conditional branches optimized out. Trying to use the different versions of the function as if they were interchangeable would just break everything.</p>


答:
Seems like you want to have a cake and eat it too. The whole point of inlining is in putting duplicate of the function at the place of its call.

But this shouldn't worry you too much as in many cases inlined code is much smaller than the original function due to the fact that it misses register saving/restoring, has some parts of it removed due to them being evaluated at compile time etc. If your function is relatively small, inlining it might actually generate smaller code than the code required to actually call existing copy of a function.

If you think you might have issues with code size, you should really post some examples and explain why do you think this is an issue.

Currently the closest thing to what you describe is JIT (Just-In-Time) compilation which allows you to have a single copy of a function written in a high level (and thus vpossibly very compact) represenation that can later be translated to machine code on the fly. This is what Android's VM does btw.

If you are worried about program loading times, you probably shouldn't worry about few functions. First, code will be loaded from device in (most likely) 4 KiB pages. To reduce load time you need to reduce your code size by at least 1 page to have some improvement, otherwise you don't really win anything.

Keep in mind that data is usually loaded from non-volatile storage once and kept in OS cache e.g. in most cases code is already in RAM.

Even if you are able to achieve what you want (using some sort of JIT translation), you should remember that doing translation on the fly also costs time and requires more RAM as you will keep both original high level code and resulted machine code, thus pushing data out of cache, potentially slowing loading speed of other programs.

Title: How to make inline function only take up one copy's worth of memory space in executable file

Body: Is there a way to make an inline function (which has certainly been inlined by the compiler), which is present in multiple locations in the program, only take up as much memory in the executable file as if it were not inline and/or only had one inlined instance? Theoretically, this should be possible, since the function would just have to be loaded from memory once, and its loaded contents (in RAM and/or cache) would be copied to the other necessary locations in RAM in order to both increase performance and reduce space taken in the hard drive. Android is what I am mainly concerned about, but I would be grateful to hear answers about other operating systems other than android as well.


问:
How to set culture for date binding in Asp.Net Core?
I have an Asp.Net Core application with MVC. I'm submitting a form with a date on the form.

Form looks (roughly) like this:

```<code>@model EditCustomerViewModel
<form asp-action="Edit">
    <input asp-for="ServiceStartDate" class="form-control" type="date" />
    <input type="submit" value="Update" class="btn btn-success" />
</form>
</code>```

Controller action is:

```<code>[HttpPost]
public async Task<IActionResult> Edit(EditCustomerViewModel viewModel)
{
    // do stuff
    return RedirectToAction("Index");
}
</code>```

View model is:

```<code>public class EditCustomerViewModel
{
    public Guid Id { get; set; }

    [DataType(DataType.Date)]
    public DateTime ServiceStartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? ServiceEndDate { get; set; }

    // etc.
}
</code>```

I'm in the UK, so dates are not in US format: dd/MM/YYYY. So by default I'm submitting 6/22/2017.

When looking on the submitted view model in controller during debugging, dates are null if submitted in UK format, but are fine if using US format. i.e. 6/22/2017 gives me null, but 22/6/2017 is bound to the correct date.

I have tried adding this to Startup.cs but it did not make any difference:

```<code>var supportedCultures = new[] { new CultureInfo("en-GB") };
app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("en-GB"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
});
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-GB");
CultureInfo.CurrentCulture = new CultureInfo("en-GB");
CultureInfo.CurrentUICulture = new CultureInfo("en-GB");
</code>```

I've checked HTTP headers and I'm posting correct header:

```<code>Accept-Language: en-GB,en
</code>```

What am I doing wrong? How can I tell MVC Core binders to bind dates in UK format?

p.s. I'm on VS2017 with *.csproj project file, with target framework .NetCoreApp 1.1

答:
Updated answer for aspnet core 2.0</p>

```<code>    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var supportedCultures = new[] { new CultureInfo("es-CO") };
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("es-CO"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        });

        // other configurations after (not before)
    }
</code>```

Body:
I have an Asp.Net Core application with MVC. I'm submitting a form with a date on the form.

Form looks (roughly) like this:

@model EditCustomerViewModel
<form asp-action="Edit">
    <input asp-for="ServiceStartDate" class="form-control" type="date" />
    <input type="submit" value="Update" class="btn btn-success" />
</form>

Controller action is:

[HttpPost]
public async Task<IActionResult> Edit(EditCustomerViewModel viewModel)
{
    // do stuff
    return RedirectToAction("Index");
}

View model is:

public class EditCustomerViewModel
{
    public Guid Id { get; set; }

    [DataType(DataType.Date)]
    public DateTime ServiceStartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? ServiceEndDate { get; set; }

    // etc.
}

I'm in the UK, so dates are not in US format: dd/MM/YYYY. So by default I'm submitting 6/22/2017.

When looking on the submitted view model in controller during debugging, dates are null if submitted in UK format, but are fine if using US format. i.e. 6/22/2017 gives me null, but 22/6/2017 is bound to the correct date.

I have tried adding this to Startup.cs but it did not make any difference:

var supportedCultures = new[] { new CultureInfo("en-GB") };
app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("en-GB"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
});
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-GB");
CultureInfo.CurrentCulture = new CultureInfo("en-GB");
CultureInfo.CurrentUICulture = new CultureInfo("en-GB");

I've checked HTTP headers and I'm posting correct header:

Accept-Language: en-GB,en

What am I doing wrong? How can I tell MVC Core binders to bind dates in UK format?

p.s. I'm on VS2017 with *.csproj project file, with target framework .NetCoreApp 1.1

Body:
Updated answer for aspnet core 2.0

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var supportedCultures = new[] { new CultureInfo("es-CO") };
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("es-CO"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        });

        // other configurations after (not before)
    }


问:
How do i multiply two one-dimensional arrays?
I will be honest with you, I have absolutely no idea what i am doing, nor have the slightest of ideas where to look and it is my homework so if someone would be kind enough to help me out, I would be truly grateful.

"Write a program that declares three arrays named price, qty, and amt.  Each  array should be declared in main()and capable of holding 3 values.  Make up numbers for price and qty (quantity).(ShoppingCart.java) (4 pts) Write a method to fill the amt array with the product of the corresponding elements in price and qty.  (3–create a method within the ShoppingCart class)"

What i have attempted is just this:

```<code>public class Shoppingjava {

    public static void main(String[] args) {

        int price[] = {4, 9, 7};
        int qty[] = {2, 5, 3};
        int amt[] = new int[3];

        System.out.println(product(price, qty));
    }

    public product(int P[], int Q[]) {
        int[][] c = new int[P.length][Q.length];
        return product;
    }

}
</code>```

But i really don't know where to go with this, I am sorry to bother anyone with this and if it someone is willing to help me out, thank you.

答:
Array elements can be accessed by their index in the form int val = arr[0] (for retrieving) or arr[i] = val (for storing).

You can iterate through the parallel arrays price and qty with a for loop, cycling through each index, and storing the product of each pair in amt.

Generic code:

```<code>for (int i = 0; i < arrZ.length; i++) {
    arrZ[i] = arrX[i] * arrY[i];
}
</code>```

Your scenario:

```<code>for (int i = 0; i < amt.length; i++) {
    amt[i] = price[i] * qty[i];
}
</code>```

I'd also recommend referring to the Java tutorials for using arrays:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Body:
I will be honest with you, I have absolutely no idea what i am doing, nor have the slightest of ideas where to look and it is my homework so if someone would be kind enough to help me out, I would be truly grateful.

"Write a program that declares three arrays named price, qty, and amt.  Each  array should be declared in main()and capable of holding 3 values.  Make up numbers for price and qty (quantity).(ShoppingCart.java) (4 pts) Write a method to fill the amt array with the product of the corresponding elements in price and qty.  (3–create a method within the ShoppingCart class)"

What i have attempted is just this:

public class Shoppingjava {

    public static void main(String[] args) {

        int price[] = {4, 9, 7};
        int qty[] = {2, 5, 3};
        int amt[] = new int[3];

        System.out.println(product(price, qty));
    }

    public product(int P[], int Q[]) {
        int[][] c = new int[P.length][Q.length];
        return product;
    }

}

But i really don't know where to go with this, I am sorry to bother anyone with this and if it someone is willing to help me out, thank you.

Body:
Array elements can be accessed by their index in the form int val = arr[0] (for retrieving) or arr[i] = val (for storing).

You can iterate through the parallel arrays price and qty with a for loop, cycling through each index, and storing the product of each pair in amt.

Generic code:

for (int i = 0; i < arrZ.length; i++) {
    arrZ[i] = arrX[i] * arrY[i];
}

Your scenario:

for (int i = 0; i < amt.length; i++) {
    amt[i] = price[i] * qty[i];
}

I'd also recommend referring to the Java tutorials for using arrays:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html


问:
making a binary as little as possible
I have a program written in C and linked to a my static library (.a) in C too. How can I make this program as little as possible, without touch the code (I can recompile it etc)?</p>

答: If you are using gcc, the <code>-Os</code> flag will optimize for a small executable. I think gcc will try to link to shared libraries by default on most systems, but you might also want to look into that. </p>

Title: making a binary as little as possible

Body: If you are using gcc, the -Os flag will optimize for a small executable. I think gcc will try to link to shared libraries by default on most systems, but you might also want to look into that.


问:
Oracle Select via loop in Stored Procedure
I'm trying to select data from a table based on a array of filters calculated from another query. I have tried to describe what I'm trying to accomplish
in pseudo code below.

```<code>SELECT Equipment, MIN(TIME) as FractionStart, MAX(TIME) as FractionEnd
INTO FRACTIONS
FROM DATA
WHERE ID = 1
GROUP BY (Equipment)

/* Pseudo code */
FOR EACH ROW IN FRACTIONS
  INSERT INTO MYTABLE (SELECT * FROM EVENTTABLE WHERE EVTTIME BETWEEN ROW.FractionStart AND ROW.FractionEnd AND EVTAREA = ROW.Equipment);
FOR NEXT;

RETURN MYTABLE;
</code>```

I have been looking at cursors, but I haven't figured out how I can add rows to them in a loop. Am I looking at the right functions? or is there a better way to solve this?

答:
Can you try this?</p>

```<code>INSERT INTO MYTABLE
(
SELECT * FROM EVENTTABLE te,
(
SELECT Equipment, MIN(TIME) as FractionStart, MAX(TIME) as FractionEnd
FROM DATA
WHERE ID = 1
GROUP BY (Equipment)
) td
WHERE te.EVTTIME BETWEEN td.FractionStart AND td.FractionEnd AND te.EVTAREA = td.Equipment
);
</code>```

Body:
I'm trying to select data from a table based on a array of filters calculated from another query. I have tried to describe what I'm trying to accomplish
in pseudo code below.

SELECT Equipment, MIN(TIME) as FractionStart, MAX(TIME) as FractionEnd
INTO FRACTIONS
FROM DATA
WHERE ID = 1
GROUP BY (Equipment)

/* Pseudo code */
FOR EACH ROW IN FRACTIONS
  INSERT INTO MYTABLE (SELECT * FROM EVENTTABLE WHERE EVTTIME BETWEEN ROW.FractionStart AND ROW.FractionEnd AND EVTAREA = ROW.Equipment);
FOR NEXT;

RETURN MYTABLE;

I have been looking at cursors, but I haven't figured out how I can add rows to them in a loop. Am I looking at the right functions? or is there a better way to solve this?

Body:
Can you try this?

INSERT INTO MYTABLE
(
SELECT * FROM EVENTTABLE te,
(
SELECT Equipment, MIN(TIME) as FractionStart, MAX(TIME) as FractionEnd
FROM DATA
WHERE ID = 1
GROUP BY (Equipment)
) td
WHERE te.EVTTIME BETWEEN td.FractionStart AND td.FractionEnd AND te.EVTAREA = td.Equipment
);


问:
Virtual Box Unsupported version 17 of data unit 'cpum'
Failed to open a session for the virtual machine Ubuntu.

Unsupported version 17 of data unit 'cpum' (instance #1, pass 0xffffffff) (VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION).

Result Code: E_FAIL (0x80004005)

Component: Console

Interface: IConsole {8ab7c520-2442-4b66-8d74-4ff1e195d2b6}

I got this error code when I tried to open my virtual box this morning, which works perfectly fine yesterday. I saved my machine state before turning off the computer. I uninstalled Bluestacks this morning, and install(then unistall) Droid4X, which I think to be the source of problem, since Droid4X somehow was listed on my VirtualBox. Can someone explain to me why is this happening?

答:
I recently ran into this issue with an error message:
"Unsupported version 4 of data unit 'pci'"<br>
with a Ubuntu 14 VM on VirtualBox 5.1 for Mac. I originally used VB 5.2 when I setup the VM, saved it, then had to downgrade VBox (to use Vagrant), which I suppose caused this issue. The fix was similar, which is hard-rebooting the VM to skip the saved state. I did it from the UI though - right click, select Start/Normal Start. There would be a warning about discarding the saved sate but this wasn't a problem for me. </p>

Body:
I recently ran into this issue with an error message:
"Unsupported version 4 of data unit 'pci'"

with a Ubuntu 14 VM on VirtualBox 5.1 for Mac. I originally used VB 5.2 when I setup the VM, saved it, then had to downgrade VBox (to use Vagrant), which I suppose caused this issue. The fix was similar, which is hard-rebooting the VM to skip the saved state. I did it from the UI though - right click, select Start/Normal Start. There would be a warning about discarding the saved sate but this wasn't a problem for me.


问:
Google Custom Search JSON API webpages only
I am building a search component that allows users to filter by type of response. You can see all responses, just the PDFs, or just the webpages. I have the first two parts down, all responses is a basic search and you can filter for pdfs using &fileType=pdf in the query, but i'm not sure how to exclude the pdfs and only return web pages.

I can't find a similar "exclude" param such as -fileType which seems to be supported in other similar APIs. Maybe I just need to format the URL the right way... If anyone has insight into how to accomplish something like this I would appreciate it.

答: You can try with -inurl:pdf in your URL.


问:
Print out all subsets in an array that equal an given sum recursively
I have a weird homework that I have to write a program with a method that takes an array of non-negative integers (array elements can have repeated values) and a value sum as parameters. The method then prints out all the combinations of the elements in array whose sum is equal to sum. The weird part is, the teacher forces us to strictly follow the below structure:

```<code>public class Combinations {

    public static void printCombinations(int[] arr, int sum) {
       // Body of the method
    }

    public static void main(String[] args) {
       // Create 2-3 arrays of integers and 2-3 sums here then call the above
       // method with these arrays and sums to test the correctness of your method
    }

}
</code>```

We are not allow to add neither more methods nor more parameters for the current program. I have researched and understood several ways to do this recursively, but with this restriction, I don't really know how to do it. Therefore, I appreciate if you guys help me out.

EDIT: The array can have repeated elements. Here's an example run of the program.

```<code>arr = {1, 3, 2, 2, 25} and sum = 3
</code>```

Outputs:

(1, 2)  // 1st and 3rd element

(1, 2) // 1st and 4th element

(3) // 2nd element

答:
Seems duplicate, please go through below link for correct solution with exact code complexity details
find-a-pair-of-elements-from-an-array-whose-sum-equals-a-given-number</p>

Body:
I have a weird homework that I have to write a program with a method that takes an array of non-negative integers (array elements can have repeated values) and a value sum as parameters. The method then prints out all the combinations of the elements in array whose sum is equal to sum. The weird part is, the teacher forces us to strictly follow the below structure:

public class Combinations {

    public static void printCombinations(int[] arr, int sum) {
       // Body of the method
    }

    public static void main(String[] args) {
       // Create 2-3 arrays of integers and 2-3 sums here then call the above
       // method with these arrays and sums to test the correctness of your method
    }

}

We are not allow to add neither more methods nor more parameters for the current program. I have researched and understood several ways to do this recursively, but with this restriction, I don't really know how to do it. Therefore, I appreciate if you guys help me out.

EDIT: The array can have repeated elements. Here's an example run of the program.

arr = {1, 3, 2, 2, 25} and sum = 3

Outputs:

(1, 2)  // 1st and 3rd element

(1, 2) // 1st and 4th element

(3) // 2nd element


问:
Share Data From Apple Watch to iPhone
I am trying to Transfer Watch Data to the Application. I have tried to Research but the Tutorials are outdated. I am new to Watch development! I am thankful for any help I can get! :)

Trying to Pass Watch Button Text to iPhone Application

ON WATCH

let watchBatteryLevel = WKInterfaceDevice.current().batteryLevel
 self.button.setTitle(watchBatteryLevel)

ON IPHONE

Your Watch Battery is .....

答:
If the watch app is not running it can't send a message to the iPhone app, and it cannot be launched from the iPhone app, so I don't know if your idea will make sense.

But you can send a message from a running watch app to the iPhone using the WCSession class functions.

https://developer.apple.com/documentation/watchconnectivity/wcsession

transferUserInfo is one function that may do what you want

Title: Share Data From Apple Watch to iPhone


问:
Linking your app to an EXISTING page
I've searched and searched and can't seem to find any info in regards to this...

We have a facebook page (facebook.com/companyname). We also have an app on facebook (apps.facebook.com/companyname). I can create a NEW community page from the app, but i cant link it to the existing page. How come? Is there any way to do so?

There's plenty of similiar questions and no one has had an answer yet.

Thanks for the help!

答:
as on Nov 17th, 2017.

App page itself is a category, selecting this category would be the only option.
Also, Fb App name and Fb Page name must be the same for integrating existing page.

Title: Linking your app to an EXISTING page


问:
Executing Multiple Scripts
I've been working on some scripts that pull data from the web in JSON format and convert to CSV files. There are roughly 20 scripts and I'm looking for the best way to run them at once. Right now I just type python script1.py into Windows PowerShell and then repeat. Is there an easy way to go about this?</p>

答:
You could use separate processes to run scripts

it could be helpful to read subprocess module

```<code>import subprocess
for fileName in files:
    subprocess.Popen(['./{}.py'.format(fileName)])
</code>```

Title: Executing Multiple Scripts

Body:
You could use separate processes to run scripts

it could be helpful to read subprocess module

import subprocess
for fileName in files:
    subprocess.Popen(['./{}.py'.format(fileName)])


问:
python xlsxwriter won't align dates
Dates wind up in the bottom right corner of a cell, apparently ignoring alignment settings from xlsxwriter. A MWE:

```<code>import pandas

df = pandas.DataFrame(
    {
        "ints": [1, 2, 3]
        , 'primes': [2, 3, 5]
        , 'odds': [1, 3, 5]
        , 'fechas': ['2017-04-07', '2017-05-09', '2017-11-30']
    }
)

df['fechas'] = pandas.to_datetime(df['fechas']).dt.date

print(df)

xlsx_writer = pandas.ExcelWriter(
    'test.xlsx'
    , engine='xlsxwriter'
    , date_format='mm/dd/yyyy'
)

df.to_excel(xlsx_writer, sheet_name='Sheet1', index=False)
wb = xlsx_writer.book
ws = xlsx_writer.sheets['Sheet1']

dollar_format = '_($* #,##0.00" "_);_($* (#,##0.0);_($* "-"??_);_(@_)'
dollar_format_wb = wb.add_format({'num_format': dollar_format, 'valign': 'vcenter'})
centre_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter'})

ws.set_column('A:A', 25, centre_format_wb)
ws.set_column('B:B', 20, centre_format_wb)
ws.set_column('C:C', 15, centre_format_wb)
ws.set_column('D:D', 10, dollar_format_wb)

# The code below was included to generate the screenshot, but isn't
# strictly necessary for the MWE
shadedrow_format_wb = wb.add_format(
    {
        'bg_color': '#EEEEEE'
        , 'left': 1
        , 'left_color': '#FFFFFF'
    }
)

for r in range(0, 2 + df.shape[0]):
    ws.set_row(r + 1, 45)
    print(r)
    if r % 2 == 0:
        # a kludge as we can't change cell range formats after the fact without re-entering cell contents
        ws.conditional_format('A{:}:D{:}'.format(r, r), {'type': 'no_errors', 'format': shadedrow_format_wb})
        print("\t", r)

xlsx_writer.save()
</code>```

Columns A, B, and C should be centered horizontally, and all rows except the header should be height 45, with all cell contents centered vertically.

Everything works like it should, except for the date column. Is there a good reason that this shouldn't work? Is there a correct way of getting the date centred? Is it a bug? Is there a work-around?

I have also tried formatting the sheet first, and performing the df.to_excel() last, with no effect.

Many thanks!

答:
The issue is that Pandas is applying a cell format for the date and this overrides the column format.

The only way to workaround it would be iterate over the dataframe and write to XlsxWriter directly, applying all the formats that you want.

Title: python xlsxwriter won't align dates

Body:
Dates wind up in the bottom right corner of a cell, apparently ignoring alignment settings from xlsxwriter. A MWE:

import pandas

df = pandas.DataFrame(
    {
        "ints": [1, 2, 3]
        , 'primes': [2, 3, 5]
        , 'odds': [1, 3, 5]
        , 'fechas': ['2017-04-07', '2017-05-09', '2017-11-30']
    }
)

df['fechas'] = pandas.to_datetime(df['fechas']).dt.date

print(df)

xlsx_writer = pandas.ExcelWriter(
    'test.xlsx'
    , engine='xlsxwriter'
    , date_format='mm/dd/yyyy'
)

df.to_excel(xlsx_writer, sheet_name='Sheet1', index=False)
wb = xlsx_writer.book
ws = xlsx_writer.sheets['Sheet1']

dollar_format = '_($* #,##0.00" "_);_($* (#,##0.0);_($* "-"??_);_(@_)'
dollar_format_wb = wb.add_format({'num_format': dollar_format, 'valign': 'vcenter'})
centre_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter'})

ws.set_column('A:A', 25, centre_format_wb)
ws.set_column('B:B', 20, centre_format_wb)
ws.set_column('C:C', 15, centre_format_wb)
ws.set_column('D:D', 10, dollar_format_wb)

# The code below was included to generate the screenshot, but isn't
# strictly necessary for the MWE
shadedrow_format_wb = wb.add_format(
    {
        'bg_color': '#EEEEEE'
        , 'left': 1
        , 'left_color': '#FFFFFF'
    }
)

for r in range(0, 2 + df.shape[0]):
    ws.set_row(r + 1, 45)
    print(r)
    if r % 2 == 0:
        # a kludge as we can't change cell range formats after the fact without re-entering cell contents
        ws.conditional_format('A{:}:D{:}'.format(r, r), {'type': 'no_errors', 'format': shadedrow_format_wb})
        print("\t", r)

xlsx_writer.save()

Columns A, B, and C should be centered horizontally, and all rows except the header should be height 45, with all cell contents centered vertically.

Everything works like it should, except for the date column. Is there a good reason that this shouldn't work? Is there a correct way of getting the date centred? Is it a bug? Is there a work-around?

I have also tried formatting the sheet first, and performing the df.to_excel() last, with no effect.

Many thanks!


问:
C Sorting records from a file
Hi Everyone I am working on a project to sort a file with a large quantity of records based on the given criteria (name or age or gender or hometown) and write to the output file in the format of the original file. However I am debating what is the fastest approach to do so. The file contains records such as:

```<code>Name Age gender hometown
Adam 28  Male   New york
Kevin 42 Male   Boston
...
</code>```

My thought is to read the file and create a linked-list of struct:

```<code>struct record
{
char * SortCriteriaString;
int SortCriteriaInt;
char * Name;
int Age;
char * Gender;
char * Hometown;};
</code>```

and then mersort the linked list based on the criteria I read from command line and store in the SortCriteriaInt or SortCriteriaString members of the struct.

Here is what I plan to do with this project. But I was asked to come up with the fastest sorter possible, so my question is: What are the fastest data structure and sorting algorithm for this task if not the one I described above?

答:
in general, you will not need the sort criteria listed in each instance of the struct, so suggest removing those two fields.

The quickest way to sort, is to not have to perform a 'deep copy' of each of the data fields that are being pointed to by the char* fields.

To avoid a deep copy (and even to avoid a simple copy of the struct instances.  Develop an array of pointers to the struct instances.
Then implement something like a 'qsort()' that performs the comparisons in the fields of the struct instances, and actually only modifying the pointers to those instances.

Then traversing the sorted array by traversing the array of pointers to the struct instances.

Title: C Sorting records from a file

Body:
Hi Everyone I am working on a project to sort a file with a large quantity of records based on the given criteria (name or age or gender or hometown) and write to the output file in the format of the original file. However I am debating what is the fastest approach to do so. The file contains records such as:

Name Age gender hometown
Adam 28  Male   New york
Kevin 42 Male   Boston
...

My thought is to read the file and create a linked-list of struct:

struct record
{
char * SortCriteriaString;
int SortCriteriaInt;
char * Name;
int Age;
char * Gender;
char * Hometown;};

and then mersort the linked list based on the criteria I read from command line and store in the SortCriteriaInt or SortCriteriaString members of the struct.

Here is what I plan to do with this project. But I was asked to come up with the fastest sorter possible, so my question is: What are the fastest data structure and sorting algorithm for this task if not the one I described above?


问:
Query with multiple EXIST
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).

I have the following SELECT statement:

```<code>select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)
</code>```

Is there any way to optimize or making this shorter?

答:
try this (I don't have any DB available to test it, also consider performance )

```<code>select * from
    rooms r,
    (
        select count(distinct id) as cnt, id from equipments  where eq_id in ('eq1','eq2') group by id
    ) as sub
where sub.id = r.id
and sub.cnt >= 2 'Options count
</code>```

Note: 2 - it is the number of options that you need. In example they are: 'eq1','eq2'

Title: Query with multiple EXIST

Body:
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).

I have the following SELECT statement:

select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)

Is there any way to optimize or making this shorter?

Body:
try this (I don't have any DB available to test it, also consider performance )

select * from
    rooms r,
    (
        select count(distinct id) as cnt, id from equipments  where eq_id in ('eq1','eq2') group by id
    ) as sub
where sub.id = r.id
and sub.cnt >= 2 'Options count

Note: 2 - it is the number of options that you need. In example they are: 'eq1','eq2'


问:
"Cannot find name 'IPost'" ServiceStack TypeScript DTOs for Auth Service
I created my Auth Server using the following ServiceStack code:

```<code>Plugins.Add(new AuthFeature(() => new CustomUserSession(),
    new IAuthProvider[] {
        new JwtAuthProvider
        {
            HashAlgorithm = AuthSettings.HashAlgorithm,
            RequireSecureConnection = requireSecureConnection,
            AuthKeyBase64 = AuthSettings.JwtAuthKeyBase64,
            ExpireTokensIn        = TimeSpan.FromHours(_configuration["AuthSettings:ExpireTokensIn"].ToDouble()),
            ExpireRefreshTokensIn = TimeSpan.FromHours(_configuration["AuthSettings:ExpireRefreshTokensIn"].ToDouble()),
            CreatePayloadFilter = (payload,session) => {
                    payload["zipCode"] = ((CustomUserSession)session).ZipCode;
            },
            PopulateSessionFilter = AuthSettings.PopulateSessionFilterImplementation
        },
        new CustomCredentialsAuthProvider((ITsoContext)_serviceProvider.GetService(typeof(ITsoContext))) //HTML Form post of User/Pass
    }));
</code>```

Very straightforward, I then rendered my Typescript "dtos.ts" from my http://runningauthservice/types.

I am using servicestack-client version 0.0.40

This is the first time I have seen IPost in any dtos.ts I render from a ServiceStack api of mine, here is a snippet of my auth dto.ts:

```<code>// @Route("/assignroles")
// @DataContract
export class AssignRoles implements IReturn<AssignRolesResponse>, IPost
{
    // @DataMember(Order=1)
    userName: string;

    // @DataMember(Order=2)
    permissions: string[];

    // @DataMember(Order=3)
    roles: string[];
    createResponse() { return new AssignRolesResponse(); }
    getTypeName() { return "AssignRoles"; }
}
</code>```

And a snippet of the Typescript error in Visual Code:

答: This issue should be resolved with the latest pre-release packages on MyGet. Please review ServiceStack v5 changes before upgrading.</p>

Body:
I created my Auth Server using the following ServiceStack code:

Plugins.Add(new AuthFeature(() => new CustomUserSession(),
    new IAuthProvider[] {
        new JwtAuthProvider
        {
            HashAlgorithm = AuthSettings.HashAlgorithm,
            RequireSecureConnection = requireSecureConnection,
            AuthKeyBase64 = AuthSettings.JwtAuthKeyBase64,
            ExpireTokensIn        = TimeSpan.FromHours(_configuration["AuthSettings:ExpireTokensIn"].ToDouble()),
            ExpireRefreshTokensIn = TimeSpan.FromHours(_configuration["AuthSettings:ExpireRefreshTokensIn"].ToDouble()),
            CreatePayloadFilter = (payload,session) => {
                    payload["zipCode"] = ((CustomUserSession)session).ZipCode;
            },
            PopulateSessionFilter = AuthSettings.PopulateSessionFilterImplementation
        },
        new CustomCredentialsAuthProvider((ITsoContext)_serviceProvider.GetService(typeof(ITsoContext))) //HTML Form post of User/Pass
    }));

Very straightforward, I then rendered my Typescript "dtos.ts" from my http://runningauthservice/types.

I am using servicestack-client version 0.0.40

This is the first time I have seen IPost in any dtos.ts I render from a ServiceStack api of mine, here is a snippet of my auth dto.ts:

// @Route("/assignroles")
// @DataContract
export class AssignRoles implements IReturn<AssignRolesResponse>, IPost
{
    // @DataMember(Order=1)
    userName: string;

    // @DataMember(Order=2)
    permissions: string[];

    // @DataMember(Order=3)
    roles: string[];
    createResponse() { return new AssignRolesResponse(); }
    getTypeName() { return "AssignRoles"; }
}

And a snippet of the Typescript error in Visual Code:


问:
Output of grep isn't line by line
I have this code:

```<code>list=$(ls -l | awk '{print$3,$6,$7,$8,$9}' | grep -v root)
echo $list
</code>```

and the output is a joint version of all the filtered strings which looks like:

```<code>> avahi Nov 16 21:50 1170 syslog Nov 16 21:50 1171 messagebus ...
</code>```

and what I wanted looks like:

```<code>> avahi Nov 16 21:50 1170
> syslog Nov 16 21:50 1171
> messagebus Nov 16 21:50 1179
> ...
</code>```

I've also read that the default output of grep should give me the paragraphs version like what I want but this isn't the case. What am I doing wrong?

答:
Given:

```<code>$ txt="line 1
> line 2
> line 3
> line 4"
</code>```

(ie, txt being set to line 1\nline 2\nline 3\nline 4)

Consider:

```<code>$ echo $txt
line 1 line 2 line 3 line 4
</code>```

vs:

```<code>$ echo "$txt"
line 1
line 2
line 3
line 4
</code>```

Use quotes or Bash will interpret and split the whitespace (like the \n at the end of lines.)

Separately, it is usually not a good idea to try and parse the output of ls since file names can have spaces in them. The spaces in the file names will break the rest of your pipe (as you have written it.)

Use a loop with a glob instead.

Title: Output of grep isn't line by line

Body:
I have this code:

list=$(ls -l | awk '{print$3,$6,$7,$8,$9}' | grep -v root)
echo $list

and the output is a joint version of all the filtered strings which looks like:

> avahi Nov 16 21:50 1170 syslog Nov 16 21:50 1171 messagebus ...

and what I wanted looks like:

> avahi Nov 16 21:50 1170
> syslog Nov 16 21:50 1171
> messagebus Nov 16 21:50 1179
> ...

I've also read that the default output of grep should give me the paragraphs version like what I want but this isn't the case. What am I doing wrong?

Body:
Given:

$ txt="line 1
> line 2
> line 3
> line 4"

(ie, txt being set to line 1\nline 2\nline 3\nline 4)

Consider:

$ echo $txt
line 1 line 2 line 3 line 4

vs:

$ echo "$txt"
line 1
line 2
line 3
line 4

Use quotes or Bash will interpret and split the whitespace (like the \n at the end of lines.)

Separately, it is usually not a good idea to try and parse the output of ls since file names can have spaces in them. The spaces in the file names will break the rest of your pipe (as you have written it.)

Use a loop with a glob instead.


问:
Google spreadsheet search for part ,replace and delete
I'm trying to start a project using Tasker(an app developed for android) It has lots of useful plugins and I have stumbled upon google spreadsheet plugin.
With this plugin i can easily read from a spreadsheet.

But my problem is writing into the spreadsheet. I want to use the spreadsheet as a database for my tasker app.

This means it will write simple values to the Spreadsheet examples

A2 = Nexus5/off:1:8:1

A3 = Nexus6/on:2:3:4

I am now trying to script a search and replace within google scripts. And im getting stuck.

What i want it to do is if my Nexus5 turns on it will send to the spreadsheet in A1 Nexus5/on:1:8:1.

The script has to search for Nexus5/ in column A and replace the cell value with the new value. After that it has to delete A1 so new input can be put in. Beneath is the script i got so far it can search for an input I put in A1 and replace it in the list with test. But I can't seem to get it search just for the first part.

function replaceInSheet(sheet, to_replace, replace_with) {
  //get the current data range values as an array
    var values = sheet.getDataRange().getValues();
  //loop over the rows in the array
  for(var row in values){
    //use Array.map to execute a replace call on each of the cells in the row.
    var replaced_values = values[row].map(function(original_value){
      return original_value.toString().replace(to_replace,replace_with);
    });
    //replace the original row values with the replaced values
    values[row] = replaced_values;
  }
  //write the updated values to the sheet
  sheet.getDataRange().setValues(values);
}
function onChange(e){
  var sheet = SpreadsheetApp.getActiveSheet()
  replaceInSheet(sheet,val,'test');
}
```

答:
You want to use regexes to crack this nut. There is a comprehensive set of answers here.

In short, set your search to /^Nexus5\// (either with that raw regex declaration, or creating a new RegExp() object) & just use string.replace(), then write the updated values back as required.

e.g.

```<code>var myString = “Nexus5/1.2.3”;
var newValue = myString.replace(/^nexus5\/.+/i, “my new value”);
</code>```

So, here we’re looking for a string beginning with “Nexus5/“ & replacing it with “my new value”. (^ anchors the search to the beginning of the string, .+ means 1 or more characters other than a line-end, we need to escape the slash - \/ - so it’s not interpreted as the end of the regex & the i after the pattern sets the search to case-insensitive.) We can now write newValue back to the source sheet however you need using the range.setValue() or range.setValues() method of the spreadsheet.

Body:
You want to use regexes to crack this nut. There is a comprehensive set of answers here.

In short, set your search to /^Nexus5\// (either with that raw regex declaration, or creating a new RegExp() object) & just use string.replace(), then write the updated values back as required.

e.g.

var myString = “Nexus5/1.2.3”;
var newValue = myString.replace(/^nexus5\/.+/i, “my new value”);

So, here we’re looking for a string beginning with “Nexus5/“ & replacing it with “my new value”. (^ anchors the search to the beginning of the string, .+ means 1 or more characters other than a line-end, we need to escape the slash - \/ - so it’s not interpreted as the end of the regex & the i after the pattern sets the search to case-insensitive.) We can now write newValue back to the source sheet however you need using the range.setValue() or range.setValues() method of the spreadsheet.


问:
Add json object to php array
I have two arrays, or so I thought. One passes a Javascript object to php via a POST, the other gets data from a JS API which returns another object. I want to join both of these arrays. Here's the sample data and how it is obtained.

Name array which I get from API:-

```<code>array(5) { [0]=> string(1) "D" [1]=> string(1) "a" [2]=> string(1) "v" [3]=> string(1) "i" [4]=> string(1) "d" }
</code>```

User array which is POST'd to my php script:-

```<code>array (
  'userID' => '12345',
  'time' => 'Monday 26th June 2017 22:12:37 AM',
)
</code>```

Now I use the following to (try) and get both of these pieces of data into the same array to log to a file.

```<code>$nameoriginal = file_get_contents("/api");
$namejson = json_decode($name);

$user = var_export($_POST, true);

$detailstolog = $namejson + $user;

file_put_contents('/logs/names.log', $detailstolog);
</code>```

However, I get a php error which states the first argument is not a valid array (i.e. $name is not valid). Why is this? What can I do to 'make' it an array?

I think the name 'array' is actually a string, hence the error. How do I make this an array, and is $array1 + $array2 the best way to do this?

I am trying to create something like:-

```<code>array (
  'name' => 'david',
  'userID' => '12345',
  'time' => 'Monday 26th June 2017 22:12:37 AM',
)
</code>```

Thanks for any help you can provide!

答:
Sorry, but I don't understand where is JSON involved here, you're dealing with arrays, hence no need to decode anything from JSON.

The first array seems to be the word "David" split into chars. Then you just need to implode it and add it to your detailstolog array as the first element:

```<code>$detailstolog['name'] = implode("", $nameoriginal); // David
$detailstolog += $_POST;
</code>```

Title: Add json object to php array

Body:
I have two arrays, or so I thought. One passes a Javascript object to php via a POST, the other gets data from a JS API which returns another object. I want to join both of these arrays. Here's the sample data and how it is obtained.

Name array which I get from API:-

array(5) { [0]=> string(1) "D" [1]=> string(1) "a" [2]=> string(1) "v" [3]=> string(1) "i" [4]=> string(1) "d" }

User array which is POST'd to my php script:-

array (
  'userID' => '12345',
  'time' => 'Monday 26th June 2017 22:12:37 AM',
)

Now I use the following to (try) and get both of these pieces of data into the same array to log to a file.

$nameoriginal = file_get_contents("/api");
$namejson = json_decode($name);

$user = var_export($_POST, true);

$detailstolog = $namejson + $user;

file_put_contents('/logs/names.log', $detailstolog);

However, I get a php error which states the first argument is not a valid array (i.e. $name is not valid). Why is this? What can I do to 'make' it an array?

I think the name 'array' is actually a string, hence the error. How do I make this an array, and is $array1 + $array2 the best way to do this?

I am trying to create something like:-

array (
  'name' => 'david',
  'userID' => '12345',
  'time' => 'Monday 26th June 2017 22:12:37 AM',
)

Thanks for any help you can provide!

Body:
Sorry, but I don't understand where is JSON involved here, you're dealing with arrays, hence no need to decode anything from JSON.

The first array seems to be the word "David" split into chars. Then you just need to implode it and add it to your detailstolog array as the first element:

$detailstolog['name'] = implode("", $nameoriginal); // David
$detailstolog += $_POST;


问:
Is it I/O manipulators that provide the functionality of << and >>?
I have read about I/O manipulators and have thereof been a little confused.It is stated that it is because of these manipulators that we are able to control streams using << and >>. I am not quite sure why, but I have always thought that is was objects, such as std::cout, that controlled the functionality of operators, such as <<.

How is it even possible that functions, since I/O manipulators allegedly are functions, can overload/define operators? :/

Being specific, they state the following for manipulators taking arguments:

These manipulators define their own operator<< or operator>> which
  perform the requested manipulation.

If this is true - that it is not the objects (the classes that they belong to), but these helper functions that control the operators << and >> - how it is known what to do in the following statement?

```<code>std::cout << "static constructor\n";
</code>```

答:
The standard input and output stream classes (std::basic_istream and std::basic_ostream) overload member and non-member operator>>() and operator<<() functions. Those are the functions that perform the actual I/O. Manipulators are functions like std::endl, std::left, std::right, std::boolalpha, etc. They merely complement the functionality provided by the I/O operator functions. They allow us to control certain properties of the I/O operation like floating point representation, field width, fill characters, and so on.

In regards to the example you provided:

```<code>std::cout << "static constructor\n";
</code>```

This calls the non-member function ostream& operator<<(ostream&, const char*); which does the actual output of the string.

A manipulator can be defined like this:

```<code>std::ostream& print_1_to_10( std::ostream& os ) {
  for (int i = 1; i <= 10; i++) {
    os << to_string(i);
  }
}
</code>```

The standard stream classes have member overloads of operator>>() and operator<<() which take as an argument a pointer to a function with the above signature. Basically it goes like:

```<code>std::ostream& std::ostream::operator<<(std::ostream&(*pf)(std::ostream&)) {
  pf(*this);
  return *this;
}
</code>```

This allows us to do:

```<code>std::cout << print_1_to_10;
</code>```

which is what allows manipulators to work.

So in summary, manipulators are simply helper functions that facilitate certain kinds of operations.

There is also the case where you might want something that resembles a manipulator, but in addition you want to pass arguments to this manipulator (i.e std::cout << print_1_to(10)). In that case it is customary to create a class that contains an overloaded operator<<() or operator>>() depending on what you want to do.

```<code>struct print_1_to {
  int n;
  print_1_to(int n) : n(n) {}
  friend std::ostream& operator<<(std::ostream& os, print_1_to const& p) {
    for (int i = 1; i <= p.n; i++) {
      os << to_string(i);
    }
    return os;
  }
};
</code>```

Body:
I have read about I/O manipulators and have thereof been a little confused.It is stated that it is because of these manipulators that we are able to control streams using << and >>. I am not quite sure why, but I have always thought that is was objects, such as std::cout, that controlled the functionality of operators, such as <<.

How is it even possible that functions, since I/O manipulators allegedly are functions, can overload/define operators? :/

Being specific, they state the following for manipulators taking arguments:

These manipulators define their own operator<< or operator>> which
  perform the requested manipulation.

If this is true - that it is not the objects (the classes that they belong to), but these helper functions that control the operators << and >> - how it is known what to do in the following statement?

std::cout << "static constructor\n";

Body:
The standard input and output stream classes (std::basic_istream and std::basic_ostream) overload member and non-member operator>>() and operator<<() functions. Those are the functions that perform the actual I/O. Manipulators are functions like std::endl, std::left, std::right, std::boolalpha, etc. They merely complement the functionality provided by the I/O operator functions. They allow us to control certain properties of the I/O operation like floating point representation, field width, fill characters, and so on.

In regards to the example you provided:

std::cout << "static constructor\n";

This calls the non-member function ostream& operator<<(ostream&, const char*); which does the actual output of the string.

A manipulator can be defined like this:

std::ostream& print_1_to_10( std::ostream& os ) {
  for (int i = 1; i <= 10; i++) {
    os << to_string(i);
  }
}

The standard stream classes have member overloads of operator>>() and operator<<() which take as an argument a pointer to a function with the above signature. Basically it goes like:

std::ostream& std::ostream::operator<<(std::ostream&(*pf)(std::ostream&)) {
  pf(*this);
  return *this;
}

This allows us to do:

std::cout << print_1_to_10;

which is what allows manipulators to work.

So in summary, manipulators are simply helper functions that facilitate certain kinds of operations.

There is also the case where you might want something that resembles a manipulator, but in addition you want to pass arguments to this manipulator (i.e std::cout << print_1_to(10)). In that case it is customary to create a class that contains an overloaded operator<<() or operator>>() depending on what you want to do.

struct print_1_to {
  int n;
  print_1_to(int n) : n(n) {}
  friend std::ostream& operator<<(std::ostream& os, print_1_to const& p) {
    for (int i = 1; i <= p.n; i++) {
      os << to_string(i);
    }
    return os;
  }
};