问:
Passing formatted string and actual parameters to stored procedure from C#
I execute a stored procedure as follows:

```<code>exec SALESREPORTFORWEB
         @StartDate = '03/20/2017', @EndDate = '03/21/2017'
</code>```

Stored Procedure

```<code>CREATE proc [dbo].[SALESREPORTFORWEB]
--SALESREPORTFORWEB @StartDate='03-20-2017' ,@EndDate='03-28-2017',@usercode in ('2739','1609')

@StartDate DATETIME =NULL ,
@EndDate DATETIME =NULL ,
@ITEMCODE VARCHAR(100)=NULL,
@ITEMDESCRIPTION VARCHAR(100)=NULL,
@CLIENTCODE Varchar(25) = null,
@CLIENTNAME VARCHAR(100)=NULL,
@CLIENTBRANCHCODE VARCHAR(100)=NULL,
@CLIENTBRANCHNAME VARCHAR(100)=NULL,
@BRANDCODE VARCHAR (25)=NULL,
@BRANDNAME VARCHAR(100)=NULL,
@USERCODE VARCHAR(25)=NULL,
@USERNAME VARCHAR(100)=NULL,
@SUBCHANNEL VARCHAR(25)=NULL
AS

SELECT  H.UserCode,U.SALESMANNAME, CONVERT(CHAR(10), H.TrxDate, 103) AS DATE,D.ItemCode,I.Description AS ITEMDESCRIPTION,d.ItemGroupLevel5 AS BRANDCODE,
B.Description AS BRANDNAME,
 H.ClientCode,
C1.Description AS Client,H.ClientBranchCode,C2.Description, C2.SubChannelCode AS BRANCHSUBCHANNEL,

ROUND(
SUM(
CASE WHEN D.QuantityLevel1 > 0 THEN
D.QuantityLevel1 * PriceUsedLevel1
ELSE
D.QuantityLevel3 * PriceUsedLevel3
END - ISNULL(D.TotalDiscountAmount, 0)
), 2) AS TrxAmount,SUM(D.QuantityBU) AS QTY
FROM tblTrxHeader H INNER JOIN
tblTrxDetail D ON H.TrxCode = D.TrxCode AND D.TrxStatus > 0  INNER JOIN
tblBrand  B ON B.Code=D.ITEMGROUPLEVEL5 INNER JOIN
tblClient C1 ON H.ClientCode = C1.Code
INNER JOIN tblClient C2 ON H.ClientBranchCode=C2.Code
INNER JOIN TBLITEM I ON I.ITEMCODE=D.ITEMCODE
/*LEFT OUTER JOIN
tblRegion R ON R.Code = C.RegionCode*/ LEFT OUTER JOIN
vw_UnitManagers U ON U.SalesmanCode = H.UserCode
WHERE
H.TrxType IN (1) AND
DATEDIFF(dd,H.TrxDate,ISNULL(@StartDate,GETDATE())) <= 0 AND DATEDIFF(dd,H.TrxDate,ISNULL(@EndDate,GETDATE())) >= 0 AND
D.ITEMCODE= ISNULL(@ITEMCODE,D.ITEMCODE) AND
H.CLIENTCODE= ISNULL(@CLIENTCODE,H.CLIENTCODE)AND
H.ClientBranchCode=ISNULL(@CLIENTBRANCHCODE,H.ClientBranchCode) AND
D.ItemGroupLevel5=ISNULL(@BRANDCODE,D.ItemGroupLevel5)AND
H.UserCode in (ISNULL(@USERCODE,H.UserCode)) AND
C2.SubChannelCode=ISNULL(@SUBCHANNEL,C2.SubChannelCode)AND
B.Description LIKE('%'+ISNULL(@BRANDNAME,B.Description)+'%')AND
I.Description LIKE('%'+ISNULL(@ITEMDESCRIPTION,I.Description)+'%')AND
C1.Description LIKE('%'+ISNULL(@CLIENTNAME,C1.Description)+'%')AND
C2.Description LIKE('%'+ISNULL(@CLIENTBRANCHNAME,C2.Description)+'%')AND
U.SalesmanName LIKE('%'+ISNULL(@USERNAME,U.SalesmanName)+'%')

GROUP BY
--CONVERT(VARCHAR, H.TrxDate, 101),
 H.UserCode,U.SALESMANNAME,H.TRXDATE,D.itemcode,I.Description,d.ItemGroupLevel5,
B.Description, H.ClientCode,C1.Description,H.ClientBranchCode,C2.Description, C2.SubChannelCode
ORDER BY H.TrxDate
</code>```

where @StartDate = '03/20/2017' and @EndDate = '03/21/2017' are the parameters of the stored procedure.

In my code this is how it looks:

```<code>var salesDataQuery = SalesDataModel.FromSql("exec SALESREPORTFORWEB '@StartDate='@StartDate, '@EndData='@EndData",
                new SqlParameter("@StartDate", startdate),
                new SqlParameter("@EndData", enddate));
</code>```

But this code throws an error:

Invalid syntax error near '@StartDate='

Can somebody help me make the right stored procedure call?

Many thanks!

答:
How about cropping parameters form exec like that:

```<code>var salesDataQuery = SalesDataModel.FromSql("exec SALESREPORTFORWEB @StartDate, @EndDate",
                new SqlParameter("@StartDate", startdate),
                new SqlParameter("@EndData", enddate));
</code>```

Edit: added parameters to procedure.

Body:
I execute a stored procedure as follows:

exec SALESREPORTFORWEB
         @StartDate = '03/20/2017', @EndDate = '03/21/2017'

Stored Procedure

CREATE proc [dbo].[SALESREPORTFORWEB]
--SALESREPORTFORWEB @StartDate='03-20-2017' ,@EndDate='03-28-2017',@usercode in ('2739','1609')

@StartDate DATETIME =NULL ,
@EndDate DATETIME =NULL ,
@ITEMCODE VARCHAR(100)=NULL,
@ITEMDESCRIPTION VARCHAR(100)=NULL,
@CLIENTCODE Varchar(25) = null,
@CLIENTNAME VARCHAR(100)=NULL,
@CLIENTBRANCHCODE VARCHAR(100)=NULL,
@CLIENTBRANCHNAME VARCHAR(100)=NULL,
@BRANDCODE VARCHAR (25)=NULL,
@BRANDNAME VARCHAR(100)=NULL,
@USERCODE VARCHAR(25)=NULL,
@USERNAME VARCHAR(100)=NULL,
@SUBCHANNEL VARCHAR(25)=NULL
AS

SELECT  H.UserCode,U.SALESMANNAME, CONVERT(CHAR(10), H.TrxDate, 103) AS DATE,D.ItemCode,I.Description AS ITEMDESCRIPTION,d.ItemGroupLevel5 AS BRANDCODE,
B.Description AS BRANDNAME,
 H.ClientCode,
C1.Description AS Client,H.ClientBranchCode,C2.Description, C2.SubChannelCode AS BRANCHSUBCHANNEL,

ROUND(
SUM(
CASE WHEN D.QuantityLevel1 > 0 THEN
D.QuantityLevel1 * PriceUsedLevel1
ELSE
D.QuantityLevel3 * PriceUsedLevel3
END - ISNULL(D.TotalDiscountAmount, 0)
), 2) AS TrxAmount,SUM(D.QuantityBU) AS QTY
FROM tblTrxHeader H INNER JOIN
tblTrxDetail D ON H.TrxCode = D.TrxCode AND D.TrxStatus > 0  INNER JOIN
tblBrand  B ON B.Code=D.ITEMGROUPLEVEL5 INNER JOIN
tblClient C1 ON H.ClientCode = C1.Code
INNER JOIN tblClient C2 ON H.ClientBranchCode=C2.Code
INNER JOIN TBLITEM I ON I.ITEMCODE=D.ITEMCODE
/*LEFT OUTER JOIN
tblRegion R ON R.Code = C.RegionCode*/ LEFT OUTER JOIN
vw_UnitManagers U ON U.SalesmanCode = H.UserCode
WHERE
H.TrxType IN (1) AND
DATEDIFF(dd,H.TrxDate,ISNULL(@StartDate,GETDATE())) <= 0 AND DATEDIFF(dd,H.TrxDate,ISNULL(@EndDate,GETDATE())) >= 0 AND
D.ITEMCODE= ISNULL(@ITEMCODE,D.ITEMCODE) AND
H.CLIENTCODE= ISNULL(@CLIENTCODE,H.CLIENTCODE)AND
H.ClientBranchCode=ISNULL(@CLIENTBRANCHCODE,H.ClientBranchCode) AND
D.ItemGroupLevel5=ISNULL(@BRANDCODE,D.ItemGroupLevel5)AND
H.UserCode in (ISNULL(@USERCODE,H.UserCode)) AND
C2.SubChannelCode=ISNULL(@SUBCHANNEL,C2.SubChannelCode)AND
B.Description LIKE('%'+ISNULL(@BRANDNAME,B.Description)+'%')AND
I.Description LIKE('%'+ISNULL(@ITEMDESCRIPTION,I.Description)+'%')AND
C1.Description LIKE('%'+ISNULL(@CLIENTNAME,C1.Description)+'%')AND
C2.Description LIKE('%'+ISNULL(@CLIENTBRANCHNAME,C2.Description)+'%')AND
U.SalesmanName LIKE('%'+ISNULL(@USERNAME,U.SalesmanName)+'%')

GROUP BY
--CONVERT(VARCHAR, H.TrxDate, 101),
 H.UserCode,U.SALESMANNAME,H.TRXDATE,D.itemcode,I.Description,d.ItemGroupLevel5,
B.Description, H.ClientCode,C1.Description,H.ClientBranchCode,C2.Description, C2.SubChannelCode
ORDER BY H.TrxDate

where @StartDate = '03/20/2017' and @EndDate = '03/21/2017' are the parameters of the stored procedure.

In my code this is how it looks:

var salesDataQuery = SalesDataModel.FromSql("exec SALESREPORTFORWEB '@StartDate='@StartDate, '@EndData='@EndData",
                new SqlParameter("@StartDate", startdate),
                new SqlParameter("@EndData", enddate));

But this code throws an error:

Invalid syntax error near '@StartDate='

Can somebody help me make the right stored procedure call?

Many thanks!

Body:
How about cropping parameters form exec like that:

var salesDataQuery = SalesDataModel.FromSql("exec SALESREPORTFORWEB @StartDate, @EndDate",
                new SqlParameter("@StartDate", startdate),
                new SqlParameter("@EndData", enddate));

Edit: added parameters to procedure.


来源: stackexchange

问:
Remove value from array if it isn't present in another array Javascript
I have an Ember application with which I am building a notification system, if the notification gets dismissed by my user I store the notifications UUID in my cookie so it doesn't get displayed again.

After a month my notifications get deleted from the database, what I am trying to do is check my database and get an array of all the notifications and then compare the UUIDS to my cookies array.

If a UUID exists in my cookies array that doesn't exist in my database I want to delete it from the cookies array.

Here is my code.

```<code>this.get('userNotificationServices').fetch().then(allNotifications => {
    if (this.getCookie("dismissed-notifications")) {
        var notificationIdsInCookie = this.getCookie("dismissed-notifications").split(',');
        notificationIdsInCookie.forEach(function (value) {
            var index = allNotifications.findIndex(x => x.id === value);
            if (index === -1) {
                notificationIdsInCookie.splice(index, 1);
            }
        });

        this.setCookie("dismissed-notifications", notificationIdsInCookie);
    }
});
</code>```

At the moment it seems to be removing the wrong values in the array, for example it removes the last array value instead of the first and then removes every value from the array. Am I doing something wrong with my filtering / is my logic wrong?

Thank you.

答:
I would strongly advice against modifying the original array with a
  foreach loop and instead create a new one.

You can use Array.prototype.filter for that:

notificationIds  = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
allNotifications = [1, 3, 10];

filtered = notificationIds.filter(id => !allNotifications.includes(id));

console.log(filtered);```

Replace !allNotifications.includes(id) with the function you use.

ContentLicense: CC BY-SA 3.0

Body:
I have an Ember application with which I am building a notification system, if the notification gets dismissed by my user I store the notifications UUID in my cookie so it doesn't get displayed again.

After a month my notifications get deleted from the database, what I am trying to do is check my database and get an array of all the notifications and then compare the UUIDS to my cookies array.

If a UUID exists in my cookies array that doesn't exist in my database I want to delete it from the cookies array.

Here is my code.

this.get('userNotificationServices').fetch().then(allNotifications => {
    if (this.getCookie("dismissed-notifications")) {
        var notificationIdsInCookie = this.getCookie("dismissed-notifications").split(',');
        notificationIdsInCookie.forEach(function (value) {
            var index = allNotifications.findIndex(x => x.id === value);
            if (index === -1) {
                notificationIdsInCookie.splice(index, 1);
            }
        });

        this.setCookie("dismissed-notifications", notificationIdsInCookie);
    }
});

At the moment it seems to be removing the wrong values in the array, for example it removes the last array value instead of the first and then removes every value from the array. Am I doing something wrong with my filtering / is my logic wrong?

Thank you.

Body:
I would strongly advice against modifying the original array with a
  foreach loop and instead create a new one.

You can use Array.prototype.filter for that:

notificationIds  = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
allNotifications = [1, 3, 10];

filtered = notificationIds.filter(id => !allNotifications.includes(id));

console.log(filtered);

Replace !allNotifications.includes(id) with the function you use.


问:
Multi-column minimal representation discovery in perl
I have a csv of data with about 20 columns and each column will have more than one distinct value. Each row after the top one which is the header, is an individual data sample. I want to narrow the list down programatically so that I have the smallest number of data samples but each permutation of the column data is still represented.

Example data

```<code>SERIAL,ACTIVE,COLOR,CLASS,SEASON,SEATS
.0xb468d47cc9749fb862990426ff79aafb,T,GREEN,BETA,SUMMER,3
.0x847129b35bad62f5837eec30dc07a8a4,T,VIOLET,DELTA,SUMMER,1
.0x14b8df88fd6d6547e387f4caa99e52fd,F,ORANGE,ALPHA,SUMMER,4
.0x0a07fb97224caf79ea73d3fdd5495b8f,T,YELLOW,DELTA,WINTER,1
.0x7d747e689bb27b60198283d7b86db409,F,READ,DELTA,SPRING,2
.0x8247524df49bd19c4c316ee070a2dd4a,T,BLUE,GAMA,WINTER,2
.0x4103ed42af6e8e463708a6c629907fb5,T,YELLOW,ALPHA,SPRING,5
.0xc38deea7f02fbfbcdde1d3718d6decb4,T,YELLOW,DELTA,FALL,5
.0xa3d562edcf64e151d7de08ff8f8e0a94,F,VIOLET,DELTA,SUMMER,3
.0x9da58b3b05603325c24629f700c25c97,T,YELLOW,OMEGA,SPRING,4
.0xef0c0e75083229d654c9b111e3af8726,T,BLUE,GAMA,FALL,1
.0xa9022c8713f0aba2a8e1d20475a3104a,T,YELLOW,BETA,SUMMER,2
.0x5bb5f73e6030730610866cee80cfc2fb,F,ORANGE,BETA,FALL,5
.0xc202e5b43dd65525754fdc52b89e7375,T,BLUE,OMEGA,SUMMER,3
.0xfac9145af33a74aedae7cc0442426432,F,READ,BETA,SPRING,1
.0x457949648053f710b4f2d55cb237a91d,T,GREEN,BETA,SPRING,3
.0xed94d4df300f10f5c4dc5d3ac76cf9e5,F,VIOLET,ALPHA,WINTER,15
.0x870130135beed4cbbe06478e368b40b3,F,YELLOW,ALPHA,SPRING,3
.0x3b6f17841edb9651e732e3ffbacbe14a,T,GREEN,OMEGA,SUMMER,3
.0xfb30e054466b9e4cf944c8e48ff74c93,F,VIOLET,DELTA,SUMMER,8
.0xf741ddc71b4a667585acaa35b67dc6c9,F,BLUE,BETA,FALL,4
.0x60257ad6c299e466086cc6e5bb0a9a33,F,VIOLET,OMEGA,SPRING,1
.0xa5d208bfee5a27a7619ba07dcbdaeea0,T,GREEN,OMEGA,FALL,1
.0x53bc78fa8863e53e8c9fb11c5f6d2320,F,GREEN,GAMA,SPRING,2
.0x5a01253ce5cb0a6aa5213f34f0b35416,T,READ,BETA,WINTER,3
.0xaed9a979ba9f6fbf39895b610dde80f4,T,ORANGE,DELTA,WINTER,1
.0xe7769918e36671af77b5d3d59ea15cfe,T,ORANGE,OMEGA,FALL,4
.0x9e5327a1583332e4c56d29c356dbc5d2,T,INDEGO,ALPHA,WINTER,5
.0x79c5c70732ff04b4d00e81ac3a07c3b7,T,READ,OMEGA,FALL,5
.0x55f54d3c9cd2552e286364894aeef62a,F,READ,GAMA,SPRING,15
</code>```

答:
Use a hash to determine whether you have seen a particular column combination before, and then use that to determine whether to print a particular line.

Here is a rather basic example to demonstrate the idea:

filter.pl

```<code>#!/usr/bin/env perl

use warnings;
use strict;

die "usage: $0 file col1,col2,col3, ... coln\n" unless @ARGV;
my ($file, $columns) = @ARGV;
-f $file or die "$file does not exist!";
defined $columns or die "need to pass in columns!";

my @columns;
for my $col ( split /,/, $columns ) {
    die "Invalid column id $col" unless $col >= 1; # 1-based
    push @columns, $col - 1; # 0-based
}
scalar @columns or die "No columns!";

open my $fh, "<", $file or die "Unable to open $file : $!";
my %uniq;
while (<$fh>) {
    chomp();
    next if $. == 1; # Skip Header
    my (@data) = split /,/, $_; # Use Text::CSV for any non-trivial csv file
    my $key = join '|', @data[ @columns ]; # key will look like 'foo|bar|baz'
    if (not defined $uniq{ $key } ) {
        print $_ . "\n"; # Print the whole line with the first unique set of columns
        $uniq{ $key } = 1; # Now we have seen this combo
    }
}
</code>```

data.csv

```<code>SERIAL,TRUTH,IN,PARALLEL
123,TRUE,YES,5
124,TRUE,YES,5
125,TRUE,YES,3
126,TRUE,NO,5
127,FALSE,YES,1
128,FALSE,YES,3
129,FALSE,NO,7
</code>```

Output

```<code>perl filter.pl data.csv 2,3
123,TRUE,YES,5
126,TRUE,NO,5
127,FALSE,YES,1
129,FALSE,NO,7
</code>```

Body:
I have a csv of data with about 20 columns and each column will have more than one distinct value. Each row after the top one which is the header, is an individual data sample. I want to narrow the list down programatically so that I have the smallest number of data samples but each permutation of the column data is still represented.

Example data

SERIAL,ACTIVE,COLOR,CLASS,SEASON,SEATS
.0xb468d47cc9749fb862990426ff79aafb,T,GREEN,BETA,SUMMER,3
.0x847129b35bad62f5837eec30dc07a8a4,T,VIOLET,DELTA,SUMMER,1
.0x14b8df88fd6d6547e387f4caa99e52fd,F,ORANGE,ALPHA,SUMMER,4
.0x0a07fb97224caf79ea73d3fdd5495b8f,T,YELLOW,DELTA,WINTER,1
.0x7d747e689bb27b60198283d7b86db409,F,READ,DELTA,SPRING,2
.0x8247524df49bd19c4c316ee070a2dd4a,T,BLUE,GAMA,WINTER,2
.0x4103ed42af6e8e463708a6c629907fb5,T,YELLOW,ALPHA,SPRING,5
.0xc38deea7f02fbfbcdde1d3718d6decb4,T,YELLOW,DELTA,FALL,5
.0xa3d562edcf64e151d7de08ff8f8e0a94,F,VIOLET,DELTA,SUMMER,3
.0x9da58b3b05603325c24629f700c25c97,T,YELLOW,OMEGA,SPRING,4
.0xef0c0e75083229d654c9b111e3af8726,T,BLUE,GAMA,FALL,1
.0xa9022c8713f0aba2a8e1d20475a3104a,T,YELLOW,BETA,SUMMER,2
.0x5bb5f73e6030730610866cee80cfc2fb,F,ORANGE,BETA,FALL,5
.0xc202e5b43dd65525754fdc52b89e7375,T,BLUE,OMEGA,SUMMER,3
.0xfac9145af33a74aedae7cc0442426432,F,READ,BETA,SPRING,1
.0x457949648053f710b4f2d55cb237a91d,T,GREEN,BETA,SPRING,3
.0xed94d4df300f10f5c4dc5d3ac76cf9e5,F,VIOLET,ALPHA,WINTER,15
.0x870130135beed4cbbe06478e368b40b3,F,YELLOW,ALPHA,SPRING,3
.0x3b6f17841edb9651e732e3ffbacbe14a,T,GREEN,OMEGA,SUMMER,3
.0xfb30e054466b9e4cf944c8e48ff74c93,F,VIOLET,DELTA,SUMMER,8
.0xf741ddc71b4a667585acaa35b67dc6c9,F,BLUE,BETA,FALL,4
.0x60257ad6c299e466086cc6e5bb0a9a33,F,VIOLET,OMEGA,SPRING,1
.0xa5d208bfee5a27a7619ba07dcbdaeea0,T,GREEN,OMEGA,FALL,1
.0x53bc78fa8863e53e8c9fb11c5f6d2320,F,GREEN,GAMA,SPRING,2
.0x5a01253ce5cb0a6aa5213f34f0b35416,T,READ,BETA,WINTER,3
.0xaed9a979ba9f6fbf39895b610dde80f4,T,ORANGE,DELTA,WINTER,1
.0xe7769918e36671af77b5d3d59ea15cfe,T,ORANGE,OMEGA,FALL,4
.0x9e5327a1583332e4c56d29c356dbc5d2,T,INDEGO,ALPHA,WINTER,5
.0x79c5c70732ff04b4d00e81ac3a07c3b7,T,READ,OMEGA,FALL,5
.0x55f54d3c9cd2552e286364894aeef62a,F,READ,GAMA,SPRING,15

Body:
Use a hash to determine whether you have seen a particular column combination before, and then use that to determine whether to print a particular line.

Here is a rather basic example to demonstrate the idea:

filter.pl

#!/usr/bin/env perl

use warnings;
use strict;

die "usage: $0 file col1,col2,col3, ... coln\n" unless @ARGV;
my ($file, $columns) = @ARGV;
-f $file or die "$file does not exist!";
defined $columns or die "need to pass in columns!";

my @columns;
for my $col ( split /,/, $columns ) {
    die "Invalid column id $col" unless $col >= 1; # 1-based
    push @columns, $col - 1; # 0-based
}
scalar @columns or die "No columns!";

open my $fh, "<", $file or die "Unable to open $file : $!";
my %uniq;
while (<$fh>) {
    chomp();
    next if $. == 1; # Skip Header
    my (@data) = split /,/, $_; # Use Text::CSV for any non-trivial csv file
    my $key = join '|', @data[ @columns ]; # key will look like 'foo|bar|baz'
    if (not defined $uniq{ $key } ) {
        print $_ . "\n"; # Print the whole line with the first unique set of columns
        $uniq{ $key } = 1; # Now we have seen this combo
    }
}

data.csv

SERIAL,TRUTH,IN,PARALLEL
123,TRUE,YES,5
124,TRUE,YES,5
125,TRUE,YES,3
126,TRUE,NO,5
127,FALSE,YES,1
128,FALSE,YES,3
129,FALSE,NO,7

Output

perl filter.pl data.csv 2,3
123,TRUE,YES,5
126,TRUE,NO,5
127,FALSE,YES,1
129,FALSE,NO,7


问:
Count number of comments from arrays in javascript
I have array structure like this:

```<code>[Array[2].attributes, Array[6].attributes] contains list of objects
</code>```

The first array contain blog posts with post_id and the second array contains blog comments with comment, comment_id and post_id

I want to count how many comments for each post and insert the count in the first array (i.e blog posts array) for each object of post_id

Complete structure:

```<code>[
   [
      {
         "attributes":{
            "created_at":"3/30/2017, 1:33:37 AM",
            "details":"aaa",
            "id":116,
            "post_id":"1490817817738",
            "title":" Technologies - Learn to code Java, Spring, Angular etc",
            "url":"-technologies---learn-to-code-java,-spring,-angular-etc",
            "userImage":"assets/img/spiritual-icon4.png",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "created_at":"3/30/2017, 12:11:28 PM",
            "details":"aaa",
            "id":117,
            "post_id":"1490856088450",
            "title":"Express JS Tutorial",
            "url":"express-js-tutorial",
            "userImage":"assets/img/spiritual-icon4.png",
            "username":".k999@gmail.com"
         }
      }
   ],
   [
      {
         "attributes":{
            "comment_id":"1490817936990",
            "content":"hi",
            "created_at":"2017-03-29 20:05:36",
            "id":28,
            "likes":"",
            "post_id":"1490817817738",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "comment_id":"1490856043965",
            "content":"hi",
            "created_at":"2017-03-30 06:40:43",
            "id":29,
            "likes":"",
            "post_id":"1490817817738",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "comment_id":"1490856048963",
            "content":"hwllo",
            "created_at":"2017-03-30 06:40:48",
            "id":30,
            "likes":"",
            "post_id":"1490817817738",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "comment_id":"1490856056938",
            "content":"hello",
            "created_at":"2017-03-30 06:40:56",
            "id":31,
            "likes":"",
            "post_id":"1490817817738",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "comment_id":"1490856093828",
            "content":"aaa",
            "created_at":"2017-03-30 06:41:33",
            "id":32,
            "likes":"",
            "post_id":"1490856088450",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         },
      },
      {
         "attributes":{
            "comment_id":"1490856096261",
            "content":"sss",
            "created_at":"2017-03-30 06:41:36",
            "id":33,
            "likes":"",
            "post_id":"1490856088450",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         },
      }
   ]
]
</code>```

I have been trying it like this but couldn't get it work:

```<code>var commentCount = Object.create(null);
self.postId = Object.create(null);

res[1].forEach(function(el , i) {
    console.log('el ', el);
   commentCount[el.attributes.post_id] = (commentCount[el.attributes.comment_id] || 0) +1;
});
console.log('self.commentCount ', commentCount);
</code>```

Update:

```<code>self.data.topics = [];
var commentCount = Object.create(null);

res.forEach(function(obj){
    self.data.topics.push(obj[0].attributes);
});

res[1].forEach(function (el, i) {
    commentCount[el.attributes.post_id] = (commentCount[el.attributes.post_id] || 0) + 1;
});
console.log('commentCount ', commentCount);

DataMixin.data.topics = self.data.topics;
</code>```

答:
Basically you do not use the same reference of post_id.

```<code>commentCount[el.attributes.post_id] = (commentCount[el.attributes.comment_id] || 0) + 1
//                         ^^^^^^^                                ^^^^^^^^^^
</code>```

But you need

```<code>commentCount[el.attributes.post_id] = (commentCount[el.attributes.post_id] || 0) + 1
//                         ^^^^^^^                                ^^^^^^^
</code>```

You could iterate the second array and count the occurence of a given post_id

var data = [[{ attributes: { created_at: "3/30/2017, 1:33:37 AM", details: "aaa", id: 116, post_id: 1490817817738, title: " Technologies - Learn to code Java, Spring, Angular etc", url: "-technologies---learn-to-code-java,-spring,-angular-etc", userImage: "assets/img/spiritual-icon4.png", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, details: { columnName: "details", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, title: { columnName: "title", typeName: "TEXT", columnSize: 65535 }, url: { columnName: "url", typeName: "VARCHAR", columnSize: 1000 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 45 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 45 } }, associations: [{ fkName: "post_id", source: "com..seeker.models.Post", target: "com..seeker.models.PostsCategories" }, { fkName: "post_id", source: "com..seeker.models.Post", target: "com..seeker.models.Comment" }], idName: "id", tableName: "post", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Post", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { created_at: "3/30/2017, 12:11:28 PM", details: "aaa", id: 117, post_id: 1490856088450, title: "Express JS Tutorial", url: "express-js-tutorial", userImage: "assets/img/spiritual-icon4.png", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, details: { columnName: "details", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, title: { columnName: "title", typeName: "TEXT", columnSize: 65535 }, url: { columnName: "url", typeName: "VARCHAR", columnSize: 1000 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 45 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 45 } }, associations: [{ fkName: "post_id", source: "com..seeker.models.Post", target: "com..seeker.models.PostsCategories" }, { fkName: "post_id", source: "com..seeker.models.Post", target: "com..seeker.models.Comment" }], idName: "id", tableName: "post", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Post", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }], [{ attributes: { comment_id: 1490817936990, content: "hi", created_at: "2017-03-29 20:05:36", id: 28, likes: 0, post_id: 1490817817738, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856043965, content: "hi", created_at: "2017-03-30 06:40:43", id: 29, likes: 0, post_id: 1490817817738, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856048963, content: "hwllo", created_at: "2017-03-30 06:40:48", id: 30, likes: 0, post_id: 1490817817738, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856056938, content: "hello", created_at: "2017-03-30 06:40:56", id: 31, likes: 0, post_id: 1490817817738, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856093828, content: "aaa", created_at: "2017-03-30 06:41:33", id: 32, likes: 0, post_id: 1490856088450, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856096261, content: "sss", created_at: "2017-03-30 06:41:36", id: 33, likes: 0, post_id: 1490856088450, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }]],
        count = Object.create(null);

data[1].forEach(function (a) {
    count[a.attributes.post_id] = (count[a.attributes.post_id] || 0) + 1;
});

console.log(count);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have array structure like this:

[Array[2].attributes, Array[6].attributes] contains list of objects

The first array contain blog posts with post_id and the second array contains blog comments with comment, comment_id and post_id

I want to count how many comments for each post and insert the count in the first array (i.e blog posts array) for each object of post_id

Complete structure:

[
   [
      {
         "attributes":{
            "created_at":"3/30/2017, 1:33:37 AM",
            "details":"aaa",
            "id":116,
            "post_id":"1490817817738",
            "title":" Technologies - Learn to code Java, Spring, Angular etc",
            "url":"-technologies---learn-to-code-java,-spring,-angular-etc",
            "userImage":"assets/img/spiritual-icon4.png",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "created_at":"3/30/2017, 12:11:28 PM",
            "details":"aaa",
            "id":117,
            "post_id":"1490856088450",
            "title":"Express JS Tutorial",
            "url":"express-js-tutorial",
            "userImage":"assets/img/spiritual-icon4.png",
            "username":".k999@gmail.com"
         }
      }
   ],
   [
      {
         "attributes":{
            "comment_id":"1490817936990",
            "content":"hi",
            "created_at":"2017-03-29 20:05:36",
            "id":28,
            "likes":"",
            "post_id":"1490817817738",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "comment_id":"1490856043965",
            "content":"hi",
            "created_at":"2017-03-30 06:40:43",
            "id":29,
            "likes":"",
            "post_id":"1490817817738",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "comment_id":"1490856048963",
            "content":"hwllo",
            "created_at":"2017-03-30 06:40:48",
            "id":30,
            "likes":"",
            "post_id":"1490817817738",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "comment_id":"1490856056938",
            "content":"hello",
            "created_at":"2017-03-30 06:40:56",
            "id":31,
            "likes":"",
            "post_id":"1490817817738",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         }
      },
      {
         "attributes":{
            "comment_id":"1490856093828",
            "content":"aaa",
            "created_at":"2017-03-30 06:41:33",
            "id":32,
            "likes":"",
            "post_id":"1490856088450",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         },
      },
      {
         "attributes":{
            "comment_id":"1490856096261",
            "content":"sss",
            "created_at":"2017-03-30 06:41:36",
            "id":33,
            "likes":"",
            "post_id":"1490856088450",
            "userImage":"https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
            "username":".k999@gmail.com"
         },
      }
   ]
]

I have been trying it like this but couldn't get it work:

var commentCount = Object.create(null);
self.postId = Object.create(null);

res[1].forEach(function(el , i) {
    console.log('el ', el);
   commentCount[el.attributes.post_id] = (commentCount[el.attributes.comment_id] || 0) +1;
});
console.log('self.commentCount ', commentCount);

Update:

self.data.topics = [];
var commentCount = Object.create(null);

res.forEach(function(obj){
    self.data.topics.push(obj[0].attributes);
});

res[1].forEach(function (el, i) {
    commentCount[el.attributes.post_id] = (commentCount[el.attributes.post_id] || 0) + 1;
});
console.log('commentCount ', commentCount);

DataMixin.data.topics = self.data.topics;

Body:
Basically you do not use the same reference of post_id.

commentCount[el.attributes.post_id] = (commentCount[el.attributes.comment_id] || 0) + 1
//                         ^^^^^^^                                ^^^^^^^^^^

But you need

commentCount[el.attributes.post_id] = (commentCount[el.attributes.post_id] || 0) + 1
//                         ^^^^^^^                                ^^^^^^^

You could iterate the second array and count the occurence of a given post_id

var data = [[{ attributes: { created_at: "3/30/2017, 1:33:37 AM", details: "aaa", id: 116, post_id: 1490817817738, title: " Technologies - Learn to code Java, Spring, Angular etc", url: "-technologies---learn-to-code-java,-spring,-angular-etc", userImage: "assets/img/spiritual-icon4.png", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, details: { columnName: "details", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, title: { columnName: "title", typeName: "TEXT", columnSize: 65535 }, url: { columnName: "url", typeName: "VARCHAR", columnSize: 1000 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 45 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 45 } }, associations: [{ fkName: "post_id", source: "com..seeker.models.Post", target: "com..seeker.models.PostsCategories" }, { fkName: "post_id", source: "com..seeker.models.Post", target: "com..seeker.models.Comment" }], idName: "id", tableName: "post", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Post", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { created_at: "3/30/2017, 12:11:28 PM", details: "aaa", id: 117, post_id: 1490856088450, title: "Express JS Tutorial", url: "express-js-tutorial", userImage: "assets/img/spiritual-icon4.png", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, details: { columnName: "details", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, title: { columnName: "title", typeName: "TEXT", columnSize: 65535 }, url: { columnName: "url", typeName: "VARCHAR", columnSize: 1000 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 45 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 45 } }, associations: [{ fkName: "post_id", source: "com..seeker.models.Post", target: "com..seeker.models.PostsCategories" }, { fkName: "post_id", source: "com..seeker.models.Post", target: "com..seeker.models.Comment" }], idName: "id", tableName: "post", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Post", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }], [{ attributes: { comment_id: 1490817936990, content: "hi", created_at: "2017-03-29 20:05:36", id: 28, likes: 0, post_id: 1490817817738, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856043965, content: "hi", created_at: "2017-03-30 06:40:43", id: 29, likes: 0, post_id: 1490817817738, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856048963, content: "hwllo", created_at: "2017-03-30 06:40:48", id: 30, likes: 0, post_id: 1490817817738, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856056938, content: "hello", created_at: "2017-03-30 06:40:56", id: 31, likes: 0, post_id: 1490817817738, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856093828, content: "aaa", created_at: "2017-03-30 06:41:33", id: 32, likes: 0, post_id: 1490856088450, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }, { attributes: { comment_id: 1490856096261, content: "sss", created_at: "2017-03-30 06:41:36", id: 33, likes: 0, post_id: 1490856088450, userImage: "https://lh3.googleusercontent.com/-/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50", username: ".k999@gmail.com" }, dirtyAttributeNames: [], frozen: false, metaModelLocal: { columnMetadata: { comment_id: { columnName: "comment_id", typeName: "TEXT", columnSize: 65535 }, content: { columnName: "content", typeName: "TEXT", columnSize: 65535 }, created_at: { columnName: "created_at", typeName: "TEXT", columnSize: 65535 }, id: { columnName: "id", typeName: "MEDIUMINT", columnSize: 7 }, likes: { columnName: "likes", typeName: "TEXT", columnSize: 65535 }, post_id: { columnName: "post_id", typeName: "TEXT", columnSize: 65535 }, updated_at: { columnName: "updated_at", typeName: "TEXT", columnSize: 65535 }, userImage: { columnName: "userImage", typeName: "VARCHAR", columnSize: 200 }, username: { columnName: "username", typeName: "VARCHAR", columnSize: 200 } }, associations: [{ fkName: "comment_id", source: "com..seeker.models.Comment", target: "com..seeker.models.CommentRating" }, { fkName: "post_id", source: "com..seeker.models.Comment", target: "com..seeker.models.Post" }], idName: "id", tableName: "comment", dbType: "MySQL", dbName: "default", modelClass: "com..seeker.models.Comment", cached: false, versionColumn: "record_version" }, modelRegistryLocal: { callbacks: [], attributeConverters: {}, validators: [] }, cachedParents: {}, cachedChildren: {}, manageTime: true, compositeKeyPersisted: false, errors: {} }]],
        count = Object.create(null);

data[1].forEach(function (a) {
    count[a.attributes.post_id] = (count[a.attributes.post_id] || 0) + 1;
});

console.log(count);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
hiding li of a tree,using jQuery works in firefox but not in IE8
I am using jQuery to show and hide li elements of a tree(tree is build using ul and li elements ) based on some condition.
here is my code.

function filterLeftNavTree(filterData){

```<code>    if(filterData.indexOf("|")!=-1){

        $("ul.treeview").find("li").hide();

        var filterData = filterData.split("|");

        for(i=0;i<filterData.length;i++){
            $("ul.treeview").find("li").filter(":contains(\'"+filterData[i]+"\')").show();
        }
    }else{
        $("ul.treeview").find("li").hide().filter(":contains(\'"+filterData+"\')").show();
    }
</code>```

}

in this function what i am doing is, passing data which can be string seperated by | .
then first hiding all li, then showing only tjose li which matched to string passed to

function.
this function is working fine in Firefox but not in IE8.  any one can please tell me why?

any alternate solution is also good for  me.

guys plz help me out.

thanks

vivek

答:
i Solved this problem.
Actually, while picking data in filterData, it picks spaces too.
and filter function is case-sensitive, so its not working in ie8.
i just trimed those spaces and its working fine in ie8.

```<code>if(filterData.indexOf("|")!=-1){

        $("ul.treeview").find("li").hide();

        var filterData = filterData.split("|");

        for(i=0;i<filterData.length;i++){
            $("ul.treeview").find("li").filter(":contains(\'"+filterData[i].trim()+"\')").show();
        }
    }else{
        $("ul.treeview").find("li").hide().filter(":contains(\'"+filterData.trim()+"\')").show();
}
</code>```

any way, thanks to all of you.

Vivek

ContentLicense: CC BY-SA 2.5

Body:
I am using jQuery to show and hide li elements of a tree(tree is build using ul and li elements ) based on some condition.
here is my code.

function filterLeftNavTree(filterData){

    if(filterData.indexOf("|")!=-1){

        $("ul.treeview").find("li").hide();

        var filterData = filterData.split("|");

        for(i=0;i<filterData.length;i++){
            $("ul.treeview").find("li").filter(":contains(\'"+filterData[i]+"\')").show();
        }
    }else{
        $("ul.treeview").find("li").hide().filter(":contains(\'"+filterData+"\')").show();
    }

}

in this function what i am doing is, passing data which can be string seperated by | .
then first hiding all li, then showing only tjose li which matched to string passed to

function.
this function is working fine in Firefox but not in IE8.  any one can please tell me why?

any alternate solution is also good for  me.

guys plz help me out.

thanks

vivek

Body:
i Solved this problem.
Actually, while picking data in filterData, it picks spaces too.
and filter function is case-sensitive, so its not working in ie8.
i just trimed those spaces and its working fine in ie8.

if(filterData.indexOf("|")!=-1){

        $("ul.treeview").find("li").hide();

        var filterData = filterData.split("|");

        for(i=0;i<filterData.length;i++){
            $("ul.treeview").find("li").filter(":contains(\'"+filterData[i].trim()+"\')").show();
        }
    }else{
        $("ul.treeview").find("li").hide().filter(":contains(\'"+filterData.trim()+"\')").show();
}

any way, thanks to all of you.

Vivek


问:
SCNAction.wait not working in swift playgrounds
In my code I have a sequence in which I am telling swift to wait for a sequence to complete before i move on to another function however it seems to skip this and just move on

```<code>let earthSequence = SCNAction.sequence([SCNAction.wait(duration: 10),rollInGroup,rollOutGroup,earthNormalRotation])
defaultEarthNode.runAction(earthSequence)

nextFunction()
</code>```

the result is simply moving on to the next function without waiting 10 seconds

答:
That's because nextFunction() is called immediately after you start the action, it doesn't wait for it to be completed. runAction has a completionHandler you can use to know when the sequence has finished.

```<code>defaultEarthNode.runAction(earthSequence, completionHandler: {
    nextFunction()
})
</code>```

Body:
In my code I have a sequence in which I am telling swift to wait for a sequence to complete before i move on to another function however it seems to skip this and just move on

let earthSequence = SCNAction.sequence([SCNAction.wait(duration: 10),rollInGroup,rollOutGroup,earthNormalRotation])
defaultEarthNode.runAction(earthSequence)

nextFunction()

the result is simply moving on to the next function without waiting 10 seconds

Body:
That's because nextFunction() is called immediately after you start the action, it doesn't wait for it to be completed. runAction has a completionHandler you can use to know when the sequence has finished.

defaultEarthNode.runAction(earthSequence, completionHandler: {
    nextFunction()
})


问:
How to use variable defined inside setOnAction outside it?
I have searched all over the internet for a solution to this but nothing seems to work.

What I want to do is use the variable "poeni" that is modified when a button is clicked and display that result in a label that is outside the OnActionEvent.

Here is the part of my code that is giving me trouble.

```<code>//The button
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int poeni = 0; //The variable i want to use outside

                if(odgovor1_1.isSelected()) poeni++;
                if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
                if(odgovor3_2.isSelected()) poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);
</code>```

答:
As the name says, local variables are local to the scope they are defined in.

So, when you want that an instance of some anonymous inner class has a mean to communicate with the enclosing class, you have to use a field on that outer class.

Like:

```<code>class Example {
  private int counter = 0;

  void someMethod() {
    Button rezultat = new Button("Pogledajte Vas rezultat");
      rezultat.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            if(odgovor1_1.isSelected()) this.Example.poeni++;
...
</code>```

But of course, that requires careful thinking how things should come together on that top level - as it might not necessarily be that Example class where you want your fields to be.

Long story short - local variables are local to their scope; you need something that exists in an enclosing scope in order to propagate such information to the outside of your local scope.

Body:
I have searched all over the internet for a solution to this but nothing seems to work.

What I want to do is use the variable "poeni" that is modified when a button is clicked and display that result in a label that is outside the OnActionEvent.

Here is the part of my code that is giving me trouble.

//The button
        Button rezultat = new Button("Pogledajte Vas rezultat");
        rezultat.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int poeni = 0; //The variable i want to use outside

                if(odgovor1_1.isSelected()) poeni++;
                if(odgovor2_3.isSelected()) poeni++; //Theese if's check if the RadioButton is checked and increment if it is
                if(odgovor3_2.isSelected()) poeni++;
            }
        });

        //The label in which I want to display the results
        Label lbl_rezultat = new Label("Vas rezultat je: " + poeni);

Body:
As the name says, local variables are local to the scope they are defined in.

So, when you want that an instance of some anonymous inner class has a mean to communicate with the enclosing class, you have to use a field on that outer class.

Like:

class Example {
  private int counter = 0;

  void someMethod() {
    Button rezultat = new Button("Pogledajte Vas rezultat");
      rezultat.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            if(odgovor1_1.isSelected()) this.Example.poeni++;
...

But of course, that requires careful thinking how things should come together on that top level - as it might not necessarily be that Example class where you want your fields to be.

Long story short - local variables are local to their scope; you need something that exists in an enclosing scope in order to propagate such information to the outside of your local scope.


问:
Are Resharper's warnings about closures correct?
Today I faced following situation

```<code>public async Task<Stream> GetApproveDocumentAsync<T>(Guid id, int revision, PdfLayoutType pdfLayoutType, string resourceFilePath, CadDrawingType cadDrawingType, int approvalWidth, int approvalHeight, Action<T> fillModelAction = null) where T : BaseApproveModel, new() {
    var previewFileName = $"{id}_{revision}_preview.png";
    Stream previewFile;
    using (var resourceFileStream = new FileStream(resourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) {
        previewFile = await _cadApiService.ConvertDrawingToImageAsync(resourceFileStream, cadDrawingType, FileFormat.EVD, FileFormat.PNG, approvalWidth, approvalHeight).ConfigureAwait(false);
    }
    Func<string[], T> createBaseApproveModelFunc = graphicContentFilenames => { //Implicitly captured closure: previewFile
         var model = new T {
             GraphicContentFiles = graphicContentFilenames,
             CadPreview = previewFileName,
             Customer = _userService.GetCurrentOverrideCustomer()?.CustomerName
         };
         fillModelAction?.Invoke(model);
         return model;
    };
    Action<List<StreamWithFileName>> fillGraphicContentAction = currentGraphicContent => { //Implicitly captured closure: fillModelAction, this
        currentGraphicContent.Add(new StreamWithFileName {FileName = previewFileName, Stream = previewFile});
    };
    return await _apagoService.ConstcutPdf(pdfLayoutType, createBaseApproveModelFunc, fillGraphicContentAction).ConfigureAwait(false);
}
</code>```

I thought I know how closures work, but I can't understand ReSharper behaviour. Is ReSharper swap these two warnings by mistake (or bug)?

I'm using ReSharper Ultimate 2016.2.2

答:
I think that what resharper is telling you is that those two closures are also capturing additional things that your code doesn't think it is using in that lambda. The first closure uses previewFileName and this (for the field _userService), so your capture of those is clearly intentional - but : it might not be obvious to you that you're also capturing previewFile. The reason you capture additional things is because the scope of the items captured is the same, so the compiler generates a single closure to capture all of previewFile, this, previewFileName and fillModelAction - and the closure instance has two methods - one for the Func<string[], T> and one for the Action<List<StreamWithFileName>>. Note that previewFileName is used by both lambdas, so: no warning.

Understanding this may be important for garbage collection reasons - if one lambda lived much longer than the other, you might not want to keep additional things alive accidentally, hence the warning. For example, the fillGraphicContentAction lambda keeps the entire this alive (whatever this is), even though the lambda doesn't use this.

Body:
Today I faced following situation

public async Task<Stream> GetApproveDocumentAsync<T>(Guid id, int revision, PdfLayoutType pdfLayoutType, string resourceFilePath, CadDrawingType cadDrawingType, int approvalWidth, int approvalHeight, Action<T> fillModelAction = null) where T : BaseApproveModel, new() {
    var previewFileName = $"{id}_{revision}_preview.png";
    Stream previewFile;
    using (var resourceFileStream = new FileStream(resourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) {
        previewFile = await _cadApiService.ConvertDrawingToImageAsync(resourceFileStream, cadDrawingType, FileFormat.EVD, FileFormat.PNG, approvalWidth, approvalHeight).ConfigureAwait(false);
    }
    Func<string[], T> createBaseApproveModelFunc = graphicContentFilenames => { //Implicitly captured closure: previewFile
         var model = new T {
             GraphicContentFiles = graphicContentFilenames,
             CadPreview = previewFileName,
             Customer = _userService.GetCurrentOverrideCustomer()?.CustomerName
         };
         fillModelAction?.Invoke(model);
         return model;
    };
    Action<List<StreamWithFileName>> fillGraphicContentAction = currentGraphicContent => { //Implicitly captured closure: fillModelAction, this
        currentGraphicContent.Add(new StreamWithFileName {FileName = previewFileName, Stream = previewFile});
    };
    return await _apagoService.ConstcutPdf(pdfLayoutType, createBaseApproveModelFunc, fillGraphicContentAction).ConfigureAwait(false);
}

I thought I know how closures work, but I can't understand ReSharper behaviour. Is ReSharper swap these two warnings by mistake (or bug)?

I'm using ReSharper Ultimate 2016.2.2


问:
String cannot be cast to org.springframework.http.ResponseEntity
While using the following code, I'm getting a ClassCastException: String
cannot be cast to org.springframework.http.ResponseEntity.

```<code>@Autowired
private  ClientService clientService;

public void methodA() {
    String url = ...
    ResponseEntity<String> resEntity = clientService.callService(url);
}
</code>```

答:
Plese send the whole stacktrace to be sure of previous answers.

People here are probably right, but it seems strange that an IDE doesn't tell you that the return type of clientService.callService(url) is incompatible with the type of your variable...

Body:
While using the following code, I'm getting a ClassCastException: String
cannot be cast to org.springframework.http.ResponseEntity.

@Autowired
private  ClientService clientService;

public void methodA() {
    String url = ...
    ResponseEntity<String> resEntity = clientService.callService(url);
}


问:
Implementing isset() in a setter method
Is there any way to implement isset() in a setter method? That is, have the setter method check if the variable exists? From what I can tell no, but hopefully someone can confirm that for me. In a nutshell, I'm looking to avoid having to do

```<code>if (isset($arr[0])) $foo->setId($arr[0])
</code>```

and simply just do

```<code>$foo->setId($arr[0])
</code>```

and somehow implement the isset() logic in the setter method. Thanks!

答:
No.

You're only passing the value of $arr[0] to the setter method, not the $arr[0] variable. $foo::setId has no idea of the existence of $arr or $arr[0], all it gets to see is its value.

And that's a good thing for encapsulation! Imagine if every function would have to check if its parameters actually existed:

```<code>function setId($id) {
    // $id is defined, it's required (has no default value),
    // and yet I can't be sure it actually exists here...?
}
</code>```

You'll have to check if the variable exists before passing its value to a function.

Title: Implementing isset() in a setter method

Body:
Is there any way to implement isset() in a setter method? That is, have the setter method check if the variable exists? From what I can tell no, but hopefully someone can confirm that for me. In a nutshell, I'm looking to avoid having to do

if (isset($arr[0])) $foo->setId($arr[0])

and simply just do

$foo->setId($arr[0])

and somehow implement the isset() logic in the setter method. Thanks!

Body:
No.

You're only passing the value of $arr[0] to the setter method, not the $arr[0] variable. $foo::setId has no idea of the existence of $arr or $arr[0], all it gets to see is its value.

And that's a good thing for encapsulation! Imagine if every function would have to check if its parameters actually existed:

function setId($id) {
    // $id is defined, it's required (has no default value),
    // and yet I can't be sure it actually exists here...?
}

You'll have to check if the variable exists before passing its value to a function.


问:
Javascript OnClick toggle scroll
This code disables scrolling once a button is clicked, but I can't figure out how to reactivate the scroll. I think the problem might have something to do with:

```<code>window.removeEventListener('scroll', noscroll);
</code>```

I have tested the if/else statement and that seems to work if I, for example, change the background color of the body.

```<code>var isScrollEnabled = true;

document.querySelector('.mobile-button').addEventListener('click', function(event) {
    event.preventDefault();
    document.querySelector('body').classList.toggle("mobile-menu");

    function noscroll() {
        window.scrollTo(0, 0);
    }

    if (isScrollEnabled = true;) {
        window.addEventListener('scroll', noscroll);
        var isScrollEnabled = false;
    } else {
        window.removeEventListener('scroll', noscroll);
        var isScrollEnabled = true;
    }
});
</code>```

答:
You can use a boolean that will hold the current state of the scroll.

change the boolean when the button is clicked every time. And use it in the if/else you mentioned

Title: Javascript OnClick toggle scroll

Body:
This code disables scrolling once a button is clicked, but I can't figure out how to reactivate the scroll. I think the problem might have something to do with:

window.removeEventListener('scroll', noscroll);

I have tested the if/else statement and that seems to work if I, for example, change the background color of the body.

var isScrollEnabled = true;

document.querySelector('.mobile-button').addEventListener('click', function(event) {
    event.preventDefault();
    document.querySelector('body').classList.toggle("mobile-menu");

    function noscroll() {
        window.scrollTo(0, 0);
    }

    if (isScrollEnabled = true;) {
        window.addEventListener('scroll', noscroll);
        var isScrollEnabled = false;
    } else {
        window.removeEventListener('scroll', noscroll);
        var isScrollEnabled = true;
    }
});


问:
How to select first entry of each ItemType
I have a table

```<code>Items (ItemType varchar(20), Size int)
</code>```

I have to select the first entry of each ItemType. For this I have used the following query

```<code>SELECT *
FROM
    (SELECT
         Size, ItemType,
         ROW_NUMBER() OVER (PARTITION BY ItemType ORDER BY Size) AS RowNum
     FROM
         Items) s
</code>```

But my this is showing output with repeating ItemType. How to solve this?

答:
Just add a WHERE condition to restrict to the first row for each partition:

```<code>SELECT *
FROM
(
    SELECT Size, ItemType,
           ROW_NUMBER() OVER (PARTITION BY ItemType ORDER BY Size) AS RowNum
    FROM Items
) s
WHERE s.RowNum = 1
</code>```

Body:
I have a table

Items (ItemType varchar(20), Size int)

I have to select the first entry of each ItemType. For this I have used the following query

SELECT *
FROM
    (SELECT
         Size, ItemType,
         ROW_NUMBER() OVER (PARTITION BY ItemType ORDER BY Size) AS RowNum
     FROM
         Items) s

But my this is showing output with repeating ItemType. How to solve this?

Body:
Just add a WHERE condition to restrict to the first row for each partition:

SELECT *
FROM
(
    SELECT Size, ItemType,
           ROW_NUMBER() OVER (PARTITION BY ItemType ORDER BY Size) AS RowNum
    FROM Items
) s
WHERE s.RowNum = 1


问:
How do I use a for-each loop to remove all .php files into 0777 folders
The following command attempts to delete all .php files in  /  if folder permission 0777

```<code>find / -type f -perm 0777 -exec rm -rf *.php  \; -exec rm -rf *.html \;
</code>```

with

```<code>find / -type d -perm 0777 -print0 | xargs -0 rm -rf *.php
</code>```

it's delete folder not php files

am looking to run it with terminal ssh command

i search for all folders have 0777 and remove all php files into it

答:
you may easily use RecursiveDirectoyIterator to do this as follows :

```<code>$directory = 'test/';

$iterator = new RecursiveDirectoryIterator($directory);
$directoryIterator = new RecursiveIteratorIterator($iterator);

foreach ($directoryIterator as $file) {
    $octalPermission = substr(decoct($file->getPerms()), -4);
    $extension = $file->getExtension();
    if (!$file->isDir() && $octalPermission == '0777' && $extension == 'php') {
        // do some stuff
        unlink($file->getPathname());
    }
}
</code>```

this will recursively iterate over your php file within a specific directory with a specific permission and delete it .

to use it for only current directory -not recursively- change this :

```<code>$iterator = new RecursiveDirectoryIterator($directory);
$directoryIterator = new RecursiveIteratorIterator($iterator);
</code>```

by the following class :

```<code>$directoryIterator = new DirectoryIterator($directory);
</code>```

Update

However , as long as the OP asks to do this using terminal not php,

you may use the following command :

```<code>find ./test/ -type f -name "*.php" -perm 0777 | xargs rm
</code>```

Update 2 :

to checkout first for directories with permission 777 , as follows :

```<code>find ./test/ -type d -perm 0777 | xargs -I {} find {} -type f -name "*.php" -perm 0777 | xargs rm
</code>```

Update 3 :

to make this command applies in files with spaces/special characters , you may use the -d -delimiter option to set it to \n as follows :

```<code>find ./test/ -type d -perm 0777 \
| xargs -I {} find {} -type f -name "*.php" -perm 0777 \
| xargs -d '\n' rm
//      ^^^^^^^ notice this
</code>```

this will find file name with php extension and permission 0777 then delete them.

Update 4 (31 Mar 2017)

for any of the previous commands , when you try to use xargs command with rm command , if there is no files exists in your search criteria , terminal may prompt an error like following :

```<code>rm: missing operand
</code>```

to avoid this , you will need to add the -r option to xargs :

```<code>-r, --no-run-if-empty        if there are no arguments, then do not run COMMAND;
</code>```

you may use it as follows :

```<code>xargs -r -d '\n' rm
</code>```

Body:
The following command attempts to delete all .php files in  /  if folder permission 0777

find / -type f -perm 0777 -exec rm -rf *.php  \; -exec rm -rf *.html \;

with

find / -type d -perm 0777 -print0 | xargs -0 rm -rf *.php

it's delete folder not php files

am looking to run it with terminal ssh command

i search for all folders have 0777 and remove all php files into it

Body:
you may easily use RecursiveDirectoyIterator to do this as follows :

$directory = 'test/';

$iterator = new RecursiveDirectoryIterator($directory);
$directoryIterator = new RecursiveIteratorIterator($iterator);

foreach ($directoryIterator as $file) {
    $octalPermission = substr(decoct($file->getPerms()), -4);
    $extension = $file->getExtension();
    if (!$file->isDir() && $octalPermission == '0777' && $extension == 'php') {
        // do some stuff
        unlink($file->getPathname());
    }
}

this will recursively iterate over your php file within a specific directory with a specific permission and delete it .

to use it for only current directory -not recursively- change this :

$iterator = new RecursiveDirectoryIterator($directory);
$directoryIterator = new RecursiveIteratorIterator($iterator);

by the following class :

$directoryIterator = new DirectoryIterator($directory);

Update

However , as long as the OP asks to do this using terminal not php,

you may use the following command :

find ./test/ -type f -name "*.php" -perm 0777 | xargs rm

Update 2 :

to checkout first for directories with permission 777 , as follows :

find ./test/ -type d -perm 0777 | xargs -I {} find {} -type f -name "*.php" -perm 0777 | xargs rm

Update 3 :

to make this command applies in files with spaces/special characters , you may use the -d -delimiter option to set it to \n as follows :

find ./test/ -type d -perm 0777 \
| xargs -I {} find {} -type f -name "*.php" -perm 0777 \
| xargs -d '\n' rm
//      ^^^^^^^ notice this

this will find file name with php extension and permission 0777 then delete them.

Update 4 (31 Mar 2017)

for any of the previous commands , when you try to use xargs command with rm command , if there is no files exists in your search criteria , terminal may prompt an error like following :

rm: missing operand

to avoid this , you will need to add the -r option to xargs :

-r, --no-run-if-empty        if there are no arguments, then do not run COMMAND;

you may use it as follows :

xargs -r -d '\n' rm


问:
How to use editor.action.joinLines in visual studio code?
As the title says, in visual studio code you can use the editor.action.joinLines to join different lines of text to one single line? Being an editor noob, the question is how? How do I map this command to a key board short cut, or what mouse actions do I need to do after selecting the said text, to get two different lines as one single line? Specifically I am working on Mac OS X.

答:
To join several lines you have to select them first (you can read more about various ways of selecting text in the vs code documentation) and then invoke the Join Lines command. As a result, all text from the second and next lines will be appended to the end of first lines.

You can invoke the Join Lines command either from the Command Palette by pressing F1 or ⇧+⌘+P on macOS and typing Join Lines or by pressing the assigned shortcut - ⌃+J


问:
Is Touch ID "Try Again" alert view's title customizable?
I've seen that the first time the Touch ID dialog is displayed, the name of the app is shown by default, and that the subtitle can be set as localizedReason. What about setting a completely custom String as title? Is it possible to change the "Try Again" title that is shown when you fail a Touch ID attempt?

答: No you cannot. These OS dialogs are very limited in what you can customize.</p>


问:
Matlab pdist2 : Out of memory
I have a vector X which contain x and y value in column 1 and 2 respectively.
I make a calcul between each point :

```<code>Distance = pdist2(X,X);
</code>```

But sometimes I have a problem of memory.

However, I use this matrix in a loop like this :

```<code>for i:1:n
    find(Distance(i,:) <= epsilon);
    .....
end
</code>```

So, do you know how to make the calcul inside the loop of just the line i of the matrix Distance ?

Thanks

答:
This is what I looked for :</p>

```<code>pdist2(X(i,:),X)
</code>```

Title: Matlab pdist2 : Out of memory

Body:
I have a vector X which contain x and y value in column 1 and 2 respectively.
I make a calcul between each point :

Distance = pdist2(X,X);

But sometimes I have a problem of memory.

However, I use this matrix in a loop like this :

for i:1:n
    find(Distance(i,:) <= epsilon);
    .....
end

So, do you know how to make the calcul inside the loop of just the line i of the matrix Distance ?

Thanks

Body:
This is what I looked for :

pdist2(X(i,:),X)


问:
How to implement a generic linked list map function in Rust?
I am cutting my teeth with Rust and I'm trying to implement a generically-typed linked list. So far my cons and len functions work but there is something wrong with map that I cannot figure out.

```<code>use std::fmt;

#[derive(Debug)]
enum List<A> {
    Empty,
    Cons(A, Box<List<A>>),
}

fn cons<A>(x: A, xs: List<A>) -> List<A> {
    return List::Cons(x, Box::new(xs));
}

fn len<A>(xs: List<A>) -> i32 {
    match xs {
        List::Empty => 0,
        List::Cons(_, xs) => 1 + len(*xs),
    }
}

fn map<A, B>(f: &Fn(A) -> B, xs: List<A>) -> List<B> {
    match xs {
        List::Empty => List::Empty,
        List::Cons(x, xs) => cons(f(x), map(f, *xs)),
    }
}

fn main() {
    let xs = cons(1, cons(2, cons(3, List::Empty)));
    println!("{:?}", xs);
    println!("{:?}", len(xs));
    let f = |x: i32| x * x;
    println!("{:?})", map(f, xs));
}
</code>```

Error

error[E0308]: mismatched types
  --> src/main.rs:32:27
   |
32 |     println!("{:?})", map(f, xs));
   |                           ^ expected reference, found closure
   |
   = note: expected type `&std::ops::Fn(_) -> _`
              found type `[closure@src/main.rs:31:13: 31:27]`
```

<p><strong>Expected Output</strong></p>

<pre class="lang-none prettyprint-override"><code>Cons(1, Cons(2, Cons(3, Empty)))
3
Cons(1, Cons(4, Cons(9, Empty)))
</code>```

My particular problem is with

```<code>println!("{:?})", map(f, xs));
</code>```

If I comment that line out, the first two lines of output are correct. I'm not sure what's wrong with my map call

Update

aochagavia helped me understand the function reference issue and the first ownership issue (of many, apparently!) - I'm having trouble using the same technique we used in len in map and getting a new error

My updated map function looks like this

```<code>fn map<A, B>(f: &Fn(A) -> B, xs: &List<A>) -> List<B> {
    match *xs {
        List::Empty => List::Empty,
        List::Cons(x, ref xs) => cons(f(x), map(f, xs)),
    }
}
</code>```

I'm now trying this

```<code>let f = |x: i32| x * x;
let ys = map(&f, &xs);
let zs = map(&f, &xs);
println!("{:?})", ys);
println!("{:?})", zs);
</code>```

The new error is this

error[E0009]: cannot bind by-move and by-ref in the same pattern
  --> src/main.rs:23:20
   |
23 |         List::Cons(x, ref xs) => cons(f(x), map(f, xs)),
   |                    ^  ------ both by-ref and by-move used
   |                    |
   |                    by-move pattern here
```

答:
The error message is big because it happens within a macro, but if you add this: let y = map(f, xs); you get a shorter (and slightly more accurate) one:

error[E0308]: mismatched types
  --> <anon>:32:15
   |
32 |   let y = map(f, xs);
   |               ^ expected reference, found closure
   |
   = note: expected type `&std::ops::Fn(_) -> _`
              found type `[closure@<anon>:31:11: 31:25]`
```

<p>That is, you are passing the closure by value instead of by reference! Using <code>map(&f, xs)</code> (note the ampersand) should solve the error. However, there is another issue with ownership (see below).</p>

<h2>The ownership issue</h2>

<p>The type signature of the <code>len</code> function is <code>fn len<A> (xs: List<A>) -> i32</code>. That means that it will take ownership of the list in order to calculate its length. This is however not what you want, since it would prevent you from using the list afterwards! Hence the error you get from the compiler.</p>

<p>The sensible way to solve this is to let <code>len</code> borrow <code>xs</code> instead of consuming it. Like this:</p>

```fn len(xs: &List) -> i32 {
    match *xs {
        List::Empty => 0,
        List::Cons(_, ref xs) => 1 + len(xs),
    }
}
```

<p>Finally, you will need to modify your <code>main</code> function to reflect this change by calling <code>len</code> like this: <code>len(&xs)</code> (note the ampersand, which you can think of as the borrow operator).</p>

<h2>Making map borrow xs as well</h2>

<p>As naomik pointed out in the comments, <code>map</code> seems to be a candidate as well for borrowing <code>xs</code> instead of consuming it. A possible implementation would be:</p>

```fn map(f: &Fn(&A) -> B, xs: &List) -> List {
    match *xs {
        List::Empty => List::Empty,
        List::Cons(ref x, ref xs) => cons(f(x), map(f, xs)),
    }
}
```

<p>The main difference with the original version is that the closure now takes an <code>&A</code> instead of an <code>A</code> (see <code>Fn(&A) -> B</code>). This is natural, since it is impossible to consume a value that is contained in a borrow (it would mean the borrow mechanism is utterly broken).</p>

<p>In main you would need to call <code>map</code> like this:</p>

```let f = |x: &i32| (*x) * (*x);
map(&f, &xs);
```

<p>Note that <code>f</code> now borrows its parameter instead of consuming it, as is required by the type signature of <code>map</code>.</p>

<h2>Some extra background in closures</h2>

<p>Closures are a bit special in Rust. You can construct them with a nice syntax, but in the end they are just structs that happen to implement the <code>Fn</code>, <code>FnMut</code> or <code>FnOnce</code> traits.</p>

<p>In case you want to pass them by value (and not by reference, as you do in your code), you can make the map function generic by using the following type signature:</p>

```fn map<F, A, B> (f: F, xs: List) -> List
    where F: Fn(A) -> B
{
```

This also gives you static dispatch. If you want to know more about that you should probably read on trait objects and static/dynamic dispatch.

Body:
I am cutting my teeth with Rust and I'm trying to implement a generically-typed linked list. So far my cons and len functions work but there is something wrong with map that I cannot figure out.

use std::fmt;

#[derive(Debug)]
enum List {
    Empty,
    Cons(A, Box<List>),
}

fn cons(x: A, xs: List) -> List {
    return List::Cons(x, Box::new(xs));
}

fn len(xs: List) -> i32 {
    match xs {
        List::Empty => 0,
        List::Cons(_, xs) => 1 + len(*xs),
    }
}

fn map(f: &Fn(A) -> B, xs: List) -> List {
    match xs {
        List::Empty => List::Empty,
        List::Cons(x, xs) => cons(f(x), map(f, *xs)),
    }
}

fn main() {
    let xs = cons(1, cons(2, cons(3, List::Empty)));
    println!("{:?}", xs);
    println!("{:?}", len(xs));
    let f = |x: i32| x * x;
    println!("{:?})", map(f, xs));
}

Error

error[E0308]: mismatched types
  --> src/main.rs:32:27
   |
32 |     println!("{:?})", map(f, xs));
   |                           ^ expected reference, found closure
   |
   = note: expected type `&std::ops::Fn(_) -> _`
              found type `[closure@src/main.rs:31:13: 31:27]`

Expected Output

Cons(1, Cons(2, Cons(3, Empty)))
3
Cons(1, Cons(4, Cons(9, Empty)))

My particular problem is with

println!("{:?})", map(f, xs));

If I comment that line out, the first two lines of output are correct. I'm not sure what's wrong with my map call

Update

aochagavia helped me understand the function reference issue and the first ownership issue (of many, apparently!) - I'm having trouble using the same technique we used in len in map and getting a new error

My updated map function looks like this

fn map(f: &Fn(A) -> B, xs: &List) -> List {
    match *xs {
        List::Empty => List::Empty,
        List::Cons(x, ref xs) => cons(f(x), map(f, xs)),
    }
}

I'm now trying this

let f = |x: i32| x * x;
let ys = map(&f, &xs);
let zs = map(&f, &xs);
println!("{:?})", ys);
println!("{:?})", zs);

The new error is this

error[E0009]: cannot bind by-move and by-ref in the same pattern
  --> src/main.rs:23:20
   |
23 |         List::Cons(x, ref xs) => cons(f(x), map(f, xs)),
   |                    ^  ------ both by-ref and by-move used
   |                    |
   |                    by-move pattern here

Body:
The error message is big because it happens within a macro, but if you add this: let y = map(f, xs); you get a shorter (and slightly more accurate) one:

error[E0308]: mismatched types
  --> <anon>:32:15
   |
32 |   let y = map(f, xs);
   |               ^ expected reference, found closure
   |
   = note: expected type `&std::ops::Fn(_) -> _`
              found type `[closure@<anon>:31:11: 31:25]`

That is, you are passing the closure by value instead of by reference! Using map(&f, xs) (note the ampersand) should solve the error. However, there is another issue with ownership (see below).

The ownership issue

The type signature of the len function is fn len<A> (xs: List<A>) -> i32. That means that it will take ownership of the list in order to calculate its length. This is however not what you want, since it would prevent you from using the list afterwards! Hence the error you get from the compiler.

The sensible way to solve this is to let len borrow xs instead of consuming it. Like this:

fn len<A>(xs: &List<A>) -> i32 {
    match *xs {
        List::Empty => 0,
        List::Cons(_, ref xs) => 1 + len(xs),
    }
}

Finally, you will need to modify your main function to reflect this change by calling len like this: len(&xs) (note the ampersand, which you can think of as the borrow operator).

Making map borrow xs as well

As naomik pointed out in the comments, map seems to be a candidate as well for borrowing xs instead of consuming it. A possible implementation would be:

fn map<A, B>(f: &Fn(&A) -> B, xs: &List<A>) -> List<B> {
    match *xs {
        List::Empty => List::Empty,
        List::Cons(ref x, ref xs) => cons(f(x), map(f, xs)),
    }
}

The main difference with the original version is that the closure now takes an &A instead of an A (see Fn(&A) -> B). This is natural, since it is impossible to consume a value that is contained in a borrow (it would mean the borrow mechanism is utterly broken).

In main you would need to call map like this:

let f = |x: &i32| (*x) * (*x);
map(&f, &xs);

Note that f now borrows its parameter instead of consuming it, as is required by the type signature of map.

Some extra background in closures

Closures are a bit special in Rust. You can construct them with a nice syntax, but in the end they are just structs that happen to implement the Fn, FnMut or FnOnce traits.

In case you want to pass them by value (and not by reference, as you do in your code), you can make the map function generic by using the following type signature:

fn map<F, A, B> (f: F, xs: List<A>) -> List<B>
    where F: Fn(A) -> B
{

This also gives you static dispatch. If you want to know more about that you should probably read on trait objects and static/dynamic dispatch.


问:
Sequelize: Custom Method with Where statement
I have two Models, a User Model and a Event Model. A user can have many Events.

I am still learning Sequelize and I'm wondering if it's possible to create like a custom method that easily get's me the upcoming Events (column date), so that I can do something like

User.getUpcomingEvents().then(() => {})

I'm coming from Laravel and Eloquent, and that was pretty easy to achieve over there but I'm struggeling to do it in Sequelize and the documentation is still a bit confusing for me.

Appreciate your tips :)

答:
If you want to return events independent on the userId value, then you can use classMethods property when defining Model so that later you can call Model.<methodName>. In this case it would be User.getUpcomingEvents()

```<code>let User = sequelize.define('User', {
    // attributes...
}, {
    classMethods: {
        getUpcomingEvents: function(userId){
            return sequelize.models.Event.findAll({
                where: {
                    date: { $gt: new Date() },
                    UserId: userId // optional, if you want to return only events of given user
                }
            }).then(events => {
                return events;
            });
        }
    }
});
</code>```

Otherwise, if you want to return upcoming events of given user, you can also use classMethod that would get userId as parameter, or, you can use instance method so that you can use it like userInstance.<methodName> like user.getUpcomingEvents()

```<code>instanceMethods: {
    getUpcomingEvents: function() {
        return this.getEvents({ where: { date: { $gt: new Date() } } }).then(events => {
            return events;
        });
    }
}
</code>```

Please read the documentation concerning instance and class methods.

Body:
If you want to return events independent on the userId value, then you can use classMethods property when defining Model so that later you can call Model.<methodName>. In this case it would be User.getUpcomingEvents()

let User = sequelize.define('User', {
    // attributes...
}, {
    classMethods: {
        getUpcomingEvents: function(userId){
            return sequelize.models.Event.findAll({
                where: {
                    date: { $gt: new Date() },
                    UserId: userId // optional, if you want to return only events of given user
                }
            }).then(events => {
                return events;
            });
        }
    }
});

Otherwise, if you want to return upcoming events of given user, you can also use classMethod that would get userId as parameter, or, you can use instance method so that you can use it like userInstance.<methodName> like user.getUpcomingEvents()

instanceMethods: {
    getUpcomingEvents: function() {
        return this.getEvents({ where: { date: { $gt: new Date() } } }).then(events => {
            return events;
        });
    }
}

Please read the documentation concerning instance and class methods.


问:
Jackson automatic formatting of Joda DateTime to ISO 8601 format
According to http://wiki.fasterxml.com/JacksonFAQDateHandling, “DateTime can be automatically serialized/deserialized similar to how java.util.Date is handled.” However, I am not able to accomplish this automatic functionality.  There are StackOverflow discussions related to this topic yet most involve a code-based solution, but based upon the quote above I should be able to accomplish this via simple configuration.

Per http://wiki.fasterxml.com/JacksonFAQDateHandling I have my configuration set so that writing dates as timestamps is false.  The result is that java.util.Date types are serialized to ISO 8601 format, but org.joda.time.DateTime types are serialized to a long object representation.

My environment is this:

Jackson 2.1

Joda time 2.1

Spring 3.2

Java 1.6

My Spring configuration for the jsonMapper bean is

```<code>@Bean
public ObjectMapper jsonMapper() {
    ObjectMapper objectMapper = new ObjectMapper();

    //Fully qualified path shows I am using latest enum
    ObjectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.
        WRITE_DATES_AS_TIMESTAMPS , false);

    return objectMapper;
}
</code>```

My test code snippet is this

```<code>Date d = new Date();
DateTime dt = new DateTime(d); //Joda time
Map<String, Object> link = new LinkedHashMap<String, Object>();
link.put("date", d);
link.put("createdDateTime", dt);
</code>```

The resulting snippet of JSON output is this:

```<code>{"date":"2012-12-24T21:20:47.668+0000"}

{"createdDateTime": {"year":2012,"dayOfMonth":24,"dayOfWeek":1,"era":1,"dayOfYear":359,"centuryOfEra":20,"yearOfEra":2012,"yearOfCentury":12,"weekyear":2012,"monthOfYear":12 *... remainder snipped for brevity*}}
</code>```

My expectation is that the DateTime object should matche that of the Date object based upon the configuration.  What am I doing wrong, or what am I misunderstanding?  Am I reading too much into the word automatically from the Jackson documentation and the fact that a string representation was produced, albeit not ISO 8601, is producing the advertised automatic functionality?

答:
In Spring Boot the configuration is even simpler. You just declare Maven dependency

```<code>    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-joda</artifactId>
    </dependency>
</code>```

and then add configuration parameter to your application.yml/properties file:

```<code>spring.jackson.serialization.write-dates-as-timestamps: false
</code>```

Body:
According to http://wiki.fasterxml.com/JacksonFAQDateHandling, “DateTime can be automatically serialized/deserialized similar to how java.util.Date is handled.” However, I am not able to accomplish this automatic functionality.  There are StackOverflow discussions related to this topic yet most involve a code-based solution, but based upon the quote above I should be able to accomplish this via simple configuration.

Per http://wiki.fasterxml.com/JacksonFAQDateHandling I have my configuration set so that writing dates as timestamps is false.  The result is that java.util.Date types are serialized to ISO 8601 format, but org.joda.time.DateTime types are serialized to a long object representation.

My environment is this:

Jackson 2.1

Joda time 2.1

Spring 3.2

Java 1.6

My Spring configuration for the jsonMapper bean is

@Bean
public ObjectMapper jsonMapper() {
    ObjectMapper objectMapper = new ObjectMapper();

    //Fully qualified path shows I am using latest enum
    ObjectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.
        WRITE_DATES_AS_TIMESTAMPS , false);

    return objectMapper;
}

My test code snippet is this

Date d = new Date();
DateTime dt = new DateTime(d); //Joda time
Map<String, Object> link = new LinkedHashMap<String, Object>();
link.put("date", d);
link.put("createdDateTime", dt);

The resulting snippet of JSON output is this:

{"date":"2012-12-24T21:20:47.668+0000"}

{"createdDateTime": {"year":2012,"dayOfMonth":24,"dayOfWeek":1,"era":1,"dayOfYear":359,"centuryOfEra":20,"yearOfEra":2012,"yearOfCentury":12,"weekyear":2012,"monthOfYear":12 *... remainder snipped for brevity*}}

My expectation is that the DateTime object should matche that of the Date object based upon the configuration.  What am I doing wrong, or what am I misunderstanding?  Am I reading too much into the word automatically from the Jackson documentation and the fact that a string representation was produced, albeit not ISO 8601, is producing the advertised automatic functionality?

Body:
In Spring Boot the configuration is even simpler. You just declare Maven dependency

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-joda</artifactId>
    </dependency>

and then add configuration parameter to your application.yml/properties file:

spring.jackson.serialization.write-dates-as-timestamps: false