问:
Why are acr.UserDialogs.Toast messages in my Xamarin.Forms app being truncated on devices?
We are using the acr.UserDialogs library to display Toasts on our Xamarin.Forms app. The messages are never more than a sentence long. In Android, the messages display fine, and the Toast will adjust size for the length of the message. Our QA tech realized that in iOS the messages were being truncated.

For example, the Toast

```<code>Title: "Connection Restored"
Message: "Your connection has been reestablished"
</code>```

is truncated to

```<code>Title: "Connection"
Message: "Your connection has been"
</code>```

when displayed on the device.

I tried changing the message to "Reconnected!" and all we see is "Reconnect"

The simulator on my Mac does not have this issue. I can see the whole message.

EDIT: I should point out that I we are using version 4.1.4 of the Acr.UserDialogs library and 2.2.0.45 for Xamarin.Forms

答:
Why? More than likely it's a bug with the library. But I assume you're also interested in a work-around.  Here's what's working for me: Just pad the string you want to display with spaces. I choose the same number of spaces as the number of characters in the original string.  So when the string is truncated in half, the remaining is what what you want to show in the first place (the part that's gets truncated is the one that contains spaces).

Let's say you want to display

```<code>"Connection"
</code>```

you might get

```<code>"Conne"
</code>```

So if you start with

```<code>"Connection          "
</code>```

you would end up with

```<code>"Connection"
</code>```

Silly, yes, but some work-arounds are.

Body:
We are using the acr.UserDialogs library to display Toasts on our Xamarin.Forms app. The messages are never more than a sentence long. In Android, the messages display fine, and the Toast will adjust size for the length of the message. Our QA tech realized that in iOS the messages were being truncated.

For example, the Toast

Title: "Connection Restored"
Message: "Your connection has been reestablished"

is truncated to

Title: "Connection"
Message: "Your connection has been"

when displayed on the device.

I tried changing the message to "Reconnected!" and all we see is "Reconnect"

The simulator on my Mac does not have this issue. I can see the whole message.

EDIT: I should point out that I we are using version 4.1.4 of the Acr.UserDialogs library and 2.2.0.45 for Xamarin.Forms

Body:
Why? More than likely it's a bug with the library. But I assume you're also interested in a work-around.  Here's what's working for me: Just pad the string you want to display with spaces. I choose the same number of spaces as the number of characters in the original string.  So when the string is truncated in half, the remaining is what what you want to show in the first place (the part that's gets truncated is the one that contains spaces).

Let's say you want to display

"Connection"

you might get

"Conne"

So if you start with

"Connection          "

you would end up with

"Connection"

Silly, yes, but some work-arounds are.


来源: stackexchange

问:
Make a data frame from a list of sequences
With a list of sequences, for example,

```<code>datList <- list(One = seq(1,5, length.out = 20),
                Two = seq(1,10, length.out = 20),
                Three = seq(5,50, length.out = 20))
</code>```

Is it possible to make a data frame so that the sequences are converted into columns. As in,

```<code>datDF <- data.frame(One = datList[[1]], Two = datList[[2]], Three = datList[[3]] )

> head(datDF)
       One      Two     Three
1 1.000000 1.000000  5.000000
2 1.210526 1.473684  7.368421
3 1.421053 1.947368  9.736842
4 1.631579 2.421053 12.105263
5 1.842105 2.894737 14.473684
6 2.052632 3.368421 16.842105
</code>```

Within the context of my 'real' data I am working with many sequences and was hoping an apply (or similar) function could be used rather than manually creating the desired data frame.

答:
We can use data.frame

```<code>datDFN <- data.frame(datList)
identical(datDF, datDFN)
#[1] TRUE
</code>```

ContentLicense: CC BY-SA 3.0

Body:
With a list of sequences, for example,

datList <- list(One = seq(1,5, length.out = 20),
                Two = seq(1,10, length.out = 20),
                Three = seq(5,50, length.out = 20))

Is it possible to make a data frame so that the sequences are converted into columns. As in,

datDF <- data.frame(One = datList[[1]], Two = datList[[2]], Three = datList[[3]] )

> head(datDF)
       One      Two     Three
1 1.000000 1.000000  5.000000
2 1.210526 1.473684  7.368421
3 1.421053 1.947368  9.736842
4 1.631579 2.421053 12.105263
5 1.842105 2.894737 14.473684
6 2.052632 3.368421 16.842105

Within the context of my 'real' data I am working with many sequences and was hoping an apply (or similar) function could be used rather than manually creating the desired data frame.

Body:
We can use data.frame

datDFN <- data.frame(datList)
identical(datDF, datDFN)
#[1] TRUE


问:
Lodash search array item in other array item
Hello i'm using lodash library.

I want to search if phone in receivedMessagesMock is in contactsMocks phone

If receivedMessagesMock.phone === contactsMocks.phoneNumbers.value I need to push the contactsMocks.name.formatted in the same receivedMessagesMock position.

Something like

```<code>if(receivedMessagesMock[0].phone === contactsMocks.phoneNumbers.value {
 receivedMessagesMock[0].name = contactsMocks.name.formatted;
}
</code>```

The contactMock and receivedMessagesMock

```<code>var contactsMock = [{'id':'1','rawId':'1','displayName':'Asd','name':{'givenName':'Asd','formatted':'Asd'},'nickname':null,'phoneNumbers':[{'id':'1','pref':false,'value':'000000000','type':'mobile', 'loggedInSystem':true}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'2','rawId':'2','displayName':'Bbb','name':{'givenName':'Bbb','formatted':'Bbb'},'nickname':null,'phoneNumbers':[{'id':'3','pref':false,'value':'565 65 65 65','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'3','rawId':'3','displayName':'Ccc','name':{'givenName':'Ccc','formatted':'Ccc'},'nickname':null,'phoneNumbers':[{'id':'5','pref':false,'value':'0000000001','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'4','rawId':'4','displayName':'Ddd','name':{'givenName':'Ddd','formatted':'Ddd'},'nickname':null,'phoneNumbers':[{'id':'6','pref':false,'value':'000 00 00 01','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null}];

    var receivedMessagesMock = [{
        'id': 12,
        'phone': '000 00 00 01',
        'time': '15:44',
        'priority': 1,
        'response' : false
    },{
        'id': 15,
        'phone': '000 00 00 01',
        'time': '15:44',
        'priority': 1,
        'response' : false
    },{
        'id': 16,
        'phone': '000 00 00 01',
        'time': '15:44',
        'priority': 2,
        'response' : true
    }
    ];
</code>```

答:
This is one way to do this using lodash:

```<code>lodash.map(receivedMessagesMock, function(rmm) {
  var foundContact = lodash.find(contactsMock, function(cm) {
    return lodash.find(cm.phoneNumbers, function(pn) {
      return pn.value == rmm.phone;
    });
  });
  if (foundContact) {
    rmm.names = foundContact.name.formatted
  }
  return rmm;
});
</code>```

Keep in mind, you asked for a name (singular) to be inserted into the received messages. This means that if two or more contacts in the list have the same number, for whatever reason, the above will always return the first match. But there is a real possibility that there will be more than one match, so it might be appropriate to insert an array of names.

```<code>lodash.map(receivedMessagesMock, function(rmm) {
  var foundContacts = lodash.filter(contactsMock, function(cm) {
    return lodash.find(cm.phoneNumbers, function(pn) {
      return pn.value == rmm.phone;
    });
  });
  if (foundContacts.length > 0) {
    rmm.names = lodash.map(foundContacts, function(fcs) {
      return name.formatted
    });
  }
  return rmm;
});
</code>```

Body:
Hello i'm using lodash library.

I want to search if phone in receivedMessagesMock is in contactsMocks phone

If receivedMessagesMock.phone === contactsMocks.phoneNumbers.value I need to push the contactsMocks.name.formatted in the same receivedMessagesMock position.

Something like

if(receivedMessagesMock[0].phone === contactsMocks.phoneNumbers.value {
 receivedMessagesMock[0].name = contactsMocks.name.formatted;
}

The contactMock and receivedMessagesMock

var contactsMock = [{'id':'1','rawId':'1','displayName':'Asd','name':{'givenName':'Asd','formatted':'Asd'},'nickname':null,'phoneNumbers':[{'id':'1','pref':false,'value':'000000000','type':'mobile', 'loggedInSystem':true}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'2','rawId':'2','displayName':'Bbb','name':{'givenName':'Bbb','formatted':'Bbb'},'nickname':null,'phoneNumbers':[{'id':'3','pref':false,'value':'565 65 65 65','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'3','rawId':'3','displayName':'Ccc','name':{'givenName':'Ccc','formatted':'Ccc'},'nickname':null,'phoneNumbers':[{'id':'5','pref':false,'value':'0000000001','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null},{'id':'4','rawId':'4','displayName':'Ddd','name':{'givenName':'Ddd','formatted':'Ddd'},'nickname':null,'phoneNumbers':[{'id':'6','pref':false,'value':'000 00 00 01','type':'mobile'}],'emails':null,'addresses':null,'ims':null,'organizations':null,'birthday':null,'note':null,'photos':null,'categories':null,'urls':null}];

    var receivedMessagesMock = [{
        'id': 12,
        'phone': '000 00 00 01',
        'time': '15:44',
        'priority': 1,
        'response' : false
    },{
        'id': 15,
        'phone': '000 00 00 01',
        'time': '15:44',
        'priority': 1,
        'response' : false
    },{
        'id': 16,
        'phone': '000 00 00 01',
        'time': '15:44',
        'priority': 2,
        'response' : true
    }
    ];

Body:
This is one way to do this using lodash:

lodash.map(receivedMessagesMock, function(rmm) {
  var foundContact = lodash.find(contactsMock, function(cm) {
    return lodash.find(cm.phoneNumbers, function(pn) {
      return pn.value == rmm.phone;
    });
  });
  if (foundContact) {
    rmm.names = foundContact.name.formatted
  }
  return rmm;
});

Keep in mind, you asked for a name (singular) to be inserted into the received messages. This means that if two or more contacts in the list have the same number, for whatever reason, the above will always return the first match. But there is a real possibility that there will be more than one match, so it might be appropriate to insert an array of names.

lodash.map(receivedMessagesMock, function(rmm) {
  var foundContacts = lodash.filter(contactsMock, function(cm) {
    return lodash.find(cm.phoneNumbers, function(pn) {
      return pn.value == rmm.phone;
    });
  });
  if (foundContacts.length > 0) {
    rmm.names = lodash.map(foundContacts, function(fcs) {
      return name.formatted
    });
  }
  return rmm;
});


问:
Performance issues with Redshift Spectrum
I am using Redhshift spectrum. I created an external table and uploaded a csv data file on S3 with around 5.5 million records. If fire a query on this external table, it is taking ~15 seconds whereas If I run same query on Amazon redshift, I was getting same result in ~2 seconds. What could be the reason for this performance lag where AWS claim it to be be very high performance platform. Please suggest solution for same performance using spectrum.</p>

答:
For your performance optimizations please have a look to understand your query.

Right now, the best performance is if you don't have a single CSV file but multiple. Typically, you could say you get great performance if the number of files per query is at least about an order of magnitude larger than the number of nodes of your cluster.

In addition, if you use Parquet files you get the advantage of a columnar format on S3 rather than reading CSV which will read the whole file from S3 - and decreases your cost as well.

You can use the script to convert data to Parquet:

ContentLicense: CC BY-SA 4.0


问:
Find Overlapping Dates and Return Overlapping Records
What I need is to return all records that may overlap each other.

```<code>-- Create Temp Table
CREATE TABLE #Overlap

(SubType varchar(50),
Cause varchar(9),
CircuitID varchar(100),
BegDate date,
EndDate date,
AmtSought decimal(11,2),
Remarks varchar(max))

--Insert records

INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-12-01','2016-12-31',354.41,'Rec 1')
INSERT INTO #Overlap VALUES('Original','201500009','36/VCID/826061/IP/NUVX','2016-08-11','2016-08-12',200.50,'Rec 2')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-11-15','2016-12-14',100.25,'Rec 3')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-12-16','2017-01-15',300.75,'Rec 4')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2017-01-01','2017-01-01',500.00,'Rec 5')
INSERT INTO #Overlap VALUES('Original','201500009','36/VCID/826061/IP/NUVX','2016-07-01','2016-07-31',100.50,'Rec 6')
</code>```

My result would look like:

```<code>SubType   Cause     CircuitID                  BegDate    EndDate    AmtSought Remarks
------------------- -------------------------- ---------- ---------- --------- --------
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-11-15 2016-12-14 100.25    Rec 3
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-12-01 2016-12-31 354.41    Rec 1
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-12-16 2017-01-15 300.75    Rec 4
Original  201500018 36/KQ--/831670/IP /NUVX/   2017-01-01 2017-01-01 500.00    Rec 5
</code>```

I have tried this from a sample code I saw but it is not returning the desired result.

```<code>Select * from #Overlap a
Inner Join #Overlap b
on a.SubType = b.SubType
And a.Cause = b.Cause
And a.CircuitID = b.CircuitID
And b.BegDate between a.BegDate and a.endDate
And b.BegDate < a.endDate
</code>```

答:
You need to check start overlap and end overlap. In case, startdate is always less than endDate, following query can be used. The CTE is not required if you have some primary key:</p>

```<code>; WITH CTE AS
(
    SELECT *,
    ROW_NUMBER() OVER(
            PARTITION BY (SELECT NULL)
            ORDER BY (SELECT NULL)
    ) AS pk FROM #Overlap
)
SELECT a.*, b.pk, b.BegDate, b.endDate FROM CTE a
CROSS JOIN CTE b
WHERE -- Simplify by adding PK
(a.pk <> b.pk)
AND (CASE WHEN (a.BegDate > b.BegDate) THEN a.BegDate ELSE b.BegDate END)
 <= (CASE WHEN (a.endDate < b.endDate) THEN a.endDate ELSE b.endDate END)
</code>```

Body:
What I need is to return all records that may overlap each other.

-- Create Temp Table
CREATE TABLE #Overlap

(SubType varchar(50),
Cause varchar(9),
CircuitID varchar(100),
BegDate date,
EndDate date,
AmtSought decimal(11,2),
Remarks varchar(max))

--Insert records

INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-12-01','2016-12-31',354.41,'Rec 1')
INSERT INTO #Overlap VALUES('Original','201500009','36/VCID/826061/IP/NUVX','2016-08-11','2016-08-12',200.50,'Rec 2')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-11-15','2016-12-14',100.25,'Rec 3')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-12-16','2017-01-15',300.75,'Rec 4')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2017-01-01','2017-01-01',500.00,'Rec 5')
INSERT INTO #Overlap VALUES('Original','201500009','36/VCID/826061/IP/NUVX','2016-07-01','2016-07-31',100.50,'Rec 6')

My result would look like:

SubType   Cause     CircuitID                  BegDate    EndDate    AmtSought Remarks
------------------- -------------------------- ---------- ---------- --------- --------
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-11-15 2016-12-14 100.25    Rec 3
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-12-01 2016-12-31 354.41    Rec 1
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-12-16 2017-01-15 300.75    Rec 4
Original  201500018 36/KQ--/831670/IP /NUVX/   2017-01-01 2017-01-01 500.00    Rec 5

I have tried this from a sample code I saw but it is not returning the desired result.

Select * from #Overlap a
Inner Join #Overlap b
on a.SubType = b.SubType
And a.Cause = b.Cause
And a.CircuitID = b.CircuitID
And b.BegDate between a.BegDate and a.endDate
And b.BegDate < a.endDate

Body:
You need to check start overlap and end overlap. In case, startdate is always less than endDate, following query can be used. The CTE is not required if you have some primary key:

; WITH CTE AS
(
    SELECT *,
    ROW_NUMBER() OVER(
            PARTITION BY (SELECT NULL)
            ORDER BY (SELECT NULL)
    ) AS pk FROM #Overlap
)
SELECT a.*, b.pk, b.BegDate, b.endDate FROM CTE a
CROSS JOIN CTE b
WHERE -- Simplify by adding PK
(a.pk <> b.pk)
AND (CASE WHEN (a.BegDate > b.BegDate) THEN a.BegDate ELSE b.BegDate END)
 <= (CASE WHEN (a.endDate < b.endDate) THEN a.endDate ELSE b.endDate END)


问:
Group by multiple columns in dplyr, using string vector input
I'm trying to transfer my understanding of plyr into dplyr, but I can't figure out how to group by multiple columns.

```<code># make data with weird column names that can't be hard coded
data = data.frame(
  asihckhdoydkhxiydfgfTgdsx = sample(LETTERS[1:3], 100, replace=TRUE),
  a30mvxigxkghc5cdsvxvyv0ja = sample(LETTERS[1:3], 100, replace=TRUE),
  value = rnorm(100)
)

# get the columns we want to average within
columns = names(data)[-3]

# plyr - works
ddply(data, columns, summarize, value=mean(value))

# dplyr - raises error
data %.%
  group_by(columns) %.%
  summarise(Value = mean(value))
#> Error in eval(expr, envir, enclos) : index out of bounds
</code>```

What am I missing to translate the plyr example into a dplyr-esque syntax?

Edit 2017: Dplyr has been updated, so a simpler solution is available. See the currently selected answer.

答:
Since this question was posted, dplyr added scoped versions of group_by (documentation here). This lets you use the same functions you would use with select, like so:

```<code>data = data.frame(
    asihckhdoydkhxiydfgfTgdsx = sample(LETTERS[1:3], 100, replace=TRUE),
    a30mvxigxkghc5cdsvxvyv0ja = sample(LETTERS[1:3], 100, replace=TRUE),
    value = rnorm(100)
)

# get the columns we want to average within
columns = names(data)[-3]

library(dplyr)
df1 <- data %>%
  group_by_at(vars(one_of(columns))) %>%
  summarize(Value = mean(value))

#compare plyr for reference
df2 <- plyr::ddply(data, columns, plyr::summarize, value=mean(value))
table(df1 == df2, useNA = 'ifany')
## TRUE
##  27
</code>```

The output from your example question is as expected (see comparison to plyr above and output below):

```<code># A tibble: 9 x 3
# Groups:   asihckhdoydkhxiydfgfTgdsx [?]
  asihckhdoydkhxiydfgfTgdsx a30mvxigxkghc5cdsvxvyv0ja       Value
                     <fctr>                    <fctr>       <dbl>
1                         A                         A  0.04095002
2                         A                         B  0.24943935
3                         A                         C -0.25783892
4                         B                         A  0.15161805
5                         B                         B  0.27189974
6                         B                         C  0.20858897
7                         C                         A  0.19502221
8                         C                         B  0.56837548
9                         C                         C -0.22682998
</code>```

Note that since dplyr::summarize only strips off one layer of grouping at a time, you've still got some grouping going on in the resultant tibble (which can sometime catch people by suprise later down the line). If you want to be absolutely safe from unexpected grouping behavior, you can always add %>% ungroup to your pipeline after you summarize.

Body:
I'm trying to transfer my understanding of plyr into dplyr, but I can't figure out how to group by multiple columns.

# make data with weird column names that can't be hard coded
data = data.frame(
  asihckhdoydkhxiydfgfTgdsx = sample(LETTERS[1:3], 100, replace=TRUE),
  a30mvxigxkghc5cdsvxvyv0ja = sample(LETTERS[1:3], 100, replace=TRUE),
  value = rnorm(100)
)

# get the columns we want to average within
columns = names(data)[-3]

# plyr - works
ddply(data, columns, summarize, value=mean(value))

# dplyr - raises error
data %.%
  group_by(columns) %.%
  summarise(Value = mean(value))
#> Error in eval(expr, envir, enclos) : index out of bounds

What am I missing to translate the plyr example into a dplyr-esque syntax?

Edit 2017: Dplyr has been updated, so a simpler solution is available. See the currently selected answer.

Body:
Since this question was posted, dplyr added scoped versions of group_by (documentation here). This lets you use the same functions you would use with select, like so:

data = data.frame(
    asihckhdoydkhxiydfgfTgdsx = sample(LETTERS[1:3], 100, replace=TRUE),
    a30mvxigxkghc5cdsvxvyv0ja = sample(LETTERS[1:3], 100, replace=TRUE),
    value = rnorm(100)
)

# get the columns we want to average within
columns = names(data)[-3]

library(dplyr)
df1 <- data %>%
  group_by_at(vars(one_of(columns))) %>%
  summarize(Value = mean(value))

#compare plyr for reference
df2 <- plyr::ddply(data, columns, plyr::summarize, value=mean(value))
table(df1 == df2, useNA = 'ifany')
## TRUE
##  27

The output from your example question is as expected (see comparison to plyr above and output below):

# A tibble: 9 x 3
# Groups:   asihckhdoydkhxiydfgfTgdsx [?]
  asihckhdoydkhxiydfgfTgdsx a30mvxigxkghc5cdsvxvyv0ja       Value
                     <fctr>                    <fctr>       <dbl>
1                         A                         A  0.04095002
2                         A                         B  0.24943935
3                         A                         C -0.25783892
4                         B                         A  0.15161805
5                         B                         B  0.27189974
6                         B                         C  0.20858897
7                         C                         A  0.19502221
8                         C                         B  0.56837548
9                         C                         C -0.22682998

Note that since dplyr::summarize only strips off one layer of grouping at a time, you've still got some grouping going on in the resultant tibble (which can sometime catch people by suprise later down the line). If you want to be absolutely safe from unexpected grouping behavior, you can always add %>% ungroup to your pipeline after you summarize.


问:
Ajax post request results to Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
Ok, this is my first time to post here so if you see that I need to correct something please tell me.

I'm having problem when I try to post data to an api using ajax. I am using tomcat8 as my web server. I added the @CrossOrigin annotation in my controller which were suggested by others. I also added the localhost:9000 as allowed-origin and Authorization in allowed-headers in my servlet.xml but still no success.

This is my ajax code:

```<code>var my_url = "http://localhost:8088/booking/api/saveTransaction";
var username = "user111";
var password = "userpass111";

              $.ajax({
                  method: "POST",
                  url: my_url,
                  dataType: "json",
                  headers: {
                    'Authorization':'Basic ' + btoa(username+":"+password),
                    'Content-Type':'x-www-form-urlencoded'
                  },
                  data: JSON.stringify(my_data),
                  success: function(data){
                    alert(data);
                  },
                  error: function(xhr, status, error){
                    alert(xhr);
                    alert(status);
                    alert(error);
                  }
              });
</code>```

In my Controller

```<code>@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping(value = "/api/saveTransaction", method = RequestMethod.POST)
public ResponseEntity<BiyaheApplicationResult> saveTransaction(Authentication authentication, @RequestBody CompanyTransaction transaction) {

    System.out.println("\n\n");
    System.out.println("START-SAVE-TRANSACTION");
    System.out.println("\n\n");

    BiyaheApplicationResult result = null;

    if(null != transaction) transaction.setTransactionDate(new Date());

    System.out.println("\n\n");
    System.out.println("TEST: SAVE-JSON-TRANSACTION");
    System.out.println("--------------------------------------------");
    System.out.println("[transaction]: " + BiyaheTextFormatter.serializeToJson(transaction));
    System.out.println("--------------------------------------------");
    System.out.println("\n\n");

    String username = authentication.getName();
    User user = this.userService.findUserByUsername(username);
    UserProfileView profile = this.userProfileViewService.getUserProfileViewById(user.getId());

    int companyId = -1;
    int branchId = -1;
    String loadingScheme = null;
    if(null != profile){
        if(BiyaheConstants.JGGC_HQ_COMPANY_ID < profile.getCompanyId()){
            companyId = profile.getCompanyId();
            CompanyConfiguration conf = this.companyConfigurationService.getCompanyConfigurationByCompanyId(companyId);
            loadingScheme = conf.getLoadingScheme();
        }

        if(BiyaheConstants.JGGC_HQ_BRANCH_ID < profile.getBranchId()){
            branchId = profile.getBranchId();
        }
    }

    double currentLoad = 0;

    boolean isSufficientLoad = false;
    if(BiyaheConstants.LOADING_SCHEME_CENTRALIZED.equalsIgnoreCase(loadingScheme)){
        CompanyLoadInfo coLoadInfo = this.companyLoadInfoService.getCompanyLoadInfoByCompanyId(companyId);
        if(null != coLoadInfo) {
            currentLoad = coLoadInfo.getCentralizeLoadAmount();
            isSufficientLoad = coLoadInfo.getCentralizeLoadAmount() > transaction.getTotalAmount();
        }
    }
    else if(BiyaheConstants.LOADING_SCHEME_DISTRIBUTED.equalsIgnoreCase(loadingScheme)){
        BranchLoadInfo branchLoadInfo = this.branchLoadInfoService.getBranchLoadInfoByBranchId(branchId);
        if(null != branchLoadInfo) {
            currentLoad = branchLoadInfo.getBranchLoad();
            isSufficientLoad = branchLoadInfo.getBranchLoad() > transaction.getTotalAmount();
        }
    }

    System.out.println("\n\n");
    System.out.println("SAVE-TRANSACTION");
    System.out.println("--------------------------------------------");
    System.out.println("[username]: " + username);
    System.out.println("[company]: " + profile.getCompanyName());
    System.out.println("[branch]: " + profile.getBranchName());
    System.out.println("[loading-scheme]: " + loadingScheme);
    System.out.println("[current-load-balance]: " + currentLoad);
    System.out.println("[transactionAmount]: " + transaction.getTotalAmount());
    System.out.println("[itemPrice]: " + transaction.getItemPriceTotal());
    System.out.println("[totalMarkup]: " + transaction.getMarkUpTotal());
    System.out.println("[isSufficientLoad]: " + isSufficientLoad);
    System.out.println("--------------------------------------------");
    System.out.println("\n\n");

    if(isSufficientLoad){
        /*
        {
            "transactionDate":null,
            "transactionType":"HOTEL",
            "transactionCode":"SOGO-6969",
            "totalAmount":2500.0,
            "itemPriceTotal":2250.0,
            "markUpTotal":250.0,
            "quantity":1.0,
            "customerName":"Rowena Palami",
            "customerEmail":"weng.palami@gmail.com",
            "customerContact":"(0918) 222-6969",
            "customerAddress":"Room #69 SOGO Hotel, Guadalupe, EDSA, MM"
        }
        * */

        String generatedReservationCode = null;
        do {
            generatedReservationCode = this.biyaheTransactionService.generateTransactionCode(10);
        }
        while(this.biyaheFlightSalesService.checkReservationCodes(generatedReservationCode));

        BiyaheSales sale = transaction.toBiyaheSales();
        sale.setReservationCode(generatedReservationCode);

        sale.setTransactionDate(new Date());
        sale.setAgent(user);

        System.out.println("\n\n");
        System.out.println("API :: SAVE-TRANSACTION");
        System.out.println("------------------------------------------------");
        System.out.println(sale.toString());
        System.out.println("------------------------------------------------");
        System.out.println("\n\n");

        this.biyaheFlightSalesService.addUpdateBiyaheFlightSales(sale);

        result = new BiyaheApplicationResult(SUCCESS_CODE_TRANSACTION_SAVE, SUCCESS_DISPLAY_TRANSACTION_SAVE);
        return new ResponseEntity(BiyaheTextFormatter.serializeToJson(result), HttpStatus.OK);
    }
    else {
        result = new BiyaheApplicationResult("ERROR", null, ERROR_CODE_INSUFFICIENT_BALANCE, ERROR_DISPLAY_INSUFFICIENT_BALANCE);
        return new ResponseEntity(BiyaheTextFormatter.serializeToJson(result), HttpStatus.NOT_ACCEPTABLE);
    }
}
</code>```

In my Servlet Context

```<code><mvc:annotation-driven />

<mvc:cors>
    <mvc:mapping path="/api/**"
                 allowed-origins="http://localhost:9000/"
                 allowed-methods="POST, GET, PUT, OPTIONS, DELETE"
                 allowed-headers="X-Auth-Token, Content-Type, Authorization"
                 exposed-headers="custom-header1, custom-header2"
                 allow-credentials="false"
                 max-age="4800" />

    <mvc:mapping path="/**"
                 allowed-origins="http://localhost:9000/"
                 allowed-methods="POST, GET, PUT, OPTIONS, DELETE"
                 allowed-headers="X-Auth-Token, Content-Type, Authorization"
                 exposed-headers="custom-header1, custom-header2"
                 allow-credentials="false"
                 max-age="4800" />
</mvc:cors>
</code>```

In my web console, I am getting -> "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8088/booking/api/saveTransaction. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

I have these 2 different domains: localhost:9000 and localhost:8088

localhost:9000 needs to post to localhost:8088

Note: I already done this in PHP but this time, I need to use only
  ajax

I have been working on this for 3 days, so if happens that there is someone who has an answer for this, please help me. Thank you in advance!

答:
CORs can be tricky, but I think your problem here is simply that you aren't return the "Access-Control-Allow-Origin" header to your client.  You can see that in the  strophes of your servlet context.

First thing you might try is to simply remove the   strophe, that should allow for all headers.

Body:
Ok, this is my first time to post here so if you see that I need to correct something please tell me.

I'm having problem when I try to post data to an api using ajax. I am using tomcat8 as my web server. I added the @CrossOrigin annotation in my controller which were suggested by others. I also added the localhost:9000 as allowed-origin and Authorization in allowed-headers in my servlet.xml but still no success.

This is my ajax code:

var my_url = "http://localhost:8088/booking/api/saveTransaction";
var username = "user111";
var password = "userpass111";

              $.ajax({
                  method: "POST",
                  url: my_url,
                  dataType: "json",
                  headers: {
                    'Authorization':'Basic ' + btoa(username+":"+password),
                    'Content-Type':'x-www-form-urlencoded'
                  },
                  data: JSON.stringify(my_data),
                  success: function(data){
                    alert(data);
                  },
                  error: function(xhr, status, error){
                    alert(xhr);
                    alert(status);
                    alert(error);
                  }
              });

In my Controller

@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping(value = "/api/saveTransaction", method = RequestMethod.POST)
public ResponseEntity<BiyaheApplicationResult> saveTransaction(Authentication authentication, @RequestBody CompanyTransaction transaction) {

    System.out.println("\n\n");
    System.out.println("START-SAVE-TRANSACTION");
    System.out.println("\n\n");

    BiyaheApplicationResult result = null;

    if(null != transaction) transaction.setTransactionDate(new Date());

    System.out.println("\n\n");
    System.out.println("TEST: SAVE-JSON-TRANSACTION");
    System.out.println("--------------------------------------------");
    System.out.println("[transaction]: " + BiyaheTextFormatter.serializeToJson(transaction));
    System.out.println("--------------------------------------------");
    System.out.println("\n\n");

    String username = authentication.getName();
    User user = this.userService.findUserByUsername(username);
    UserProfileView profile = this.userProfileViewService.getUserProfileViewById(user.getId());

    int companyId = -1;
    int branchId = -1;
    String loadingScheme = null;
    if(null != profile){
        if(BiyaheConstants.JGGC_HQ_COMPANY_ID < profile.getCompanyId()){
            companyId = profile.getCompanyId();
            CompanyConfiguration conf = this.companyConfigurationService.getCompanyConfigurationByCompanyId(companyId);
            loadingScheme = conf.getLoadingScheme();
        }

        if(BiyaheConstants.JGGC_HQ_BRANCH_ID < profile.getBranchId()){
            branchId = profile.getBranchId();
        }
    }

    double currentLoad = 0;

    boolean isSufficientLoad = false;
    if(BiyaheConstants.LOADING_SCHEME_CENTRALIZED.equalsIgnoreCase(loadingScheme)){
        CompanyLoadInfo coLoadInfo = this.companyLoadInfoService.getCompanyLoadInfoByCompanyId(companyId);
        if(null != coLoadInfo) {
            currentLoad = coLoadInfo.getCentralizeLoadAmount();
            isSufficientLoad = coLoadInfo.getCentralizeLoadAmount() > transaction.getTotalAmount();
        }
    }
    else if(BiyaheConstants.LOADING_SCHEME_DISTRIBUTED.equalsIgnoreCase(loadingScheme)){
        BranchLoadInfo branchLoadInfo = this.branchLoadInfoService.getBranchLoadInfoByBranchId(branchId);
        if(null != branchLoadInfo) {
            currentLoad = branchLoadInfo.getBranchLoad();
            isSufficientLoad = branchLoadInfo.getBranchLoad() > transaction.getTotalAmount();
        }
    }

    System.out.println("\n\n");
    System.out.println("SAVE-TRANSACTION");
    System.out.println("--------------------------------------------");
    System.out.println("[username]: " + username);
    System.out.println("[company]: " + profile.getCompanyName());
    System.out.println("[branch]: " + profile.getBranchName());
    System.out.println("[loading-scheme]: " + loadingScheme);
    System.out.println("[current-load-balance]: " + currentLoad);
    System.out.println("[transactionAmount]: " + transaction.getTotalAmount());
    System.out.println("[itemPrice]: " + transaction.getItemPriceTotal());
    System.out.println("[totalMarkup]: " + transaction.getMarkUpTotal());
    System.out.println("[isSufficientLoad]: " + isSufficientLoad);
    System.out.println("--------------------------------------------");
    System.out.println("\n\n");

    if(isSufficientLoad){
        /*
        {
            "transactionDate":null,
            "transactionType":"HOTEL",
            "transactionCode":"SOGO-6969",
            "totalAmount":2500.0,
            "itemPriceTotal":2250.0,
            "markUpTotal":250.0,
            "quantity":1.0,
            "customerName":"Rowena Palami",
            "customerEmail":"weng.palami@gmail.com",
            "customerContact":"(0918) 222-6969",
            "customerAddress":"Room #69 SOGO Hotel, Guadalupe, EDSA, MM"
        }
        * */

        String generatedReservationCode = null;
        do {
            generatedReservationCode = this.biyaheTransactionService.generateTransactionCode(10);
        }
        while(this.biyaheFlightSalesService.checkReservationCodes(generatedReservationCode));

        BiyaheSales sale = transaction.toBiyaheSales();
        sale.setReservationCode(generatedReservationCode);

        sale.setTransactionDate(new Date());
        sale.setAgent(user);

        System.out.println("\n\n");
        System.out.println("API :: SAVE-TRANSACTION");
        System.out.println("------------------------------------------------");
        System.out.println(sale.toString());
        System.out.println("------------------------------------------------");
        System.out.println("\n\n");

        this.biyaheFlightSalesService.addUpdateBiyaheFlightSales(sale);

        result = new BiyaheApplicationResult(SUCCESS_CODE_TRANSACTION_SAVE, SUCCESS_DISPLAY_TRANSACTION_SAVE);
        return new ResponseEntity(BiyaheTextFormatter.serializeToJson(result), HttpStatus.OK);
    }
    else {
        result = new BiyaheApplicationResult("ERROR", null, ERROR_CODE_INSUFFICIENT_BALANCE, ERROR_DISPLAY_INSUFFICIENT_BALANCE);
        return new ResponseEntity(BiyaheTextFormatter.serializeToJson(result), HttpStatus.NOT_ACCEPTABLE);
    }
}

In my Servlet Context

<mvc:annotation-driven />

<mvc:cors>
    <mvc:mapping path="/api/**"
                 allowed-origins="http://localhost:9000/"
                 allowed-methods="POST, GET, PUT, OPTIONS, DELETE"
                 allowed-headers="X-Auth-Token, Content-Type, Authorization"
                 exposed-headers="custom-header1, custom-header2"
                 allow-credentials="false"
                 max-age="4800" />

    <mvc:mapping path="/**"
                 allowed-origins="http://localhost:9000/"
                 allowed-methods="POST, GET, PUT, OPTIONS, DELETE"
                 allowed-headers="X-Auth-Token, Content-Type, Authorization"
                 exposed-headers="custom-header1, custom-header2"
                 allow-credentials="false"
                 max-age="4800" />
</mvc:cors>

In my web console, I am getting -> "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8088/booking/api/saveTransaction. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

I have these 2 different domains: localhost:9000 and localhost:8088

localhost:9000 needs to post to localhost:8088

Note: I already done this in PHP but this time, I need to use only
  ajax

I have been working on this for 3 days, so if happens that there is someone who has an answer for this, please help me. Thank you in advance!


问:
does node js mysql needs apache
I have recently wanted to use a MySQL database with my node.js server. And after doing some digging, I found the following github page for mysql to be used via node.js:

https://github.com/mysqljs/mysql

However what I wasn't sure is if this is an API that allows for node.js to communicate with a MySQL database, or if this is a full implementation of a MySQL database (hence I wouldn't need to install apache). Since I tried implementing this without an apache server, it gave me an error:

code run (after having doing npm install mysql)

```<code>var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'articles'
});

connection.connect();
</code>```

error:

[Error: connect ECONNREFUSED 127.0.0.1:3306]

答:
Apache is a web server. MySQL is a database. You don't need either to use the other. But you do need a MySQL Server running on your localhost to use MySQL with Node.js, the github link you provided is like an API to use MySQL with Node.js.

Node.js has its own web server which you can use for development, however when and if you move to production, you would want to use a web server like Apache or Nginx with your application, and you will have to do some work for that. But you probably are just learning and won't do that anytime soon.

Title: does node js mysql needs apache

Body:
I have recently wanted to use a MySQL database with my node.js server. And after doing some digging, I found the following github page for mysql to be used via node.js:

https://github.com/mysqljs/mysql

However what I wasn't sure is if this is an API that allows for node.js to communicate with a MySQL database, or if this is a full implementation of a MySQL database (hence I wouldn't need to install apache). Since I tried implementing this without an apache server, it gave me an error:

code run (after having doing npm install mysql)

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'articles'
});

connection.connect();

error:

[Error: connect ECONNREFUSED 127.0.0.1:3306]


问:
create multiple Azure VMs in single powershell script parallely
I am able to create Azure VM using powershell.

I have to create 4 VM's parallel.

Does any feature in powershell to do create multiple VMs parallel ? Something like background jobs or call the same function for all different VMs using threads kind of ?

答: Thanks all, I have solved my issue using PS workflow parallel and sequence features. Achieved it.</p>


问:
How to get all file information by path?
Is there a PHP function that returns all information about the file using the path as parameter? I need a information just like $_FILES array has: name,type,tmp_name(i already have this),error and size.

For example:

```<code>$file = get_file('path/to/file');
</code>```

答:
```<code>$_SERVER['SCRIPT_FILENAME'];
</code>```

That should work.

Body:
Is there a PHP function that returns all information about the file using the path as parameter? I need a information just like $_FILES array has: name,type,tmp_name(i already have this),error and size.

For example:

$file = get_file('path/to/file');

Body:
$_SERVER['SCRIPT_FILENAME'];

That should work.


问:
Update textbox with AJAX
When a dropdown's value changes, I need the values of two textboxes to change, based on the new value of the dropdown, without refreshing the page.

This should be dead easy, but I'm having trouble figuring out what makes AJAX tick. I seem to be able to get the value, but I can't set the textbox.

This similar question didn't help me. Neither did this.

JavaScript:

```<code>// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            alert(result);
            newDob = result;
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change
    $("#DoB").val(newDob);
});
</code>```

Controller:

```<code>[HttpGet]
public string PatientDob(int patientId)
{
    return db.Patients.Find(patientId).DateOfBirth.ToString("MM/dd/yyyy");
}
</code>```

答:
The problem is that ajax by default is asynchronous so that the las line in your code example is probably executed before obtaining the result from the server.
You could either add async: false to your ajax call in order to wait for the result before executing your next javascript step:

```<code> $.ajax({
    url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
    async: false,
    type: "GET",
    success: function (result) {
        // Displays correct result
        alert(result);
        newDob = result;
    },
    error: function (xhr, status, err) {
        alert(err);
    }
});
$("#DoB").val(newDob);
</code>```

or (preferrably) set the text field in the success method of the call (this wouldn't block any other code from executing while you're waiting for the server result):

```<code> $.ajax({
    url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
    async: true,
    type: "GET",
    success: function (result) {
        // Displays correct result
        alert(result);
        newDob = result;
        $("#DoB").val(newDob);
    },
    error: function (xhr, status, err) {
        alert(err);
    }
});
</code>```

Title: Update textbox with AJAX

Body:
When a dropdown's value changes, I need the values of two textboxes to change, based on the new value of the dropdown, without refreshing the page.

This should be dead easy, but I'm having trouble figuring out what makes AJAX tick. I seem to be able to get the value, but I can't set the textbox.

This similar question didn't help me. Neither did this.

JavaScript:

// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            alert(result);
            newDob = result;
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change
    $("#DoB").val(newDob);
});

Controller:

[HttpGet]
public string PatientDob(int patientId)
{
    return db.Patients.Find(patientId).DateOfBirth.ToString("MM/dd/yyyy");
}

Body:
The problem is that ajax by default is asynchronous so that the las line in your code example is probably executed before obtaining the result from the server.
You could either add async: false to your ajax call in order to wait for the result before executing your next javascript step:

 $.ajax({
    url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
    async: false,
    type: "GET",
    success: function (result) {
        // Displays correct result
        alert(result);
        newDob = result;
    },
    error: function (xhr, status, err) {
        alert(err);
    }
});
$("#DoB").val(newDob);

or (preferrably) set the text field in the success method of the call (this wouldn't block any other code from executing while you're waiting for the server result):

 $.ajax({
    url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
    async: true,
    type: "GET",
    success: function (result) {
        // Displays correct result
        alert(result);
        newDob = result;
        $("#DoB").val(newDob);
    },
    error: function (xhr, status, err) {
        alert(err);
    }
});


答:
Yes; take a look at finfo_file function.

According to the official documentation found @ http://php.net/manual/en/function.finfo-file.php

finfo_file -- finfo::file — Return information about a file

Procedural approach:

```<code>string finfo_file ( resource $finfo , string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )
</code>```

Object Oriented approach:

```<code>public string finfo::file ( string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )
</code>```

Title: How to get all file information by path?

Body:
Yes; take a look at finfo_file function.

According to the official documentation found @ http://php.net/manual/en/function.finfo-file.php

finfo_file -- finfo::file — Return information about a file

Procedural approach:

string finfo_file ( resource $finfo , string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Object Oriented approach:

public string finfo::file ( string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )


问:
How to convert a dictionary of strings into a block of text with python
I have a dictionary full of string-valued k-v pairs, and I want each to be separated by ==>& then printed to a newline.

I use an array to mediate the transformation, which seems unnecessary & inelegant. I'd like to do this in 1 line if possible.

Here's what I have:

```<code>foo_dict = {
    'a' : '1',
    'b' : '2',
    'c' : '3',
    }
foo_list = []
for k, v in foo_dict.items():
    foo_list.append('{} ==> {}'.format(k, v))
foo_text = '\n'.join(foo_list)
</code>```

this will print:

```<code>b ==> 2
c ==> 3
a ==> 1
</code>```

the order doesn't matter (otherwise I'd just use OrderedDict.) What matters is that all k-v pairs get printed in the correct format.

答:
You can try this:</p>

```<code>new_list = [a+"==>"+b if isinstance(a, str) and isinstance(b, str) else str(a)+"==>"+str(b) for a, b in foo_dict.items()]

#then, just print the contents

for i in new_list:
    print i
</code>```

Body:
I have a dictionary full of string-valued k-v pairs, and I want each to be separated by ==>& then printed to a newline.

I use an array to mediate the transformation, which seems unnecessary & inelegant. I'd like to do this in 1 line if possible.

Here's what I have:

foo_dict = {
    'a' : '1',
    'b' : '2',
    'c' : '3',
    }
foo_list = []
for k, v in foo_dict.items():
    foo_list.append('{} ==> {}'.format(k, v))
foo_text = '\n'.join(foo_list)

this will print:

b ==> 2
c ==> 3
a ==> 1

the order doesn't matter (otherwise I'd just use OrderedDict.) What matters is that all k-v pairs get printed in the correct format.

Body:
You can try this:

new_list = [a+"==>"+b if isinstance(a, str) and isinstance(b, str) else str(a)+"==>"+str(b) for a, b in foo_dict.items()]

#then, just print the contents

for i in new_list:
    print i


问:
Loop transfers data from last row only
I am trying to transfer data from one sheet to another in format as shown in the pictures. The length of the data in sheet one is unknown. The code I am using will place the data in the proper format but all of the data ends up as the data from the last row.

```<code>For b = 1 To l - 1 Step 1
    For c = 0 To (l - 2) * 4 Step 4

        idvalue = Sheet1.Cells(b + 1, 1).Value
         Sheet3.Cells(c + 1, 2).Value = idvalue
        namevalue = Sheet1.Cells(b + 1, 2).Value
         Sheet3.Cells(c + 2, 2).Value = namevalue
        amountvalue = Sheet1.Cells(b + 1, 3).Value
         Sheet3.Cells(c + 3, 2).Value = amountvalue
        commentsvalue = Sheet1.Cells(b + 1, 4).Value
         Sheet3.Cells(c + 4, 2).Value = commentsvalue

    Next c
Next b
</code>```

答:
Here's a solution that makes the code a lot easier to read.

Obviously you'll also need to change the For loop declaration to whatever start row / end row is required.

```<code>Sub Example()

Dim lNewRow As Long
Dim lOldRow As Long

lNewRow = 1

For lOldRow = 2 To 7

    With Sheets("Sheet3")

        .Cells(lNewRow, 1) = "ID"
        .Cells(lNewRow, 2) = Sheets("Sheet1").Cells(lOldRow, 1)

        .Cells(lNewRow + 1, 1) = "NAME"
        .Cells(lNewRow + 1, 2) = Sheets("Sheet1").Cells(lOldRow, 2)

        .Cells(lNewRow + 2, 1) = "AMT"
        .Cells(lNewRow + 2, 2) = Sheets("Sheet1").Cells(lOldRow, 3)

        .Cells(lNewRow + 3, 1) = "COMMENTS"
        .Cells(lNewRow + 3, 2) = Sheets("Sheet1").Cells(lOldRow, 4)

    End With

    lNewRow = lNewRow + 4

Next

End Sub
</code>```

Title: Loop transfers data from last row only

Body:
I am trying to transfer data from one sheet to another in format as shown in the pictures. The length of the data in sheet one is unknown. The code I am using will place the data in the proper format but all of the data ends up as the data from the last row.

For b = 1 To l - 1 Step 1
    For c = 0 To (l - 2) * 4 Step 4

        idvalue = Sheet1.Cells(b + 1, 1).Value
         Sheet3.Cells(c + 1, 2).Value = idvalue
        namevalue = Sheet1.Cells(b + 1, 2).Value
         Sheet3.Cells(c + 2, 2).Value = namevalue
        amountvalue = Sheet1.Cells(b + 1, 3).Value
         Sheet3.Cells(c + 3, 2).Value = amountvalue
        commentsvalue = Sheet1.Cells(b + 1, 4).Value
         Sheet3.Cells(c + 4, 2).Value = commentsvalue

    Next c
Next b

Body:
Here's a solution that makes the code a lot easier to read.

Obviously you'll also need to change the For loop declaration to whatever start row / end row is required.

Sub Example()

Dim lNewRow As Long
Dim lOldRow As Long

lNewRow = 1

For lOldRow = 2 To 7

    With Sheets("Sheet3")

        .Cells(lNewRow, 1) = "ID"
        .Cells(lNewRow, 2) = Sheets("Sheet1").Cells(lOldRow, 1)

        .Cells(lNewRow + 1, 1) = "NAME"
        .Cells(lNewRow + 1, 2) = Sheets("Sheet1").Cells(lOldRow, 2)

        .Cells(lNewRow + 2, 1) = "AMT"
        .Cells(lNewRow + 2, 2) = Sheets("Sheet1").Cells(lOldRow, 3)

        .Cells(lNewRow + 3, 1) = "COMMENTS"
        .Cells(lNewRow + 3, 2) = Sheets("Sheet1").Cells(lOldRow, 4)

    End With

    lNewRow = lNewRow + 4

Next

End Sub


问:
get a static src from json returns undefined
i'm trying to build an overlay that shows two images. the images src is stored in a json file that looks like this:

```<code>{
    "items": [{
        "title": "Multimilionario",
        "front": "http://placehold.it/810x2028?text=front",
        "back": "http://placehold.it/810x2028?text=back"
    }]
}
</code>```

when i click on a button, the overlay opens and it's supposed to append the src to two s. but what i get is src(undefined).

my jquery click function looks like this (I've left off all the logic for the overlay to open/close):

```<code>$(".js-overlay-start").unbind("click").bind("click", function(e) {
    e.preventDefault();

    $.ajax({
        url: 'json/overlay.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {
            var item = data.items;
            console.log(item);

            $('.json-front').attr("src", "");
            $('.json-back').attr("src", "");
            $('.json-front').attr("src", item.front);
            $('.json-back').attr("src", item.back);
        } //success
    });//ajax
});
</code>```

i've used this very structure to build something very simple on another project and it worked fine. I'm not sure what's going on.

is it because the overlay is hidden or something? any hint or help is greatly appreciated :)

答:
You are using data.items like a single object, it's an array.</p>

```<code>$(".js-overlay-start").unbind("click").bind("click", function(e) {
    e.preventDefault();

    $.ajax({
        url: 'json/overlay.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {
            var item = data.items[0];
            console.log(item);

            $('.json-front').attr("src", "");
            $('.json-back').attr("src", "");
            $('.json-front').attr("src", item.front);
            $('.json-back').attr("src", item.back);
        } //success
    });//ajax
});
</code>```

Body:
i'm trying to build an overlay that shows two images. the images src is stored in a json file that looks like this:

{
    "items": [{
        "title": "Multimilionario",
        "front": "http://placehold.it/810x2028?text=front",
        "back": "http://placehold.it/810x2028?text=back"
    }]
}

when i click on a button, the overlay opens and it's supposed to append the src to two s. but what i get is src(undefined).

my jquery click function looks like this (I've left off all the logic for the overlay to open/close):

$(".js-overlay-start").unbind("click").bind("click", function(e) {
    e.preventDefault();

    $.ajax({
        url: 'json/overlay.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {
            var item = data.items;
            console.log(item);

            $('.json-front').attr("src", "");
            $('.json-back').attr("src", "");
            $('.json-front').attr("src", item.front);
            $('.json-back').attr("src", item.back);
        } //success
    });//ajax
});

i've used this very structure to build something very simple on another project and it worked fine. I'm not sure what's going on.

is it because the overlay is hidden or something? any hint or help is greatly appreciated :)

Body:
You are using data.items like a single object, it's an array.

$(".js-overlay-start").unbind("click").bind("click", function(e) {
    e.preventDefault();

    $.ajax({
        url: 'json/overlay.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {
            var item = data.items[0];
            console.log(item);

            $('.json-front').attr("src", "");
            $('.json-back').attr("src", "");
            $('.json-front').attr("src", item.front);
            $('.json-back').attr("src", item.back);
        } //success
    });//ajax
});


问:
Convert Elixir string to integer or float
I need to convert a string to a floating point value or an integer. There was no method such as,</p>

```<code>string_to_integer
</code>```

答:
If you wanted to convert a string to whatever numeric type is within the string & remove all other characters, this is probably overkill, but will return a float if its a float or an int if its an int or nil if the string does not contain an numeric type.</p>

```<code>@spec string_to_numeric(binary()) :: float() | number() | nil
def string_to_numeric(val) when is_binary(val), do: _string_to_numeric(Regex.replace(~r{[^\d\.]}, val, ""))
defp _string_to_numeric(val) when is_binary(val), do: _string_to_numeric(Integer.parse(val), val)
defp _string_to_numeric(:error, _val), do: nil
defp _string_to_numeric({num, ""}, _val), do: num
defp _string_to_numeric({num, ".0"}, _val), do: num
defp _string_to_numeric({_num, _str}, val), do: elem(Float.parse(val), 0)
</code>```

Body:
I need to convert a string to a floating point value or an integer. There was no method such as,

string_to_integer

Body:
If you wanted to convert a string to whatever numeric type is within the string & remove all other characters, this is probably overkill, but will return a float if its a float or an int if its an int or nil if the string does not contain an numeric type.

@spec string_to_numeric(binary()) :: float() | number() | nil
def string_to_numeric(val) when is_binary(val), do: _string_to_numeric(Regex.replace(~r{[^\d\.]}, val, ""))
defp _string_to_numeric(val) when is_binary(val), do: _string_to_numeric(Integer.parse(val), val)
defp _string_to_numeric(:error, _val), do: nil
defp _string_to_numeric({num, ""}, _val), do: num
defp _string_to_numeric({num, ".0"}, _val), do: num
defp _string_to_numeric({_num, _str}, val), do: elem(Float.parse(val), 0)


问:
Confusion in java.Clock, systemDefaultZone() returning UTC time
I am trying to understand why the following java.time.Clock is returning UTC time instead of the local time zone (EST).

```<code>C:\Users\Felipe>scala
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_65).
Type in expressions for evaluation. Or try :help.

scala> import java.time._
import java.time._

scala> ZoneId.systemDefault()
res0: java.time.ZoneId = America/New_York

scala> val clock = Clock.systemDefaultZone()
clock: java.time.Clock = SystemClock[America/New_York]

scala> clock.instant
res1: java.time.Instant = 2017-07-06T16:20:04.990Z
</code>```

The current time when I ran the above was 12:20pm (i.e. 4h before the UTC time shown)

答:
Instant does not have any time zone information. It is just the number of seconds/nanoseconds since epoch. LocalDateTime represents time in the local time zone, which can be obtained from clock using:

```<code>LocalDateTime.now(clock)
</code>```

You can also convert an Instant to ZonedDateTime (which represents time along with timezone) using:

```<code>clock.instant().atZone(ZoneId.systemDefault())
</code>```

Body:
I am trying to understand why the following java.time.Clock is returning UTC time instead of the local time zone (EST).

C:\Users\Felipe>scala
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_65).
Type in expressions for evaluation. Or try :help.

scala> import java.time._
import java.time._

scala> ZoneId.systemDefault()
res0: java.time.ZoneId = America/New_York

scala> val clock = Clock.systemDefaultZone()
clock: java.time.Clock = SystemClock[America/New_York]

scala> clock.instant
res1: java.time.Instant = 2017-07-06T16:20:04.990Z

The current time when I ran the above was 12:20pm (i.e. 4h before the UTC time shown)

Body:
Instant does not have any time zone information. It is just the number of seconds/nanoseconds since epoch. LocalDateTime represents time in the local time zone, which can be obtained from clock using:

LocalDateTime.now(clock)

You can also convert an Instant to ZonedDateTime (which represents time along with timezone) using:

clock.instant().atZone(ZoneId.systemDefault())


问:
Get percentage of NULL for all columns in Hive
I would like to get the percentage of NULL values in a table in Hive. Is there an easy way to do this without having to enumerate all column names in the query? In this case there are about 50k rows and 20 columns. Thanks in advance!

Something like:

SELECT count(each_column) / count(*) FROM TABLE_1
 WHERE each_column = NULL;

答:
If you do this using code, you need to list the columns.  Here is one way:

```<code>select avg(case when col1 is null then 1.0 else 0.0 end) as col1_null_p,
       avg(case when col2 is null then 1.0 else 0.0 end) as col2_null_p,
       . . .
from t;
</code>```

If you take the list of columns in the table, you can readily construct the query in a spreadsheet.

Body:
If you do this using code, you need to list the columns.  Here is one way:

select avg(case when col1 is null then 1.0 else 0.0 end) as col1_null_p,
       avg(case when col2 is null then 1.0 else 0.0 end) as col2_null_p,
       . . .
from t;

If you take the list of columns in the table, you can readily construct the query in a spreadsheet.


问:
setProperty for color attribute is not working in gxt text area
I have to change the font color of text area dynamically from the color menu. But I am not able to change it. Can you please help me ?</p>

```<code>final ColorMenu fontColorMenu = new ColorMenu();
fontColorMenu.getPalette().addValueChangeHandler(new ValueChangeHandler<String>() {
        @Override
        public void onValueChange(ValueChangeEvent<String> event) {

       //textarea.getElement().getStyle().setColor("#"+event.getValue()); // Not working
       //textarea.getElement().getStyle().setProperty("color", "#"+event.getValue()); // Not working
         textarea.getElement().getStyle().setProperty("Color", "red !important");   // Not working
         }
       });
</code>```

答:
You can try this:

```<code>textarea.getCell().getInputElement(textarea.getElement()).getStyle().setColor("red");
</code>```

Do not know if this is the best solution, but it works or me.

Body:
I have to change the font color of text area dynamically from the color menu. But I am not able to change it. Can you please help me ?

final ColorMenu fontColorMenu = new ColorMenu();
fontColorMenu.getPalette().addValueChangeHandler(new ValueChangeHandler<String>() {
        @Override
        public void onValueChange(ValueChangeEvent<String> event) {

       //textarea.getElement().getStyle().setColor("#"+event.getValue()); // Not working
       //textarea.getElement().getStyle().setProperty("color", "#"+event.getValue()); // Not working
         textarea.getElement().getStyle().setProperty("Color", "red !important");   // Not working
         }
       });

Body:
You can try this:

textarea.getCell().getInputElement(textarea.getElement()).getStyle().setColor("red");

Do not know if this is the best solution, but it works or me.


问:
Angular Translate Unit Test - Can't inject $translateProvider
I'm using ES6, AngularJS, Karma/Jasmine, and angular-translate. Can't seem to get my unit test to pass. Not really too sure how to work with 3rd party modules, like angular-translate, when it comes to unit testing. The code and the error I'm getting are below. $translateProvider is not loading.

```<code>import CatalogueModule from './catalogue.module'
import CatalogueService from './catalogue.service'

let service,
    _$translateProvider;

describe('CatalogueService', () => {
  beforeEach(angular.mock.module(CatalogueModule));

  beforeEach(() => {
    angular.mock.module({
      $translateProvider: jasmine.createSpyObj('$translateProvider',
        ['translations', 'preferredLanguage']
      ),
      $translate: jasmine.createSpyObj('$translate',
        ['use']
      )
    });
  })

  beforeEach(inject(($translateProvider) => {
    _$translateProvider = $translateProvider;

    _$translateProvider.translations('en', {});
    _$translateProvider.preferredLanguage('en');

    // service = new CatalogueService();
  }));

  it('should set the config object after initialization', inject(($translateProvider, CatalogueService) => {
    // $translateProvider.use.and.returnValue();
    // expect(service.config.headers).to.equal(null);
  }));
});
</code>```

This is the error:

```<code>✖ "before each" hook: WorkFn for "should set the config object after initialization"
      Chrome 59.0.3071 (Mac OS X 10.12.3)
    Error: [$injector:unpr] Unknown provider: $translateProviderProvider <- $translateProvider
</code>```

UPDATE - Adding catalogue.service.js

```<code>class CatalogueService {
  constructor($http, $q, $translate) {
    'ngInject';

    this._$http      = $http;
    this._$q         = $q;
    this._$translate = $translate;

    this.config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '******',
        'P3-APP-ID': '*****',
        'P3-Date': '*****'
      }
    };

    this.catalogue = this.getCatalogue();
  }

  getCatalogue() {
    const lang = this._$translate.use();
    const url = `https://somedomain.com/catalog?language_code=${lang}`;
    const deferred = this._$q.defer();

    this._$http
      .get(url, this.config)
      .then(
        (res) => deferred.resolve(res.data.characters),
        (err) => deferred.reject(err)
      );

    return deferred.promise;
  };

  getCharacterByCharId(charId) {
    return this.catalogue
      .then((res) => {
        return res.find((character) => {
          return character.link_name === charId;
        });
      });
  };
}

export default CatalogueService;
</code>```

答:
There is no

```<code>beforeEach(angular.mock.module(...))
</code>```

in the test. Which means that only ng and ngMock modules are loaded in current test, and there is no $translateProvider service.

It is preferable to test Angular units by instantiating them with DI, not directly. This allows to test both service annotation and class internals.

It is highly desirable to keep unit tests isolated and eliminate every unit but tested one from the test, especially third-party libraries. If tested units require $translateProvider, it should be preferably be replaced with a mock or a stub:

```<code>beforeEach(angular.mock.module('moduleThatContainsCatalogueService');

beforeEach(() => {
  angular.mock.module({
    $translateProvider: jasmine.createSpyObj('$translateProvider',
      ['translations', 'preferredLanguage', 'use']
    )
  });
})

it('...', inject(($translateProvider, catalogueService) => {
  $translateProvider.use.and.returnValue(...);
  ...
}));
</code>```

Body:
I'm using ES6, AngularJS, Karma/Jasmine, and angular-translate. Can't seem to get my unit test to pass. Not really too sure how to work with 3rd party modules, like angular-translate, when it comes to unit testing. The code and the error I'm getting are below. $translateProvider is not loading.

import CatalogueModule from './catalogue.module'
import CatalogueService from './catalogue.service'

let service,
    _$translateProvider;

describe('CatalogueService', () => {
  beforeEach(angular.mock.module(CatalogueModule));

  beforeEach(() => {
    angular.mock.module({
      $translateProvider: jasmine.createSpyObj('$translateProvider',
        ['translations', 'preferredLanguage']
      ),
      $translate: jasmine.createSpyObj('$translate',
        ['use']
      )
    });
  })

  beforeEach(inject(($translateProvider) => {
    _$translateProvider = $translateProvider;

    _$translateProvider.translations('en', {});
    _$translateProvider.preferredLanguage('en');

    // service = new CatalogueService();
  }));

  it('should set the config object after initialization', inject(($translateProvider, CatalogueService) => {
    // $translateProvider.use.and.returnValue();
    // expect(service.config.headers).to.equal(null);
  }));
});

This is the error:

✖ "before each" hook: WorkFn for "should set the config object after initialization"
      Chrome 59.0.3071 (Mac OS X 10.12.3)
    Error: [$injector:unpr] Unknown provider: $translateProviderProvider <- $translateProvider

UPDATE - Adding catalogue.service.js

class CatalogueService {
  constructor($http, $q, $translate) {
    'ngInject';

    this._$http      = $http;
    this._$q         = $q;
    this._$translate = $translate;

    this.config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '******',
        'P3-APP-ID': '*****',
        'P3-Date': '*****'
      }
    };

    this.catalogue = this.getCatalogue();
  }

  getCatalogue() {
    const lang = this._$translate.use();
    const url = `https://somedomain.com/catalog?language_code=${lang}`;
    const deferred = this._$q.defer();

    this._$http
      .get(url, this.config)
      .then(
        (res) => deferred.resolve(res.data.characters),
        (err) => deferred.reject(err)
      );

    return deferred.promise;
  };

  getCharacterByCharId(charId) {
    return this.catalogue
      .then((res) => {
        return res.find((character) => {
          return character.link_name === charId;
        });
      });
  };
}

export default CatalogueService;

Body:
There is no

beforeEach(angular.mock.module(...))

in the test. Which means that only ng and ngMock modules are loaded in current test, and there is no $translateProvider service.

It is preferable to test Angular units by instantiating them with DI, not directly. This allows to test both service annotation and class internals.

It is highly desirable to keep unit tests isolated and eliminate every unit but tested one from the test, especially third-party libraries. If tested units require $translateProvider, it should be preferably be replaced with a mock or a stub:

beforeEach(angular.mock.module('moduleThatContainsCatalogueService');

beforeEach(() => {
  angular.mock.module({
    $translateProvider: jasmine.createSpyObj('$translateProvider',
      ['translations', 'preferredLanguage', 'use']
    )
  });
})

it('...', inject(($translateProvider, catalogueService) => {
  $translateProvider.use.and.returnValue(...);
  ...
}));


问:
jquery table filtering/sorting plugins
Hey guys,
Are there any table sorting plugins that let you 'opt out' from sorting once you have sorted a column, restoring the the table to the unsorted/default state as when the table was loaded? And also gives hints on the order of columns clicked when multiple columns are used for sorting?</p>

答:
What about jQuery tablesorter plugin?

Have a look at its demo here

ContentLicense: CC BY-SA 2.5

Title: jquery table filtering/sorting plugins


问:
Windows vs. Linux vs. Mac: Different php extensions with same struct name and some shared files
I have two php extensions -- A and B.

In a.h I have:

```<code>struct foo : public functor {
    virtual void operator()( some parameters );
};
</code>```

In b.h, I also have the same thing

```<code>struct foo : public functor {
    virtual void operator()( some parameters );
};
</code>```

Functor is declared in shared.h which is shared between the two extensions

```<code>struct functor {
    virtual void operator()( some parameters );
};
</code>```

void foo::operator()(some parameters) are implemented differently in a2.cpp and b2.cpp.

In a1.cpp, I have a list of functors used in extension A:

```<code>const functor a_func[] = {
    func1(new func1),
    func2(new func2),
    foo(new foo),
    func4(new func4)
};
</code>```

In b2.cpp, I have a similar list:

```<code>const functor b_func[] = {
    func1(new func1),
    foo(new foo),
    func3(new func3),
    func4(new func4)
};
</code>```

The function foo is called in shared.cpp

```<code>const functor* func = get_func( functors );
*func( some arguments );
</code>```

Where 'functors' is either a_func or b_func, and shared.cpp is called from extension A or extension B depending on the API you're using.

The problem I'm currently facing right now is that when testing extension B on Mac and when extension A is loaded before extension B in php.ini, the foo function defined in a2.cpp is used instead of b2.cpp. But if I reverse the order in php.ini, everything works fine. When I debug into it, I see that the list of functors being passed into get_func() is correct (i.e., b_func).

I tried using namespace or renaming the foo function in A and B which fixes the problem. But the thing I'm confused about is the extensions have always worked on Windows and Linux, however now it has this one name definition problem on Mac.

答: Just in case other people are wondering. This is because MacOS has a default configuration of flat namespace. To fix this, you need to put in MACOSX_DEPLOYMENT_TARGET=sw_vers -productVersion in your config file.

Body:
I have two php extensions -- A and B.

In a.h I have:

struct foo : public functor {
    virtual void operator()( some parameters );
};

In b.h, I also have the same thing

struct foo : public functor {
    virtual void operator()( some parameters );
};

Functor is declared in shared.h which is shared between the two extensions

struct functor {
    virtual void operator()( some parameters );
};

void foo::operator()(some parameters) are implemented differently in a2.cpp and b2.cpp.

In a1.cpp, I have a list of functors used in extension A:

const functor a_func[] = {
    func1(new func1),
    func2(new func2),
    foo(new foo),
    func4(new func4)
};

In b2.cpp, I have a similar list:

const functor b_func[] = {
    func1(new func1),
    foo(new foo),
    func3(new func3),
    func4(new func4)
};

The function foo is called in shared.cpp

const functor* func = get_func( functors );
*func( some arguments );

Where 'functors' is either a_func or b_func, and shared.cpp is called from extension A or extension B depending on the API you're using.

The problem I'm currently facing right now is that when testing extension B on Mac and when extension A is loaded before extension B in php.ini, the foo function defined in a2.cpp is used instead of b2.cpp. But if I reverse the order in php.ini, everything works fine. When I debug into it, I see that the list of functors being passed into get_func() is correct (i.e., b_func).

I tried using namespace or renaming the foo function in A and B which fixes the problem. But the thing I'm confused about is the extensions have always worked on Windows and Linux, however now it has this one name definition problem on Mac.


问:
FastCGI cache key while ignoring GET requests but allow certain GET requests to bypass cache
I have a WordPress installation running on with Woocommerce which requires the GET request add_to_cart to function in order for users to add items to the cart.

I have FastCGI cache key similar to
How to set fastcgi_cache_key using original $request_uri without $args?

```<code># Map request_path var without query strings
map $request_uri $request_path {
    ~(?<captured_path>[^?]*) $captured_path;
}

# FastCGI Cache
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_path$cookie_aelia_cs_selected_currency";
</code>```

Is there any way to bypass FastCGI for these requests and for NGINX to just serve the page?

I am pretty new to NGINX and so any help would be very much appreciated

UPDATE

I have tried to use the following in the server block

```<code>if ($arg_name ~* "(add-to-cart|remove-item)") {
        set $no_cache 1;
}
</code>```

The server is still ignoring this and serving the cached file.

SOLVED NOW

答:
Solved in the end by adding <code>.*add-to-cart.*</code> in the checks for request. </p>

```<code># Don't cache uris containing the following segments
if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml|.*add-to-cart.*") {
    set $no_cache 1;
}
</code>```

Body:
I have a WordPress installation running on with Woocommerce which requires the GET request add_to_cart to function in order for users to add items to the cart.

I have FastCGI cache key similar to
How to set fastcgi_cache_key using original $request_uri without $args?

# Map request_path var without query strings
map $request_uri $request_path {
    ~(?<captured_path>[^?]*) $captured_path;
}

# FastCGI Cache
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_path$cookie_aelia_cs_selected_currency";

Is there any way to bypass FastCGI for these requests and for NGINX to just serve the page?

I am pretty new to NGINX and so any help would be very much appreciated

UPDATE

I have tried to use the following in the server block

if ($arg_name ~* "(add-to-cart|remove-item)") {
        set $no_cache 1;
}

The server is still ignoring this and serving the cached file.

SOLVED NOW

Body:
Solved in the end by adding .*add-to-cart.* in the checks for request.

# Don't cache uris containing the following segments
if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml|.*add-to-cart.*") {
    set $no_cache 1;
}


问:
TreeView DoubleClick
The tree view in avalonia doesn't have a double-click Event.
Is it possible to implement this in another way?

I want to catch the double-click Event in a ViewModel to execute
a method.

Regards,
Kevin

答: PointerPressed event has ClickCount property. Subscribe from codebehind or behavior and check if ClickCount == 2

Title: TreeView DoubleClick


问:
Can git tell me if a rebase will conflict without actually rebasing?
I would like to programmatically determine with of my feature branches would have rebase conflicts if I tried to rebase them.  Is there a way I can get git to tell me this information without actually performing the rebase?

Failing that, what is the simplest way to detect if a rebase failed before git rebase --aborting it?

My question is similar to these two, which are the same but for merge instead of rebase

Can git tell me if a merge will conflict without actually merging?

Is there a git-merge --dry-run option?

答:
Is there a way I can get git to tell me this information without actually performing the rebase?

The short answer is "no".  The long answer is longer but ends with "no" :-) ... you could get pretty close by writing a lot of code but to get the full correct answer you must do all the commit-copying steps of the rebase, at which point you might as well just run the rebase.

Failing that, what is the simplest way to detect if a rebase failed before git rebase --aborting it?

The git rebase command returns a success (zero) exit code if the rebase completes successfully, and a failure (nonzero) exit code if not.  In shell script, you can just use git rebase $args || git rebase --abort.


问:
How to set a property of a service from an async method in Angular 2/4
I have a service and a component as follows:

```<code>import {OnDestroy, Component} from '@angular/core';
import { JumpService } from "./jump-service";
@Component({
  selector: 'jumper',
  providers: [JumpService]
})
export class Jump implements OnDestroy {
   constructor(
        private _jumpService: JumpService
    ) {

    }
private async _JumpAndShoot(): Promise<area51.armor> {
        let oxy = await this._panic;
        if (!oxy) return;
        this._jumpService.armour = { a, b };
        this._jumpService.oxy = oxy;
        return { a, b };
    }
}
</code>```

Service:

```<code>import { Injectable } from "@angular/core";
@Injectable()
export class JumpService {

     armor: area51.armor;
     oxy: area51.oxylevel;

shoot() {
 //logic
 console.log("Value of oxy", this.oxy); // shows undefined.
}

}
</code>```

Even though, the value of oxy is set on the JumpService inside the async method, it is always shown as undefined in my service when I try to access it. Whereas I don't have problem accessing the armor property which is being set in the method. Is there any different way of setting the properties when dealing with async methods? Please help.

Thank you.

答: If you are using providers in a component like @Component(providers: [JumpService])it will be local to this component and its tree. Provide it in your main module or a top level component.

Body:
I have a service and a component as follows:

import {OnDestroy, Component} from '@angular/core';
import { JumpService } from "./jump-service";
@Component({
  selector: 'jumper',
  providers: [JumpService]
})
export class Jump implements OnDestroy {
   constructor(
        private _jumpService: JumpService
    ) {

    }
private async _JumpAndShoot(): Promise<area51.armor> {
        let oxy = await this._panic;
        if (!oxy) return;
        this._jumpService.armour = { a, b };
        this._jumpService.oxy = oxy;
        return { a, b };
    }
}

Service:

import { Injectable } from "@angular/core";
@Injectable()
export class JumpService {

     armor: area51.armor;
     oxy: area51.oxylevel;

shoot() {
 //logic
 console.log("Value of oxy", this.oxy); // shows undefined.
}

}

Even though, the value of oxy is set on the JumpService inside the async method, it is always shown as undefined in my service when I try to access it. Whereas I don't have problem accessing the armor property which is being set in the method. Is there any different way of setting the properties when dealing with async methods? Please help.

Thank you.


问:
Convert two different date formats to one consistent format in Powershell?
I am automating the reading of log files and have noticed that some log files have dates shown as 2016-12-19 while others would have the same date as Jul 28 11.

Thus far, I have successfully extracted both dates to come out as above. I need to convert both to the same format (either YYYY-MM-DD or anything else). How can I do this?

答:
PowerShell uses objects, so you can cast those date-like strings to [DateTime] objects. Example:

```<code>PS C:\> $dateTime = [DateTime] "2016-12-19"
PS C:\> $dateTime
Monday, December 19, 2016 12:00:00 AM
PS C:\> "{0:MM/dd/yyyy}" -f $dateTime
12/19/2016
</code>```

You can even shorten this:

```<code>PS C:\> "{0:MM/dd/yyyy}" -f ([DateTime] "2016-12-19")
12/19/2016
</code>```

(-f is PowerShell's string format operator.)

Body:
PowerShell uses objects, so you can cast those date-like strings to [DateTime] objects. Example:

PS C:\> $dateTime = [DateTime] "2016-12-19"
PS C:\> $dateTime
Monday, December 19, 2016 12:00:00 AM
PS C:\> "{0:MM/dd/yyyy}" -f $dateTime
12/19/2016

You can even shorten this:

PS C:\> "{0:MM/dd/yyyy}" -f ([DateTime] "2016-12-19")
12/19/2016

(-f is PowerShell's string format operator.)


问:
Flask-WTForm combination is receiving data (request.form), but is not saving in RegistrationForm()
I am trying to make a simple web app where I can upload data from a client to a database, and then send it back. I have everything done except the user authentication and session handling. I am new to Flask-WTForms (and flask tbh), and my example code is below. My problem is that when I try I cannot retrieve my form data through the WTForm that I made. I can only get data from request.form. However that is not ideal because I am trying to use Flask-login.

```<code>@login_manager.user_loader
def load_user(username):
    USERS = mongo.db.users
    u = USERS.find_one({"username": username})
    if not u:
       return None
    return User(u['username'])

@app.route('/register', methods=['GET', 'POST'])
def register():
    USERS = mongo.db.users
    myform = RegistrationForm()
    if myform.validate_on_submit():
        USERS.insert({"Username": myform.username.data, "Password":
myform.password.data})
        return "REGISTERED"
    print(request.form["Username"])
    return "ERROR: Your request failed"
</code>```

When I try to get data through WTForms it does not work and fails, but request.form has the data. I know that flask_wtf does not require it, but I also tried:

```<code>myform = RegistrationForm(request.form)
</code>```

For completeness sake, here is my form file as well.

```<code>  from wtforms import StringField, PasswordField, validators
  from wtforms.validators import DataRequired
  from flask_wtf import FlaskForm

WTF_CSRF_ENABLED = False

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
</code>```

Side note, I know Sql is easier for this project, but I am using mongo for other reasons.

答:
My problem is that when I try I cannot retrieve my form data through the WTForm that I made. I can only get data from request.form.

My understanding is that accessing request.form is in fact the way that you are supposed to retrieve your form data.

First, some issues I spotted:

In load_user(), you write return User(u['username']), which would appear to be returning a totally new User object rather than an ORM-created object which represents the actual record in the database. The problem with this is that it won't have any extra data that's in the database; it'll just be a User object with the name set to u['username'].

In register(), you are attempting to insert new users into the database without first checking whether the specified name already exists.

I just set up signup and login for my Flask app and it was a hassle, so I'll try to save you some time by showing you the code I ended up with. I have these in separate files, but you can also have them all in one file. Separating them out into separate files actually added another layer of complication involving blueprints and creating the model files the right way.

routes.py:

```<code>(...)

web_routes = Blueprint('web_routes', __name__)

(...)

@web_routes.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignupForm()
    if request.method == 'GET':
        return render_template('signup.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            if User.query.filter_by(email=form.email.data).first():
                return "Email address already exists"
            else:
                new_user = User(form.email.data, form.password.data)
                db.session.add(new_user)
                db.session.commit()

                login_user(new_user)

                return redirect(url_for('web_routes.pay'))
        else:
            return "Form didn't validate"

@web_routes.route('/login', methods=['GET','POST'])
def login():

    form = SignupForm()
    if request.method == 'GET':
        return render_template('login.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(email=form.email.data).first()
            if user:
                if user.check_password(form.password.data):
                    login_user(user)
                    return redirect(url_for('web_routes.app'))
                else:
                    return "Wrong password"
            else:
                return "user doesn't exist"
    else:
        return "form not validated"
</code>```

forms.py:

```<code>(...)

class LoginForm(FlaskForm):
    username = StringField('username', validators=[DataRequired()])

class SignupForm(Form):
    email = StringField('email')
    password = PasswordField('password')
    submit = SubmitField("Sign In")
</code>```

models.py:

```<code>from werkzeug.security import generate_password_hash, \
     check_password_hash

(...)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(80), primary_key=True, unique=True)
    password_hash = db.Column(db.String(200))

    def __init__(self, email, password):
        self.email = email
        self.set_password(password)

    def __repr__(self):
        return '<User %r>' % self.email

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.email)

def init_db():
    db.create_all()

    # Create a test user
    new_user = User('a@a.com', 'aaaaaaaa')
    db.session.add(new_user)
    db.session.commit()

if __name__ == '__main__':
    init_db()
</code>```

app.py:

```<code>(...)

from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(email):
    from models import User
    return User.query.filter_by(email=email).first()

if __name__ == '__main__':
    from routes import web_routes
    app.register_blueprint(web_routes)

    # To get PyCharm's debugger to work, you need to have "debug=False, threaded=True"
    #app.run(debug=False, threaded=True)
    app.run(debug=True)
</code>```

Body:
I am trying to make a simple web app where I can upload data from a client to a database, and then send it back. I have everything done except the user authentication and session handling. I am new to Flask-WTForms (and flask tbh), and my example code is below. My problem is that when I try I cannot retrieve my form data through the WTForm that I made. I can only get data from request.form. However that is not ideal because I am trying to use Flask-login.

@login_manager.user_loader
def load_user(username):
    USERS = mongo.db.users
    u = USERS.find_one({"username": username})
    if not u:
       return None
    return User(u['username'])

@app.route('/register', methods=['GET', 'POST'])
def register():
    USERS = mongo.db.users
    myform = RegistrationForm()
    if myform.validate_on_submit():
        USERS.insert({"Username": myform.username.data, "Password":
myform.password.data})
        return "REGISTERED"
    print(request.form["Username"])
    return "ERROR: Your request failed"

When I try to get data through WTForms it does not work and fails, but request.form has the data. I know that flask_wtf does not require it, but I also tried:

myform = RegistrationForm(request.form)

For completeness sake, here is my form file as well.

  from wtforms import StringField, PasswordField, validators
  from wtforms.validators import DataRequired
  from flask_wtf import FlaskForm

WTF_CSRF_ENABLED = False

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])

Side note, I know Sql is easier for this project, but I am using mongo for other reasons.

Body:
My problem is that when I try I cannot retrieve my form data through the WTForm that I made. I can only get data from request.form.

My understanding is that accessing request.form is in fact the way that you are supposed to retrieve your form data.

First, some issues I spotted:

In load_user(), you write return User(u['username']), which would appear to be returning a totally new User object rather than an ORM-created object which represents the actual record in the database. The problem with this is that it won't have any extra data that's in the database; it'll just be a User object with the name set to u['username'].

In register(), you are attempting to insert new users into the database without first checking whether the specified name already exists.

I just set up signup and login for my Flask app and it was a hassle, so I'll try to save you some time by showing you the code I ended up with. I have these in separate files, but you can also have them all in one file. Separating them out into separate files actually added another layer of complication involving blueprints and creating the model files the right way.

routes.py:

(...)

web_routes = Blueprint('web_routes', __name__)

(...)

@web_routes.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignupForm()
    if request.method == 'GET':
        return render_template('signup.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            if User.query.filter_by(email=form.email.data).first():
                return "Email address already exists"
            else:
                new_user = User(form.email.data, form.password.data)
                db.session.add(new_user)
                db.session.commit()

                login_user(new_user)

                return redirect(url_for('web_routes.pay'))
        else:
            return "Form didn't validate"

@web_routes.route('/login', methods=['GET','POST'])
def login():

    form = SignupForm()
    if request.method == 'GET':
        return render_template('login.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(email=form.email.data).first()
            if user:
                if user.check_password(form.password.data):
                    login_user(user)
                    return redirect(url_for('web_routes.app'))
                else:
                    return "Wrong password"
            else:
                return "user doesn't exist"
    else:
        return "form not validated"

forms.py:

(...)

class LoginForm(FlaskForm):
    username = StringField('username', validators=[DataRequired()])

class SignupForm(Form):
    email = StringField('email')
    password = PasswordField('password')
    submit = SubmitField("Sign In")

models.py:

from werkzeug.security import generate_password_hash, \
     check_password_hash

(...)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(80), primary_key=True, unique=True)
    password_hash = db.Column(db.String(200))

    def __init__(self, email, password):
        self.email = email
        self.set_password(password)

    def __repr__(self):
        return '<User %r>' % self.email

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.email)

def init_db():
    db.create_all()

    # Create a test user
    new_user = User('a@a.com', 'aaaaaaaa')
    db.session.add(new_user)
    db.session.commit()

if __name__ == '__main__':
    init_db()

app.py:

(...)

from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(email):
    from models import User
    return User.query.filter_by(email=email).first()

if __name__ == '__main__':
    from routes import web_routes
    app.register_blueprint(web_routes)

    # To get PyCharm's debugger to work, you need to have "debug=False, threaded=True"
    #app.run(debug=False, threaded=True)
    app.run(debug=True)