问:
Notification makes sound but does not display anything
For my app I am looking to implement a local notification system.

My code to schedule a notification is as follows:

```<code>func scheduleNotification(_ Name:String, _ Time:DateComponents){
        let center = UNUserNotificationCenter.current()
        let notification = UNMutableNotificationContent()
        notification.title = Name
        notification.sound = UNNotificationSound.default()

        var trigger = UNCalendarNotificationTrigger(dateMatching: Time, repeats: false)

        let identifier = Name

        let request = UNNotificationRequest(identifier: identifier, content: notification, trigger: trigger)
        center.add(request)

    }
</code>```

Now that worked yesterday, but not it no longer does. In both simulator and device.

I've tried the suggestion here to no avail: Local Notifications make sound but do not display (Swift)

What I have tried:

Testing with the app force closed

Testing with the app in the background

Changing identifiers

答:
I think you need to set body of notification. add this line too below notification.title = Name line

```<code>notification.body = "Hello Notification"
</code>```

For more check Apple doc.

Body:
For my app I am looking to implement a local notification system.

My code to schedule a notification is as follows:

func scheduleNotification(_ Name:String, _ Time:DateComponents){
        let center = UNUserNotificationCenter.current()
        let notification = UNMutableNotificationContent()
        notification.title = Name
        notification.sound = UNNotificationSound.default()

        var trigger = UNCalendarNotificationTrigger(dateMatching: Time, repeats: false)

        let identifier = Name

        let request = UNNotificationRequest(identifier: identifier, content: notification, trigger: trigger)
        center.add(request)

    }

Now that worked yesterday, but not it no longer does. In both simulator and device.

I've tried the suggestion here to no avail: Local Notifications make sound but do not display (Swift)

What I have tried:

Testing with the app force closed

Testing with the app in the background

Changing identifiers

Body:
I think you need to set body of notification. add this line too below notification.title = Name line

notification.body = "Hello Notification"

For more check Apple doc.


来源: stackexchange

问:
Python - convert rows to columns after group by and populate zeroes for non matching rows
I have a requirement where I need to convert the rows of a dataframe column to columns, however I am facing an issue after GROUPBY.
Below is a set of 3 users that can have types between type1 to type6.

```<code>user_id1    type4
user_id1    type6
user_id1    type1
user_id1    type2
user_id1    type1
user_id1    type6
user_id2    type1
user_id2    type2
user_id2    type2
user_id2    type1
user_id2    type3
user_id2    type4
user_id2    type5
user_id2    type6
user_id2    type2
user_id2    type6
user_id3    type1
user_id3    type2
user_id3    type3
user_id3    type2
</code>```

The output I am expecting is -

```<code>user_id   type1 type2   type3   type4   type5   type6
user_id1    2    1       0       1       0       2
user_id2    2    3       1       1       1       2
user_id3    1    2       1       0       0       0
</code>```

I tried to do a groupby on the type and got the count.But not sure how to convert to column especially the missing types should be populated with 0.

Thanks a lot for your time.

答:
What you need to use is pivot_table from pandas. You can specify what rows and columns you need, fill_value states what do you want to do with empty values and aggfunc len counts.

I'm not sure what your DataSeries looks like, but you need sth like this:

```<code>pd.pivot_table(data, index='user_id', columns='type', aggfunc=len, fill_value=0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a requirement where I need to convert the rows of a dataframe column to columns, however I am facing an issue after GROUPBY.
Below is a set of 3 users that can have types between type1 to type6.

user_id1    type4
user_id1    type6
user_id1    type1
user_id1    type2
user_id1    type1
user_id1    type6
user_id2    type1
user_id2    type2
user_id2    type2
user_id2    type1
user_id2    type3
user_id2    type4
user_id2    type5
user_id2    type6
user_id2    type2
user_id2    type6
user_id3    type1
user_id3    type2
user_id3    type3
user_id3    type2

The output I am expecting is -

user_id   type1 type2   type3   type4   type5   type6
user_id1    2    1       0       1       0       2
user_id2    2    3       1       1       1       2
user_id3    1    2       1       0       0       0

I tried to do a groupby on the type and got the count.But not sure how to convert to column especially the missing types should be populated with 0.

Thanks a lot for your time.

Body:
What you need to use is pivot_table from pandas. You can specify what rows and columns you need, fill_value states what do you want to do with empty values and aggfunc len counts.

I'm not sure what your DataSeries looks like, but you need sth like this:

pd.pivot_table(data, index='user_id', columns='type', aggfunc=len, fill_value=0)


问:
Can't excute a function when i click on li element
I have an HTML list like this:

```<code><ul id='years'>
<li class='year'>2014</li>
<li class='year'>2015</li>
<li class='year'>2015</li>
</ul>
</code>```

when I click on "2014" for example, I need to hide other list and show only the clicked one then pass this year to php file, catch this year and connect to a database baking with other data related to this year then list this new data at the end of list, and I tried this:

jQuery part:

```<code><script>
$('.year').click(function(){
var path=$(this).text();
$(".year").toggle(200);
$(this).toggle(200);
$.post("test.php",{p:path},function(data){
$(".years").append(data);
});

// last part of script
$(".col_1").click(function(){
//whatever
});

</script>
</code>```

test.php:

```<code>if(isset($_POST['p']){
$year=$_POST['p'];
$db_connection=new mysqli(localhost,USER,PASS) ;
$query="select*from user.info where year=$year" ;
$db_connection->query($query);
$rows=$db_connection->num_rows;
for($i=0;$i<$rows;$i++){`
$result->data_seek($rowP);
$result->fetch_assoc()["col_1"];
$returned_data.="<li class='col_1'>$result</li>";
}
echo "$returned_data";
}
</code>```

All of this work well and the data show up in the web page but the last part of script doesn't work and nothing happen when i click on any element of this list. Is the reason because the
 coded by php or what?.. Thanks for help.

答:
just move $(".col_1").click(function(){ inside Success function in ajax

$('.year').click(function(){
  debugger;
  var path=$(this).text();
  $(".year").toggle(200);
  $(this).toggle(200);
  $.post("test.php",{p:path},function(data){
    $(".years").append(data);
    $(".col_1").click(function(){
    //alert();
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='years'>
<li class='year'>2014</li>
<li class='year'>2015</li>
<li class='year'>2015</li>
</ul></code>```

Body:
I have an HTML list like this:

2014

2015

2015

when I click on "2014" for example, I need to hide other list and show only the clicked one then pass this year to php file, catch this year and connect to a database baking with other data related to this year then list this new data at the end of list, and I tried this:

jQuery part:

test.php:

if(isset($_POST['p']){
$year=$_POST['p'];
$db_connection=new mysqli(localhost,USER,PASS) ;
$query="select*from user.info where year=$year" ;
$db_connection->query($query);
$rows=$db_connection->num_rows;
for($i=0;$i<$rows;$i++){`
$result->data_seek($rowP);
$result->fetch_assoc()["col_1"];
$returned_data.="
$result
";
}
echo "$returned_data";
}

All of this work well and the data show up in the web page but the last part of script doesn't work and nothing happen when i click on any element of this list. Is the reason because the
 coded by php or what?.. Thanks for help.

Body:
just move $(".col_1").click(function(){ inside Success function in ajax

$('.year').click(function(){
  debugger;
  var path=$(this).text();
  $(".year").toggle(200);
  $(this).toggle(200);
  $.post("test.php",{p:path},function(data){
    $(".years").append(data);
    $(".col_1").click(function(){
    //alert();
    });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='years'>
<li class='year'>2014</li>
<li class='year'>2015</li>
<li class='year'>2015</li>
</ul>


问:
Conditionally Perform difftime in R
I have a data table with devices that are inspected "annually." When the device has an inspection code "AC" (inspection_disposition_cd="AC"), then I need to count the days passed since the inspection record listed in the row directly above it.

The code I am using does the math just fine, however, I am struggling with coding so that ONLY the rows that have the AC code receive this action. Can anyone provide any advice as to how to single out these rows?

This is the working code:

```<code>DispNotClear2$First<-c(0,with(DispNotClear2,difftime(insp_dt[2:length(insp_dt)],insp_dt[1], unit="days")))
DispNotClear2$BETWEEN<-c(0,with(DispNotClear2,diff(insp_dt[1:(length(insp_dt)-1)],unit="days")))}
</code>```

Also, here are 30 rows of sample data from my data table:

```<code>library(data.table)
SampleData <- setDT(structure(list(record_num = c(12354L, 6764L, 9959L, 94L, 16463L,
6859L, 80678L, 87555L, 77980L, 2839L, 4785L, 6082L, 28271L, 54L,
23000L, 2565L, 3507L, 25607L, 106L, 14621L, 33525L, 6335L, 24970L,
4851L, 77057L, 17247L, 14488L, 2754L, 88945L, 2710L), device_num = c("2P4564",
"1P27589", "1P9215", "1P32077", "3P2093", "1P29651", "3P13054",
"1P14559", "3P7242", "1P30282", "1P12286", "1P13149", "3P10127",
"1P18885", "4P5121", "1P14621", "1P6278", "1P35255", "1P28871",
"3P2643", "3P12113", "1P31196", "4P2597", "1W5192", "2P5643",
"3P6750", "3F1928", "1P11978", "1P33505", "1P14572"), year = c(2016,
2011, 2016, 2010, 2011, 2013, 2014, 2015, 2013, 2012, 2015, 2016,
2013, 2015, 2010, 2011, 2011, 2015, 2013, 2012, 2016, 2011, 2015,
2016, 2012, 2016, 2011, 2015, 2010, 2014), inspection_type_cd = c("CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)"), inspection_disposition_cd = c("AC", "AC",
"AC", "AU", "AC", "AC", "AU", "AC", "AC", "AC", "AC", "AU", "AU",
"AU", "AU", "AU", "RD", "AU", "AU", "AC", "AU", "AC", "AU", "AU",
"AC", "AU", "AU", "AC", "AU", "AC"), remarks = c("2015 AFFIRMATION OF CORRECTION",
NA, "2016 AOC", NA, "PENALTY PAID", "2012 AOC", NA, "2015 AFFIRMATION OF CORRECTION",
"2013 AFFIRMATION OF CORRECTION", "2011 CORRECTION", "2015 AFFIRMATION OF CORRECTION",
NA, NA, "2015 CAT1", NA, NA, "AFFIRMATION OF CORRECTION FILED 68 DAYS LATE",
NA, NA, "2012 CORRECTION", "2016 CAT1", "2010 AFFIRMATION OF CORRECTION",
NA, NA, "2012 CORRECTION", "2016 CAT1", NA, "2015 AFFIRMATION OF CORRECTION",
NA, "2013 AOC"), insp_dt = structure(c(16911, 15271, 17060, 14784,
15014, 16009, 16339, 16658, 16044, 15363, 16576, 17151, 16069,
16444, 14714, 15184, 15237, 16631, 16059, 15415, 16979, 14995,
16748, 17137, 15644, 16973, 15211, 16636, 14957, 16087), class = "Date"),
    days_late = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, 68, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA)), .Names = c("record_num", "device_num",
"year", "inspection_type_cd", "inspection_disposition_cd", "remarks",
"insp_dt", "days_late"), class = "data.frame", row.names = c(NA, -30L)))
</code>```

which looks like

```<code>    record_num device_num year inspection_type_cd inspection_disposition_cd                                      remarks    insp_dt days_late
 1:      12354     2P4564 2016   CATEGORY 1 (1YR)                        AC               2015 AFFIRMATION OF CORRECTION 2016-04-20        NA
 2:       6764    1P27589 2011   CATEGORY 1 (1YR)                        AC                                           NA 2011-10-24        NA
 3:       9959     1P9215 2016   CATEGORY 1 (1YR)                        AC                                     2016 AOC 2016-09-16        NA
 4:         94    1P32077 2010   CATEGORY 1 (1YR)                        AU                                           NA 2010-06-24        NA
 5:      16463     3P2093 2011   CATEGORY 1 (1YR)                        AC                                 PENALTY PAID 2011-02-09        NA
 6:       6859    1P29651 2013   CATEGORY 1 (1YR)                        AC                                     2012 AOC 2013-10-31        NA
 7:      80678    3P13054 2014   CATEGORY 1 (1YR)                        AU                                           NA 2014-09-26        NA
 8:      87555    1P14559 2015   CATEGORY 1 (1YR)                        AC               2015 AFFIRMATION OF CORRECTION 2015-08-11        NA
 9:      77980     3P7242 2013   CATEGORY 1 (1YR)                        AC               2013 AFFIRMATION OF CORRECTION 2013-12-05        NA
10:       2839    1P30282 2012   CATEGORY 1 (1YR)                        AC                              2011 CORRECTION 2012-01-24        NA
11:       4785    1P12286 2015   CATEGORY 1 (1YR)                        AC               2015 AFFIRMATION OF CORRECTION 2015-05-21        NA
12:       6082    1P13149 2016   CATEGORY 1 (1YR)                        AU                                           NA 2016-12-16        NA
13:      28271    3P10127 2013   CATEGORY 1 (1YR)                        AU                                           NA 2013-12-30        NA
14:         54    1P18885 2015   CATEGORY 1 (1YR)                        AU                                    2015 CAT1 2015-01-09        NA
15:      23000     4P5121 2010   CATEGORY 1 (1YR)                        AU                                           NA 2010-04-15        NA
16:       2565    1P14621 2011   CATEGORY 1 (1YR)                        AU                                           NA 2011-07-29        NA
17:       3507     1P6278 2011   CATEGORY 1 (1YR)                        RD AFFIRMATION OF CORRECTION FILED 68 DAYS LATE 2011-09-20        68
18:      25607    1P35255 2015   CATEGORY 1 (1YR)                        AU                                           NA 2015-07-15        NA
19:        106    1P28871 2013   CATEGORY 1 (1YR)                        AU                                           NA 2013-12-20        NA
20:      14621     3P2643 2012   CATEGORY 1 (1YR)                        AC                              2012 CORRECTION 2012-03-16        NA
21:      33525    3P12113 2016   CATEGORY 1 (1YR)                        AU                                    2016 CAT1 2016-06-27        NA
22:       6335    1P31196 2011   CATEGORY 1 (1YR)                        AC               2010 AFFIRMATION OF CORRECTION 2011-01-21        NA
23:      24970     4P2597 2015   CATEGORY 1 (1YR)                        AU                                           NA 2015-11-09        NA
24:       4851     1W5192 2016   CATEGORY 1 (1YR)                        AU                                           NA 2016-12-02        NA
25:      77057     2P5643 2012   CATEGORY 1 (1YR)                        AC                              2012 CORRECTION 2012-10-31        NA
26:      17247     3P6750 2016   CATEGORY 1 (1YR)                        AU                                    2016 CAT1 2016-06-21        NA
27:      14488     3F1928 2011   CATEGORY 1 (1YR)                        AU                                           NA 2011-08-25        NA
28:       2754    1P11978 2015   CATEGORY 1 (1YR)                        AC               2015 AFFIRMATION OF CORRECTION 2015-07-20        NA
29:      88945    1P33505 2010   CATEGORY 1 (1YR)                        AU                                           NA 2010-12-14        NA
30:       2710    1P14572 2014   CATEGORY 1 (1YR)                        AC                                     2013 AOC 2014-01-17        NA
    record_num device_num year inspection_type_cd inspection_disposition_cd                                      remarks    insp_dt days_late
</code>```

答:
If I understood correctly, below code takes difference between above row for the records where    inspection_disposition_cd=="AC"

SampleData[,day_passed:=ifelse(inspection_disposition_cd=="AC",difftime(shift(insp_dt,1),insp_dt,units = "days"),0)]

alternatively

SampleData[inspection_disposition_cd=="AC",day_passed:=difftime(shift(insp_dt,1),insp_dt,units = "days")]

Title: Conditionally Perform difftime in R

Body:
I have a data table with devices that are inspected "annually." When the device has an inspection code "AC" (inspection_disposition_cd="AC"), then I need to count the days passed since the inspection record listed in the row directly above it.

The code I am using does the math just fine, however, I am struggling with coding so that ONLY the rows that have the AC code receive this action. Can anyone provide any advice as to how to single out these rows?

This is the working code:

DispNotClear2$First<-c(0,with(DispNotClear2,difftime(insp_dt[2:length(insp_dt)],insp_dt[1], unit="days")))
DispNotClear2$BETWEEN<-c(0,with(DispNotClear2,diff(insp_dt[1:(length(insp_dt)-1)],unit="days")))}

Also, here are 30 rows of sample data from my data table:

library(data.table)
SampleData <- setDT(structure(list(record_num = c(12354L, 6764L, 9959L, 94L, 16463L,
6859L, 80678L, 87555L, 77980L, 2839L, 4785L, 6082L, 28271L, 54L,
23000L, 2565L, 3507L, 25607L, 106L, 14621L, 33525L, 6335L, 24970L,
4851L, 77057L, 17247L, 14488L, 2754L, 88945L, 2710L), device_num = c("2P4564",
"1P27589", "1P9215", "1P32077", "3P2093", "1P29651", "3P13054",
"1P14559", "3P7242", "1P30282", "1P12286", "1P13149", "3P10127",
"1P18885", "4P5121", "1P14621", "1P6278", "1P35255", "1P28871",
"3P2643", "3P12113", "1P31196", "4P2597", "1W5192", "2P5643",
"3P6750", "3F1928", "1P11978", "1P33505", "1P14572"), year = c(2016,
2011, 2016, 2010, 2011, 2013, 2014, 2015, 2013, 2012, 2015, 2016,
2013, 2015, 2010, 2011, 2011, 2015, 2013, 2012, 2016, 2011, 2015,
2016, 2012, 2016, 2011, 2015, 2010, 2014), inspection_type_cd = c("CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)", "CATEGORY 1 (1YR)",
"CATEGORY 1 (1YR)"), inspection_disposition_cd = c("AC", "AC",
"AC", "AU", "AC", "AC", "AU", "AC", "AC", "AC", "AC", "AU", "AU",
"AU", "AU", "AU", "RD", "AU", "AU", "AC", "AU", "AC", "AU", "AU",
"AC", "AU", "AU", "AC", "AU", "AC"), remarks = c("2015 AFFIRMATION OF CORRECTION",
NA, "2016 AOC", NA, "PENALTY PAID", "2012 AOC", NA, "2015 AFFIRMATION OF CORRECTION",
"2013 AFFIRMATION OF CORRECTION", "2011 CORRECTION", "2015 AFFIRMATION OF CORRECTION",
NA, NA, "2015 CAT1", NA, NA, "AFFIRMATION OF CORRECTION FILED 68 DAYS LATE",
NA, NA, "2012 CORRECTION", "2016 CAT1", "2010 AFFIRMATION OF CORRECTION",
NA, NA, "2012 CORRECTION", "2016 CAT1", NA, "2015 AFFIRMATION OF CORRECTION",
NA, "2013 AOC"), insp_dt = structure(c(16911, 15271, 17060, 14784,
15014, 16009, 16339, 16658, 16044, 15363, 16576, 17151, 16069,
16444, 14714, 15184, 15237, 16631, 16059, 15415, 16979, 14995,
16748, 17137, 15644, 16973, 15211, 16636, 14957, 16087), class = "Date"),
    days_late = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, 68, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA)), .Names = c("record_num", "device_num",
"year", "inspection_type_cd", "inspection_disposition_cd", "remarks",
"insp_dt", "days_late"), class = "data.frame", row.names = c(NA, -30L)))

which looks like

    record_num device_num year inspection_type_cd inspection_disposition_cd                                      remarks    insp_dt days_late
 1:      12354     2P4564 2016   CATEGORY 1 (1YR)                        AC               2015 AFFIRMATION OF CORRECTION 2016-04-20        NA
 2:       6764    1P27589 2011   CATEGORY 1 (1YR)                        AC                                           NA 2011-10-24        NA
 3:       9959     1P9215 2016   CATEGORY 1 (1YR)                        AC                                     2016 AOC 2016-09-16        NA
 4:         94    1P32077 2010   CATEGORY 1 (1YR)                        AU                                           NA 2010-06-24        NA
 5:      16463     3P2093 2011   CATEGORY 1 (1YR)                        AC                                 PENALTY PAID 2011-02-09        NA
 6:       6859    1P29651 2013   CATEGORY 1 (1YR)                        AC                                     2012 AOC 2013-10-31        NA
 7:      80678    3P13054 2014   CATEGORY 1 (1YR)                        AU                                           NA 2014-09-26        NA
 8:      87555    1P14559 2015   CATEGORY 1 (1YR)                        AC               2015 AFFIRMATION OF CORRECTION 2015-08-11        NA
 9:      77980     3P7242 2013   CATEGORY 1 (1YR)                        AC               2013 AFFIRMATION OF CORRECTION 2013-12-05        NA
10:       2839    1P30282 2012   CATEGORY 1 (1YR)                        AC                              2011 CORRECTION 2012-01-24        NA
11:       4785    1P12286 2015   CATEGORY 1 (1YR)                        AC               2015 AFFIRMATION OF CORRECTION 2015-05-21        NA
12:       6082    1P13149 2016   CATEGORY 1 (1YR)                        AU                                           NA 2016-12-16        NA
13:      28271    3P10127 2013   CATEGORY 1 (1YR)                        AU                                           NA 2013-12-30        NA
14:         54    1P18885 2015   CATEGORY 1 (1YR)                        AU                                    2015 CAT1 2015-01-09        NA
15:      23000     4P5121 2010   CATEGORY 1 (1YR)                        AU                                           NA 2010-04-15        NA
16:       2565    1P14621 2011   CATEGORY 1 (1YR)                        AU                                           NA 2011-07-29        NA
17:       3507     1P6278 2011   CATEGORY 1 (1YR)                        RD AFFIRMATION OF CORRECTION FILED 68 DAYS LATE 2011-09-20        68
18:      25607    1P35255 2015   CATEGORY 1 (1YR)                        AU                                           NA 2015-07-15        NA
19:        106    1P28871 2013   CATEGORY 1 (1YR)                        AU                                           NA 2013-12-20        NA
20:      14621     3P2643 2012   CATEGORY 1 (1YR)                        AC                              2012 CORRECTION 2012-03-16        NA
21:      33525    3P12113 2016   CATEGORY 1 (1YR)                        AU                                    2016 CAT1 2016-06-27        NA
22:       6335    1P31196 2011   CATEGORY 1 (1YR)                        AC               2010 AFFIRMATION OF CORRECTION 2011-01-21        NA
23:      24970     4P2597 2015   CATEGORY 1 (1YR)                        AU                                           NA 2015-11-09        NA
24:       4851     1W5192 2016   CATEGORY 1 (1YR)                        AU                                           NA 2016-12-02        NA
25:      77057     2P5643 2012   CATEGORY 1 (1YR)                        AC                              2012 CORRECTION 2012-10-31        NA
26:      17247     3P6750 2016   CATEGORY 1 (1YR)                        AU                                    2016 CAT1 2016-06-21        NA
27:      14488     3F1928 2011   CATEGORY 1 (1YR)                        AU                                           NA 2011-08-25        NA
28:       2754    1P11978 2015   CATEGORY 1 (1YR)                        AC               2015 AFFIRMATION OF CORRECTION 2015-07-20        NA
29:      88945    1P33505 2010   CATEGORY 1 (1YR)                        AU                                           NA 2010-12-14        NA
30:       2710    1P14572 2014   CATEGORY 1 (1YR)                        AC                                     2013 AOC 2014-01-17        NA
    record_num device_num year inspection_type_cd inspection_disposition_cd                                      remarks    insp_dt days_late


问:
ELK Stack Setup on Google Cloud: Getting Unable to connect to Elasticsearch at http://localhost:9200 w
I'm installing ELK Stack (version 5.2) on Google Cloud Platform as part of a blog post I'm writing. After following instructions from Elastic themselves, I get the following issue

Kibana Dashboard:

Any ideas on what's preventing ES and Kibana from communicating?

答: As it turns out, the issue was with the Java version on Google Cloud. For some reason, 1.7 was installed and ELK stack 5.x requires Jave 1.8. Once I installed 1.8 everything ran fine.</p>


问:
Scala - anonymous object select query
I have an original C# LINQ Query:

```<code>var rez = planes
    .Where(b => (b.FlDate >= dateFrom) && (b.FlDate <= dateTo))
    .GroupBy(i => i.Destination)
    .Select(g => new { Destination = g.Key, Count = g.Count() })
    .ToList();
</code>```

and re-written Scala-code with issue:

```<code>var rez = planes
  .filter( _.FlDate.getMillis >= dateFrom.getMillis)
  .filter(_.FlDate.getMillis <= dateTo.getMillis)
  .groupBy(_.Destination)
  .flatMap( new { Destination:String = _.Key, Count = _.Count() })//issue is here
</code>```

So main task is to create anonymous objects array with  Destination and Count properties

Scala PlanesLogRow class source:

```<code>import com.github.nscala_time.time.Imports._

class PlanesLogRow {
  var FlDate:DateTime = new DateTime
  var Origin = ""
  var Destination = ""
}
</code>```

答:
There are no C# comaprable anonmyous classes in Scala (although they do exist, they are far less useful IMO). Alternatively, you can use a Tuple2[String, Int] ((String, Int)) which has nice syntax sugar.

For convience, we can create a case class of the PlanesLogRow, which gives us a nice compact way for creating a class (note all values are immutable):

```<code>case class PlanesLogRow(flightDate: ZonedDateTime, origin: String, destination: String)
</code>```

Now let's create a sequence of them:

```<code>val flights = Seq(
  PlanesLogRow(ZonedDateTime.now(), "US", "Kiev"),
  PlanesLogRow(ZonedDateTime.now().plusHours(2L), "US", "Prague"),
  PlanesLogRow(ZonedDateTime.now().plusHours(4L), "Canada", "Prague")
)
</code>```

From and to dates (I used java.time for convenience):

```<code>val dateFrom = ZonedDateTime.now
val dateTo = ZonedDateTime.now().plusHours(5L)
</code>```

Now, we can filter once (no need for two passes over the collection), group, and then output the result to a Map[String, Int]:

```<code>val result: Map[String, Int] =
  flights
    .filter(logRow => logRow.flightDate.isAfter(dateFrom) && logRow.flightDate.isBefore(dateTo))
    .groupBy(_.destination)
    .map { case (location, logRows) => (location, logRows.length) }
</code>```

Yields:

```<code>Map(Prague -> 2)
</code>```

In Scala, unlike LINQ in C#, combinators over collections are strict, not lazy. This means that for every combinator you invoke (map, filter etc) there will be an allocation of a new collection. To get around this, you can use views which produce lazy collections:

```<code>val result =
  flights
    .view
    .filter(logRow => logRow.flightDate.isAfter(dateFrom) && logRow.flightDate.isBefore(dateTo))
    .groupBy(_.destination)
    .map { case (location, logRows) => (location, logRows.length) }
</code>```

Other then that, the naming convention for scala fields are camelCase, not PascalCase like C#.

Title: Scala - anonymous object select query

Body:
I have an original C# LINQ Query:

var rez = planes
    .Where(b => (b.FlDate >= dateFrom) && (b.FlDate <= dateTo))
    .GroupBy(i => i.Destination)
    .Select(g => new { Destination = g.Key, Count = g.Count() })
    .ToList();

and re-written Scala-code with issue:

var rez = planes
  .filter( _.FlDate.getMillis >= dateFrom.getMillis)
  .filter(_.FlDate.getMillis <= dateTo.getMillis)
  .groupBy(_.Destination)
  .flatMap( new { Destination:String = _.Key, Count = _.Count() })//issue is here

So main task is to create anonymous objects array with  Destination and Count properties

Scala PlanesLogRow class source:

import com.github.nscala_time.time.Imports._

class PlanesLogRow {
  var FlDate:DateTime = new DateTime
  var Origin = ""
  var Destination = ""
}

Body:
There are no C# comaprable anonmyous classes in Scala (although they do exist, they are far less useful IMO). Alternatively, you can use a Tuple2[String, Int] ((String, Int)) which has nice syntax sugar.

For convience, we can create a case class of the PlanesLogRow, which gives us a nice compact way for creating a class (note all values are immutable):

case class PlanesLogRow(flightDate: ZonedDateTime, origin: String, destination: String)

Now let's create a sequence of them:

val flights = Seq(
  PlanesLogRow(ZonedDateTime.now(), "US", "Kiev"),
  PlanesLogRow(ZonedDateTime.now().plusHours(2L), "US", "Prague"),
  PlanesLogRow(ZonedDateTime.now().plusHours(4L), "Canada", "Prague")
)

From and to dates (I used java.time for convenience):

val dateFrom = ZonedDateTime.now
val dateTo = ZonedDateTime.now().plusHours(5L)

Now, we can filter once (no need for two passes over the collection), group, and then output the result to a Map[String, Int]:

val result: Map[String, Int] =
  flights
    .filter(logRow => logRow.flightDate.isAfter(dateFrom) && logRow.flightDate.isBefore(dateTo))
    .groupBy(_.destination)
    .map { case (location, logRows) => (location, logRows.length) }

Yields:

Map(Prague -> 2)

In Scala, unlike LINQ in C#, combinators over collections are strict, not lazy. This means that for every combinator you invoke (map, filter etc) there will be an allocation of a new collection. To get around this, you can use views which produce lazy collections:

val result =
  flights
    .view
    .filter(logRow => logRow.flightDate.isAfter(dateFrom) && logRow.flightDate.isBefore(dateTo))
    .groupBy(_.destination)
    .map { case (location, logRows) => (location, logRows.length) }

Other then that, the naming convention for scala fields are camelCase, not PascalCase like C#.


问:
typescript - create type that denotes the set of even numbers
Can anyone know how to create this kind of type?
if 'evenNumbers" is the name of the type, i want for example that:

```<code>let a:evenNumbers = 3
</code>```

will return error and

```<code>let a:evenNumbers = 4
</code>```

will not.

Thanks.

答:
You can define a type like this and throw Error from constructor() method:

```<code>export class EvenNumber{
  value: number;
  constructor(value: number){
    if(value % 2 != 0){
      throw new Error('not even');
    }
    this.value = value;
  }
}
</code>```

Since EvenNumber is a custom type, you should use constructor to instantiate it:

```<code>let a:EvenNumber = new EvenNumber(3);
</code>```

Body:
Can anyone know how to create this kind of type?
if 'evenNumbers" is the name of the type, i want for example that:

let a:evenNumbers = 3

will return error and

let a:evenNumbers = 4

will not.

Thanks.

Body:
You can define a type like this and throw Error from constructor() method:

export class EvenNumber{
  value: number;
  constructor(value: number){
    if(value % 2 != 0){
      throw new Error('not even');
    }
    this.value = value;
  }
}

Since EvenNumber is a custom type, you should use constructor to instantiate it:

let a:EvenNumber = new EvenNumber(3);


问:
How to test Rest API call with swagger if needs authentication
I have springfox-swagger2 (version 2.6.1) and springfox-swagger-ui (version 2.6.1) in spring application.

How to I can configure authorization token for calls which needs authorized for continue (how to set X-AUTH-TOKEN for swagger).

Thanks!

答:
Define the following API key as the security scheme. In your cause a header called X-AUTH-TOKEN. We refer to this scheme using the key mykey.

private ApiKey apiKey() {
  return new ApiKey("mykey", "X-AUTH-TOKEN", "header");
}
```

<ol start="2">
<li>Setup the security context. This just means you're setting up what the authorization scope is for a given path in your API. For e.g. for <code>/anyPath/customers</code> we may require a scope of <code>accessEverything</code>.</li>
</ol>

<pre class="lang-java prettyprint-override"><code>private SecurityContext securityContext() {
    return SecurityContext.builder()
        .securityReferences(defaultAuth())
        .forPaths(PathSelectors.regex("/anyPath.*"))
        .build();
}

List<SecurityReference> defaultAuth() {
  AuthorizationScope authorizationScope
      = new AuthorizationScope("global", "accessEverything");
  AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
  authorizationScopes[0] = authorizationScope;
  return newArrayList(
      new SecurityReference("myKey", authorizationScopes));
}
</code>```

Then in your docket associate the newly created security context and security schemes.

new Docket(...)
    .securitySchemes(newArrayList(apiKey()))
    .securityContexts(newArrayList(securityContext()))
```

<p>Now to enable swagger UI you need to supply the following bean configuration</p>

<pre class="lang-java prettyprint-override"><code>@Bean
SecurityConfiguration security() {
  return new SecurityConfiguration(
      "test-app-client-id",
      "test-app-client-secret",
      "test-app-realm",
      "test-app",
      "YOUR_API_AUTH_TOKEN",
      ApiKeyVehicle.HEADER,
      "X-AUTH-TOKEN",
      "," /*scope separator*/);
}
</code>```

This tells the swagger-ui that you're going to use the api key and provide an api auth token at build time (perhaps using an encrypted configuration property.

NOTE: The swagger-ui is limited in its configurability. It serves the 80% of uses cases. Additional customization might mean you won't be able to use the bundled swagger-ui.

Body:
Define the following API key as the security scheme. In your cause a header called X-AUTH-TOKEN. We refer to this scheme using the key mykey.

private ApiKey apiKey() {
  return new ApiKey("mykey", "X-AUTH-TOKEN", "header");
}

Setup the security context. This just means you're setting up what the authorization scope is for a given path in your API. For e.g. for /anyPath/customers we may require a scope of accessEverything.

private SecurityContext securityContext() {
    return SecurityContext.builder()
        .securityReferences(defaultAuth())
        .forPaths(PathSelectors.regex("/anyPath.*"))
        .build();
}

List<SecurityReference> defaultAuth() {
  AuthorizationScope authorizationScope
      = new AuthorizationScope("global", "accessEverything");
  AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
  authorizationScopes[0] = authorizationScope;
  return newArrayList(
      new SecurityReference("myKey", authorizationScopes));
}

Then in your docket associate the newly created security context and security schemes.

new Docket(...)
    .securitySchemes(newArrayList(apiKey()))
    .securityContexts(newArrayList(securityContext()))

Now to enable swagger UI you need to supply the following bean configuration

@Bean
SecurityConfiguration security() {
  return new SecurityConfiguration(
      "test-app-client-id",
      "test-app-client-secret",
      "test-app-realm",
      "test-app",
      "YOUR_API_AUTH_TOKEN",
      ApiKeyVehicle.HEADER,
      "X-AUTH-TOKEN",
      "," /*scope separator*/);
}

This tells the swagger-ui that you're going to use the api key and provide an api auth token at build time (perhaps using an encrypted configuration property.

NOTE: The swagger-ui is limited in its configurability. It serves the 80% of uses cases. Additional customization might mean you won't be able to use the bundled swagger-ui.


问:
Is it possible to detect if a batch file is started with CALL command or without?
The problems is that CALL command doubles the caret sign ^ and make double percentage a single one. And in hybrid files this can be a big problem.Or if a bat is not executed with CALL from another bat and you want to warn the user.

The %cmdcmdline%(despite this can be used if the file is executed directly from the prompt) and (goto)>nul (eventually this can be used with this) techniques I think are not useful here.

I'm still thinking over this , but if anybody comes with elegant solution will be great.

EDIT. one possible approach is to detect the batch recursion level though a reliable way to check this configuration entry is needed (I have no idea how it is calculated).

答:
As with the Jeb's answer, this can not differentiate if the current batch file has been called or it has been directly invoked from a called batch file. This code just detects if when finished the execution context will be a batch file (there was a call somewhere to reach this point) or the command line (there was not any call or the initial context was the command line). Not the same, but maybe someone could derive a better way from it.

edited after Jeb's comment. I though the echo could be more problematic but it wasn't, so the (goto) approach is clearly a better option.

@echo off
rem Check if this is the initial invocation or we have already determined
rem how the batch file was started

    rem If already tested save method, remove test variable and goto main
    if defined __callTest__ (
        set "startMethod=%__callTest__%"
        set "__callTest__="
        goto :main
    )

rem Initial invocation - Test routine

    rem Cancel current batch context and check if the new context is
    rem   - batch (there was a call somewhere)
    rem   - command line (no call)
    rem Once the invocation method is determined, restart the current batch

    setlocal enableextensions disabledelayedexpansion
    call :getCurrentFile _f0
    (
        rem Cancel context
        2>nul (goto)

        rem The context cancel operation interferes with echo logic. Restore
        echo on

        rem We try to read a non existing variable and see if we could.
        rem   - In command line context, the reading of a non existing variable
        rem     returns the name of the variable, setting our test var
        rem   - In batch context, reading a non existing variable does not
        rem     return anything, and the test variable is undefined

        call set "__callTest__=%%{[%random%""%random%]}%%"
        if defined __callTest__ (
            set "__callTest__=direct"
            "%_f0%" %*
        ) else (
            set "__callTest__=call"
            call "%_f0%" %*
        )
    )
    :getCurrentFile returnVar
        set "%~1=%~f0"
        goto :eof

rem Main batch code
:main
    setlocal enableextensions disabledelayedexpansion
    echo Method invocation is [ %startMethod% ]
    goto :eof
```

And yes, of course, not bullet proof. This code has the habitual batch argument handling problems around %*.

Body:
As with the Jeb's answer, this can not differentiate if the current batch file has been called or it has been directly invoked from a called batch file. This code just detects if when finished the execution context will be a batch file (there was a call somewhere to reach this point) or the command line (there was not any call or the initial context was the command line). Not the same, but maybe someone could derive a better way from it.

edited after Jeb's comment. I though the echo could be more problematic but it wasn't, so the (goto) approach is clearly a better option.

@echo off
rem Check if this is the initial invocation or we have already determined
rem how the batch file was started

    rem If already tested save method, remove test variable and goto main
    if defined __callTest__ (
        set "startMethod=%__callTest__%"
        set "__callTest__="
        goto :main
    )

rem Initial invocation - Test routine

    rem Cancel current batch context and check if the new context is
    rem   - batch (there was a call somewhere)
    rem   - command line (no call)
    rem Once the invocation method is determined, restart the current batch

    setlocal enableextensions disabledelayedexpansion
    call :getCurrentFile _f0
    (
        rem Cancel context
        2>nul (goto)

        rem The context cancel operation interferes with echo logic. Restore
        echo on

        rem We try to read a non existing variable and see if we could.
        rem   - In command line context, the reading of a non existing variable
        rem     returns the name of the variable, setting our test var
        rem   - In batch context, reading a non existing variable does not
        rem     return anything, and the test variable is undefined

        call set "__callTest__=%%{[%random%""%random%]}%%"
        if defined __callTest__ (
            set "__callTest__=direct"
            "%_f0%" %*
        ) else (
            set "__callTest__=call"
            call "%_f0%" %*
        )
    )
    :getCurrentFile returnVar
        set "%~1=%~f0"
        goto :eof

rem Main batch code
:main
    setlocal enableextensions disabledelayedexpansion
    echo Method invocation is [ %startMethod% ]
    goto :eof

And yes, of course, not bullet proof. This code has the habitual batch argument handling problems around %*.


问:
I am unable to write this asp code
I have this C.A.T. where I am supposed to answer several questions using asp.net.
I recently posted one which has no answer yet here.

This current one requires to create a table with with 4 columns and 5 rows using for loop. I have taken a screen shot of the question and included it.

The code I have managed so far is:

```<code><html>
    <body>
    <%
    'dim i
    'for i=0 to 24
    'Response.write(i &"<br/>")
    'next

        'this is some new code

         %>
        <table border="1">
            <%
        for i=0 to 24

        %>
        <tr>
            <td><% response.write(i) %></td>
        </tr>

        <%

        next
    %>
    </table>
    </body>
    </html>
</code>```

Someone help please.

答:
Sample code for the two loops needed:

```<code>For row As Integer = 0 To 4
    For column As Integer = 0 To 4
        Console.Write(String.Format("r{0}c{1} ", row, column))
    Next
    Console.WriteLine
Next
</code>```

You still have to (1) integrate this into your ASP code (Hint: replace the Console.Write/.WriteLine) and (2) go from row and column to the number you need.

Title: I am unable to write this asp code

Body:
I have this C.A.T. where I am supposed to answer several questions using asp.net.
I recently posted one which has no answer yet here.

This current one requires to create a table with with 4 columns and 5 rows using for loop. I have taken a screen shot of the question and included it.

The code I have managed so far is:

    <%
    'dim i
    'for i=0 to 24
    'Response.write(i &"
")
    'next

        'this is some new code

         %>

            <%
        for i=0 to 24

        %>

            <% response.write(i) %>

        <%

        next
    %>

Someone help please.

Body:
Sample code for the two loops needed:

For row As Integer = 0 To 4
    For column As Integer = 0 To 4
        Console.Write(String.Format("r{0}c{1} ", row, column))
    Next
    Console.WriteLine
Next

You still have to (1) integrate this into your ASP code (Hint: replace the Console.Write/.WriteLine) and (2) go from row and column to the number you need.


问:
JQuery hide Class if other class is visible or shown
Found similar questions but nothing that covers exactly what I need.  I kept it simple in my example and I want to use JQuery.

I have two classes.  I want to hide the "filter" div if the "category" div is shown on page load.  There are currently NO styles associated with either class. I believe I am pretty close but it doesn't work.

```<code><script language="text/javascript">
if(!$(this).hasClass("category")){
$('filter').css('display', 'none');
}
</script>

<div class="category">By Category</div>
<div class="filter">By Custom Filter</div>
</code>```

Thanks in advance!

答: Change the selector to $('.filter')

ContentLicense: CC BY-SA 2.5

Body:
Found similar questions but nothing that covers exactly what I need.  I kept it simple in my example and I want to use JQuery.

I have two classes.  I want to hide the "filter" div if the "category" div is shown on page load.  There are currently NO styles associated with either class. I believe I am pretty close but it doesn't work.

By Category

By Custom Filter

Thanks in advance!

Body: Change the selector to $('.filter')


问:
How to get Vim to highlight non-ascii characters?
I'm trying to get Vim to highlight non-ASCII characters. Is there an available setting, regex search pattern, or plugin to do so?</p>

答:
Someone already have answered the question. However, for others that are still having problems, here is another solution to highlight non-ascii characters in comments (or any syntax group in the matter). It's not the best, but it's a temporary fix.

One may try:

```<code>:syntax match nonascii "[^\u0000-\u007F]" containedin=ALL contained |
            \ highlight nonascii ctermfg=yellow guifg=yellow
</code>```

This has mix parts from other solutions. You may remove contained, but, from documentation, there may be potential problem of recursing itself (as I understand). To view other defined patterns,  syn-contains section would contain it.

```<code>:help syn-containedin
:help syn-contains
</code>```

Replicated issue from: Set item to higher highlight priority on vim

Body:
Someone already have answered the question. However, for others that are still having problems, here is another solution to highlight non-ascii characters in comments (or any syntax group in the matter). It's not the best, but it's a temporary fix.

One may try:

:syntax match nonascii "[^\u0000-\u007F]" containedin=ALL contained |
            \ highlight nonascii ctermfg=yellow guifg=yellow

This has mix parts from other solutions. You may remove contained, but, from documentation, there may be potential problem of recursing itself (as I understand). To view other defined patterns,  syn-contains section would contain it.

:help syn-containedin
:help syn-contains

Replicated issue from: Set item to higher highlight priority on vim


问:
Mongodb Update Embedded Documents Using Multiple Field Matches with C# driver
I have a document structure on mongodb like below:

```<code>{
    _id: <string>,
    field1: ...,
    field2: ...,
    field3: ...,
    DeviceVersionPairs: [{
            DeviceId: <ObjectId>,
            CloudFolderId: <ObjectId>,
            CloudFileId: <ObjectId>,
            VersionId: <ObjectId>,
            Status: <int>
        },{
            DeviceId: <ObjectId>,
            CloudFolderId: <ObjectId>,
            CloudFileId: <ObjectId>,
            VersionId: <ObjectId>,
            Status: <int>
        },
        ....
    ]
}
</code>```

I wrote this mongodb query, it is designed to find the row with the _id given than update the subdocument in its DeviceVersionPairs array matching the elemMatch filter, which actually works;

```<code>db.deduplications.update({
    "_id": "...",
    "DeviceVersionPairs": { "$elemMatch" : {
        "DeviceId": ObjectId("..."),
        "CloudFolderId": ObjectId("..."),
        "CloudFileId": ObjectId("..."),
        "VersionId": ObjectId("...")
    }}
},{
    "$set": { "DeviceVersionPairs.$.Status": 100 }
}, false, false)
</code>```

But I can't convert it to use with C# driver(2.0.1.27). So far I had this, but this lacks the elemMatch statement, hence it doesn't work as expected.

```<code>var p = DbContext.Deduplications.FindOneAndUpdateAsync(
    filter: Builders<Dal.Deduplication>.Filter.And(
        Builders<Dal.Deduplication>.Filter.Eq("_id", fileHash),
        Builders<Dal.Deduplication>.Filter.Eq("DeviceVersionPairs.DeviceId", deviceId),
        Builders<Dal.Deduplication>.Filter.Eq("DeviceVersionPairs.CloudFolderId", CloudFolderId),
        Builders<Dal.Deduplication>.Filter.Eq("DeviceVersionPairs.CloudFileId", FileId),
        Builders<Dal.Deduplication>.Filter.Eq("DeviceVersionPairs.VersionId", versionIdToBeRemoved)),
    update: Builders<Dal.Deduplication>.Update.Set("DeviceVersionPairs.$.Status", DVPStatus.PassiveOrDeleted)).Result;
</code>```

What is the way to make such a request to mongodb using C# driver?

答:
Finally I've come up with my own solution. Creating the filter using the regular BsonDocument objects did the job.

```<code>var filter = new BsonDocument(new List<BsonElement> {
    new BsonElement("_id", fileHash),
    new BsonElement("DeviceVersionPairs", new BsonDocument("$elemMatch", new BsonDocument(new List<BsonElement> {
        new BsonElement("DeviceId", deviceId),
        new BsonElement("CloudFolderId", cloudFolderId),
        new BsonElement("CloudFileId", cloudFileId),
        new BsonElement("VersionId", versionId)
    })))
});
</code>```

Body:
I have a document structure on mongodb like below:

{
    _id: <string>,
    field1: ...,
    field2: ...,
    field3: ...,
    DeviceVersionPairs: [{
            DeviceId: <ObjectId>,
            CloudFolderId: <ObjectId>,
            CloudFileId: <ObjectId>,
            VersionId: <ObjectId>,
            Status: <int>
        },{
            DeviceId: <ObjectId>,
            CloudFolderId: <ObjectId>,
            CloudFileId: <ObjectId>,
            VersionId: <ObjectId>,
            Status: <int>
        },
        ....
    ]
}

I wrote this mongodb query, it is designed to find the row with the _id given than update the subdocument in its DeviceVersionPairs array matching the elemMatch filter, which actually works;

db.deduplications.update({
    "_id": "...",
    "DeviceVersionPairs": { "$elemMatch" : {
        "DeviceId": ObjectId("..."),
        "CloudFolderId": ObjectId("..."),
        "CloudFileId": ObjectId("..."),
        "VersionId": ObjectId("...")
    }}
},{
    "$set": { "DeviceVersionPairs.$.Status": 100 }
}, false, false)

But I can't convert it to use with C# driver(2.0.1.27). So far I had this, but this lacks the elemMatch statement, hence it doesn't work as expected.

var p = DbContext.Deduplications.FindOneAndUpdateAsync(
    filter: Builders<Dal.Deduplication>.Filter.And(
        Builders<Dal.Deduplication>.Filter.Eq("_id", fileHash),
        Builders<Dal.Deduplication>.Filter.Eq("DeviceVersionPairs.DeviceId", deviceId),
        Builders<Dal.Deduplication>.Filter.Eq("DeviceVersionPairs.CloudFolderId", CloudFolderId),
        Builders<Dal.Deduplication>.Filter.Eq("DeviceVersionPairs.CloudFileId", FileId),
        Builders<Dal.Deduplication>.Filter.Eq("DeviceVersionPairs.VersionId", versionIdToBeRemoved)),
    update: Builders<Dal.Deduplication>.Update.Set("DeviceVersionPairs.$.Status", DVPStatus.PassiveOrDeleted)).Result;

What is the way to make such a request to mongodb using C# driver?

Body:
Finally I've come up with my own solution. Creating the filter using the regular BsonDocument objects did the job.

var filter = new BsonDocument(new List<BsonElement> {
    new BsonElement("_id", fileHash),
    new BsonElement("DeviceVersionPairs", new BsonDocument("$elemMatch", new BsonDocument(new List<BsonElement> {
        new BsonElement("DeviceId", deviceId),
        new BsonElement("CloudFolderId", cloudFolderId),
        new BsonElement("CloudFileId", cloudFileId),
        new BsonElement("VersionId", versionId)
    })))
});


问:
How to publish report from jasper studio to jasper server
How to publish report from jasper studio to jasper server?

will I publish the main report only or  Including the sub reports?

答:
You can publish report as given in Jasper documentation.

You also have to publish subreport.


问:
c# combination of List of List items
I have a List<TeamName>, where class TeamName contains the List<MembersName>

So I have something like this:

```<code>List<TeamName> teamNameList //each item of "tnl" has public member "memberNameList"
</code>```

...

```<code>class TeamName //each team has different member
{
   public TName
   public List<MemberName> memberNameLis;
}

class MemberName
{
     public MName;
}
</code>```

Now i want to make all possible combination of MemberName from each Team.

e.g.  I have 3 teams (T1, T2, T3) they have members count as -

T1 = 3 members, T2 = 2 Members, T3 = 1 member,

So now I need something -

T1M1 T2M1 T3M1

T1M1 T2M2 T3M1

T1M2 T2M1 T3M1

T1M2 T2M2 T3M1

T1M3 T2M1 T3M1

T1M3 T2M2 T3M1

```<code>List<List<MemberName>> combi;
</code>```

how to do this in Code?
i am just a beginner so kindly pardon me for not asking a question in a clean pattern.
help please :)

答:
lets say you have your team list as -

```<code>List<TeamName> tnl;
...
...
...

// now you can call like -
IEnumerable<IEnumerable<MemberName>> allPossible = CartesianProduct(tnl.Select(c => c.mnl));
...
...
</code>```

And Cartesian Product method will be the same

```<code>IEnumerable<IEnumerable<T>> CartesianProduct<T>(IEnumerable<IEnumerable<T>> sequences)
{
    IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
    return sequences.Aggregate(
        emptyProduct,
        (accumulator, sequence) =>
            from accseq in accumulator
            from item in sequence
            select accseq.Concat(new[] { item })
        );
}
</code>```

Try it, for your input it will give you your required result.

if you will loop -

```<code> foreach (var item in r4)
 {
     foreach (var mn in item)
     {
         Console.Write("\t"+mn.Name);
     }
     Console.WriteLine();
 }
</code>```

you will get your answer -

```<code>T1M1    T2M1    T3M1
T1M1    T2M2    T3M1
T1M2    T2M1    T3M1
T1M2    T2M2    T3M1
T1M3    T2M1    T3M1
T1M3    T2M2    T3M1
</code>```

I have tested it.

Title: c# combination of List of List items

Body:
I have a List<TeamName>, where class TeamName contains the List<MembersName>

So I have something like this:

List<TeamName> teamNameList //each item of "tnl" has public member "memberNameList"

...

class TeamName //each team has different member
{
   public TName
   public List<MemberName> memberNameLis;
}

class MemberName
{
     public MName;
}

Now i want to make all possible combination of MemberName from each Team.

e.g.  I have 3 teams (T1, T2, T3) they have members count as -

T1 = 3 members, T2 = 2 Members, T3 = 1 member,

So now I need something -

T1M1 T2M1 T3M1

T1M1 T2M2 T3M1

T1M2 T2M1 T3M1

T1M2 T2M2 T3M1

T1M3 T2M1 T3M1

T1M3 T2M2 T3M1

List<List<MemberName>> combi;

how to do this in Code?
i am just a beginner so kindly pardon me for not asking a question in a clean pattern.
help please :)

Body:
lets say you have your team list as -

List<TeamName> tnl;
...
...
...

// now you can call like -
IEnumerable<IEnumerable<MemberName>> allPossible = CartesianProduct(tnl.Select(c => c.mnl));
...
...

And Cartesian Product method will be the same

IEnumerable<IEnumerable<T>> CartesianProduct<T>(IEnumerable<IEnumerable<T>> sequences)
{
    IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
    return sequences.Aggregate(
        emptyProduct,
        (accumulator, sequence) =>
            from accseq in accumulator
            from item in sequence
            select accseq.Concat(new[] { item })
        );
}

Try it, for your input it will give you your required result.

if you will loop -

 foreach (var item in r4)
 {
     foreach (var mn in item)
     {
         Console.Write("\t"+mn.Name);
     }
     Console.WriteLine();
 }

you will get your answer -

T1M1    T2M1    T3M1
T1M1    T2M2    T3M1
T1M2    T2M1    T3M1
T1M2    T2M2    T3M1
T1M3    T2M1    T3M1
T1M3    T2M2    T3M1

I have tested it.


问:
How to save Persian date time in SQL server?
In past projects, I tried to save my time format in Gregorian dates
and convert Gregorian dates to Persian in the logic layer of application, but I'm tired of doing it in that way.

I need save and restore date time with format of Persian in sql server without any conversion

Can type of datetime2 in sql server store Persian date time?

If not, what is the best way to store Persian date time?

答:
datetime2 in SQL Server uses the Gregorian calendar.

If you want to use dates based on the Persian calendar, then you either need to make and use some functions that you can call in your SQL code to do the conversion for you, or you need to make a User Defined Type that can store the data.

Here's an example of some functions that can convert between Persian and Gregorian. I haven't tried them out so I have no idea if they work, or to their quality.

I couldn't find an example of creating a UDT for Persian dates, but this is the documentation for UDTs in general.

Personally, I would store the dates in SQL Server as UTC Gregorian datetime2. And I'd either have conversion code in the application data layer that converts them when saving to, and loading from SQL Server, or I'd do the conversion when the DateTime is displayed to/retrieved from the user.

UTC is the date and time standard for the world, especially for science and engineering, and as such SQL Server and .Net have been built using it. It makes sense to also use UTC so that you can get the most benefit from the existing SQL Server and .Net code. Of course your users still want to be able to write and read a DateTime using the Persian calendar, so it makes sense to me that you'd perform that conversion just before one will be displayed to the user, or just after the user has provided one.


问:
Scala Phantom Cassandra insert method returns empty ResultSet
I want to insert data to my table in Cassandra and then return value from column "user_id" instead of full ResultSet. Here it is snippet of my code:

```<code>   def create(user: User): Future[UUID] = {
     insert
       .value(_.id, user.id)
       .value(_.email, user.email)
       .value(_.name, user.name)
       .consistencyLevel_=(ConsistencyLevel.ALL)
       .future()
       .map(r => fromRow(r.one()).id)
    }

   def fromRow(r: Row): User = {
     User(id(r), email(r), name(r))
   }
</code>```

So future() returns Future[ResultSet]. After that I try to retrieve Row from ResultSet, modify it to User and get id eventually. Despite the fact that data were saved to my table I got

ResultSet[ exhausted: true, Columns[]]

columns of the ResultSet are empty and consequently r.one() returned null.
I haven't found any examples for my purpose. So, can phantom-dsl do something like Quill?

```<code>val q = quote {
  query[Product].insert(lift(Product(0L, "My Product", 1011L))).returning(_.id)
}
</code>```

答:
So in more recent versions of phantom that create method is automatically generated. More details here. The fromRow method is also automatically generated so you don't need to type it manually.

Long story short, this is what you could use:

```<code>def create(user: User): Future[UUID] = {
  store(user)
    .consistencyLevel_=(ConsistencyLevel.ALL)
    .future()
    .map(_ => user.id)
}
</code>```

Body:
I want to insert data to my table in Cassandra and then return value from column "user_id" instead of full ResultSet. Here it is snippet of my code:

   def create(user: User): Future[UUID] = {
     insert
       .value(_.id, user.id)
       .value(_.email, user.email)
       .value(_.name, user.name)
       .consistencyLevel_=(ConsistencyLevel.ALL)
       .future()
       .map(r => fromRow(r.one()).id)
    }

   def fromRow(r: Row): User = {
     User(id(r), email(r), name(r))
   }

So future() returns Future[ResultSet]. After that I try to retrieve Row from ResultSet, modify it to User and get id eventually. Despite the fact that data were saved to my table I got

ResultSet[ exhausted: true, Columns[]]

columns of the ResultSet are empty and consequently r.one() returned null.
I haven't found any examples for my purpose. So, can phantom-dsl do something like Quill?

val q = quote {
  query[Product].insert(lift(Product(0L, "My Product", 1011L))).returning(_.id)
}

Body:
So in more recent versions of phantom that create method is automatically generated. More details here. The fromRow method is also automatically generated so you don't need to type it manually.

Long story short, this is what you could use:

def create(user: User): Future[UUID] = {
  store(user)
    .consistencyLevel_=(ConsistencyLevel.ALL)
    .future()
    .map(_ => user.id)
}


问:
Handle change event not working for input types?
I am new to react… my handle change event is not working while typing text into an input. How do I go about fixing that? I want to handle both inputs with the same handle change.

```<code>import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            first_name:'',
            last_name:''
        }
    }
    handleChange(e){
        var first_name = e.target.first_name
        var last_name = e.target.last_name
        var state = this.state
        state[first_name] = e.target.value
        state[last_name] = e.target.value
        this.setState(state)
    }
    render() {
        return (
          <div>
              <TextField hint text="First Name" id="user_first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
              <TextField hint text="Last Name" id="user_last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />
          </div>
        )
    }
}
</code>```

答:
as you're using material-ui/TextField component updating state by target.id can't work, because TextField component doesn't pass your id to its input, so you can do it by adding second parameter to your handleChange function, like this:

import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
  constructor(props) {
    super(props)
     this.state = {
      first_name:'',
      last_name:''
    }
  }
  handleChange(value, param){
     this.setState({[param]: value});
  }
  render() {
    return (

            <TextField hint text="First Name" id="first_name" floatingLabelFixed="editprofile" onChange={(e) => this.handleChange(e.target.value, 'first_name')} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
            <TextField hint text="Last Name" id="last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={(e) => this.handleChange(e.target.value, 'last_name')} size="30" type="text" value={this.state.last_name} />

  )}
}```

Body:
I am new to react… my handle change event is not working while typing text into an input. How do I go about fixing that? I want to handle both inputs with the same handle change.

import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            first_name:'',
            last_name:''
        }
    }
    handleChange(e){
        var first_name = e.target.first_name
        var last_name = e.target.last_name
        var state = this.state
        state[first_name] = e.target.value
        state[last_name] = e.target.value
        this.setState(state)
    }
    render() {
        return (

              <TextField hint text="First Name" id="user_first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
              <TextField hint text="Last Name" id="user_last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />

        )
    }
}

Body:
as you're using material-ui/TextField component updating state by target.id can't work, because TextField component doesn't pass your id to its input, so you can do it by adding second parameter to your handleChange function, like this:

import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
  constructor(props) {
    super(props)
     this.state = {
      first_name:'',
      last_name:''
    }
  }
  handleChange(value, param){
     this.setState({[param]: value});
  }
  render() {
    return (
    <div>
            <TextField hint text="First Name" id="first_name" floatingLabelFixed="editprofile" onChange={(e) => this.handleChange(e.target.value, 'first_name')} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
            <TextField hint text="Last Name" id="last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={(e) => this.handleChange(e.target.value, 'last_name')} size="30" type="text" value={this.state.last_name} />
      </div>
  )}
}


问:
PostgreSQL Need to make TOTAL ROW
enter image description hereHello I'm Begginer and I need some help, I have this code in my SQL database

```<code>SELECT round(SUM(Cena)::NUMERIC,2) AS CelkovaCena, a.Meno, a.Priezvisko,Nazov
FROM Predstavenie
JOIN Autor a ON Predstavenie.ID_Autor = a.ID_Autor
WHERE a.Meno = 'Juraj' AND a.Priezvisko = 'Klein'
GROUP BY a.Meno,a.Priezvisko,Nazov;
</code>```

This is what i get after i run this SELECT.

```<code>2.2 |    Juraj   |  Klein  |    Po východe slnka
5.4 |    Juraj   |  Klein  |    Ako išiel Ferenc po hlavnej
0.5 |    Juraj   |  Klein  |    Protialkoholické hnutie Klein Ferenc PHKF
</code>```

I need to make total row below, from col "cena". I need to have something like this.

```<code>2.2 |    Juraj   |  Klein  |    Po východe slnka
5.4 |    Juraj   |  Klein  |    Ako išiel Ferenc po hlavnej
0.5 |    Juraj   |  Klein  |    Protialkoholické hnutie Klein Ferenc PHKF
8.1 |                      |                          |
</code>```

Rollup doesnt seem to work because of groups. I looked up on internet for various solutions, but none of them works... Thank you.

答:
Use GROUPING SETS:

```<code>SELECT round(SUM(Cena)::NUMERIC,2) AS CelkovaCena, a.Meno,
       a.Priezvisko, Nazov
FROM Predstavenie p JOIN
     Autor a
     ON p.ID_Autor = a.ID_Autor
WHERE a.Meno = 'Juraj' AND a.Priezvisko = 'Klein'
GROUP BY GROUPING SETS ((a.Meno, a.Priezvisko, Nazov), ());
</code>```

This is like ROLLUP but it allows you to explicitly list the summary rows that you want.

Title: PostgreSQL Need to make TOTAL ROW

Body:
enter image description hereHello I'm Begginer and I need some help, I have this code in my SQL database

SELECT round(SUM(Cena)::NUMERIC,2) AS CelkovaCena, a.Meno, a.Priezvisko,Nazov
FROM Predstavenie
JOIN Autor a ON Predstavenie.ID_Autor = a.ID_Autor
WHERE a.Meno = 'Juraj' AND a.Priezvisko = 'Klein'
GROUP BY a.Meno,a.Priezvisko,Nazov;

This is what i get after i run this SELECT.

2.2 |    Juraj   |  Klein  |    Po východe slnka
5.4 |    Juraj   |  Klein  |    Ako išiel Ferenc po hlavnej
0.5 |    Juraj   |  Klein  |    Protialkoholické hnutie Klein Ferenc PHKF

I need to make total row below, from col "cena". I need to have something like this.

2.2 |    Juraj   |  Klein  |    Po východe slnka
5.4 |    Juraj   |  Klein  |    Ako išiel Ferenc po hlavnej
0.5 |    Juraj   |  Klein  |    Protialkoholické hnutie Klein Ferenc PHKF
8.1 |                      |                          |

Rollup doesnt seem to work because of groups. I looked up on internet for various solutions, but none of them works... Thank you.

Body:
Use GROUPING SETS:

SELECT round(SUM(Cena)::NUMERIC,2) AS CelkovaCena, a.Meno,
       a.Priezvisko, Nazov
FROM Predstavenie p JOIN
     Autor a
     ON p.ID_Autor = a.ID_Autor
WHERE a.Meno = 'Juraj' AND a.Priezvisko = 'Klein'
GROUP BY GROUPING SETS ((a.Meno, a.Priezvisko, Nazov), ());

This is like ROLLUP but it allows you to explicitly list the summary rows that you want.


问:
How to reverse a transformation by matrix in Blender?
I have a selected mesh (creatively called 'selected') which I want to work with in its local space so I use the following:

```<code>    tmesh = NMesh.GetRawFromObject(selected.name)
    tmesh.transform(selected.matrix)
</code>```

I then do a bunch of calculations on its verticies and remove them by index, which works great.

What doesn't work so great is when I try to add them back later from a list of vert.co objects. They end up being positioned correctly relative to each other, but nowhere near the original verticies.

```<code>            for v in tmesh.verts:
                 toAdd.append(v.co)
              mesh = selected.getData(mesh=1)
              mesh.verts.extend(toAdd)
</code>```

I realized this is because the object is in a different space. So I think what I need to do is translate the new verticies back to the old space... but my understanding of what exactly is going on here is fuzzy at best. How do I "undo" the tmesh.transform(selected.matrix) command?

A more thoroug explanation of what I'm doing can be found here: http://www.kellbot.com/2010/11/lego-plans-now-with-better-rendering/

答: I'm not familiar with Blender specfically, but after a quick peek at the documentation, in principle it seems like you ought to be able to use the invert() Matrix method to obtain the inverse transformation of the selected.matrix (perhaps after first making a copy() of it).

Body:
I have a selected mesh (creatively called 'selected') which I want to work with in its local space so I use the following:

    tmesh = NMesh.GetRawFromObject(selected.name)
    tmesh.transform(selected.matrix)

I then do a bunch of calculations on its verticies and remove them by index, which works great.

What doesn't work so great is when I try to add them back later from a list of vert.co objects. They end up being positioned correctly relative to each other, but nowhere near the original verticies.

            for v in tmesh.verts:
                 toAdd.append(v.co)
              mesh = selected.getData(mesh=1)
              mesh.verts.extend(toAdd)

I realized this is because the object is in a different space. So I think what I need to do is translate the new verticies back to the old space... but my understanding of what exactly is going on here is fuzzy at best. How do I "undo" the tmesh.transform(selected.matrix) command?

A more thoroug explanation of what I'm doing can be found here: http://www.kellbot.com/2010/11/lego-plans-now-with-better-rendering/

ContentLicense: CC BY-SA 4.0


问:
html, css, javascript - show/hide divs - one is shown than another should be hidden
I want to create show/hide div's.
It is my code: jsfiddle.net/b60b34h1

But it don't works like I want.
I want that when "press button2" pressed than another div's should hidden.
It should show only one div.

Can You help me?
Thanks

答:
function unhide(divID) {
    var item = document.getElementById('button' + divID);
    if (item) {
      item.className = 'unhidden';

      // hidden other divs
      for (var i = 1; i <= 3; i++) {
        if (i != divID) {
          document.getElementById('button' + i).className = 'hidden';
        }
      }

    }
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none;
}

.unhidden {
  display: block;
}</code>```

press button1 press button2 press button3

button1

abc

abc

abc

button2

abc

abc

abc

button3

abc

abc

abc

```

Body:
function unhide(divID) {
    var item = document.getElementById('button' + divID);
    if (item) {
      item.className = 'unhidden';

      // hidden other divs
      for (var i = 1; i <= 3; i++) {
        if (i != divID) {
          document.getElementById('button' + i).className = 'hidden';
        }
      }

    }
  }

.hidden {
  display: none;
}

.unhidden {
  display: block;
}

<div>
  <p><a href="javascript:void(0);" onclick="unhide(1)">press button1</a> <a href="javascript:void(0);" onclick="unhide(2)">press button2</a> <a href="javascript:void(0);" onclick="unhide(3)">press button3</a></p>
  <div class="unhidden" id="button1">
    <h3>button1</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
  <div class="hidden" id="button2">
    <h3>button2</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
  <div class="hidden" id="button3">
    <h3>button3</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
</div>


问:
Mongo DB collections are not found
I am using MongoDB as my data storage, version v3.4.1. I am using a docker image of mongo, running it like this:

```<code>docker run -d -p 27017:27017 -v /home/rancher/data:/data/db --name mongodb mongo:latest
</code>```

After that I created many databases and collections. It was fine for more than one month; but now I am not able to find any collections inside the data base. This command to list collections is showing an empty list: show dbs. Alternatively, if I do use mydb then show collections nothing is displayed.

These are the data in the /home/rancher/data folder:

collection-0--4220404477553112134.wt

  collection-0-1041804628168690390.wt

  collection-2--4220404477553112134.wt

  collection-2-1041804628168690390.wt

  diagnostic.data

  index-1--4220404477553112134.wt

  index-1-1041804628168690390.wt

  index-3--4220404477553112134.wt

  index-3-1041804628168690390.wt

  index-4-1041804628168690390.wt

  journal

  _mdb_catalog.wt

  mongod.lock

  sizeStorer.wt

  storage.bson

  WiredTiger

  WiredTiger.lock

  WiredTiger.turtle

  WiredTiger.wt

  WiredTigerLAS.wt

Can anyone tell me why the collections are not persistent in mongo DB?

答:
you may have ran into a problem with mongo:latest tag and how mongodb changed the default driver they used for data files.

it's a bad idea to use :latest tag of any image because things change between images, and problems like this can happen.

switch to a previous release, like 3.2, and see if it finds you data

docker run -d -p 27017:27017 -v /home/rancher/data:/data/db --name mongodb mongo:3.2.12

Title: Mongo DB collections are not found

Body:
I am using MongoDB as my data storage, version v3.4.1. I am using a docker image of mongo, running it like this:

docker run -d -p 27017:27017 -v /home/rancher/data:/data/db --name mongodb mongo:latest

After that I created many databases and collections. It was fine for more than one month; but now I am not able to find any collections inside the data base. This command to list collections is showing an empty list: show dbs. Alternatively, if I do use mydb then show collections nothing is displayed.

These are the data in the /home/rancher/data folder:

collection-0--4220404477553112134.wt

  collection-0-1041804628168690390.wt

  collection-2--4220404477553112134.wt

  collection-2-1041804628168690390.wt

  diagnostic.data

  index-1--4220404477553112134.wt

  index-1-1041804628168690390.wt

  index-3--4220404477553112134.wt

  index-3-1041804628168690390.wt

  index-4-1041804628168690390.wt

  journal

  _mdb_catalog.wt

  mongod.lock

  sizeStorer.wt

  storage.bson

  WiredTiger

  WiredTiger.lock

  WiredTiger.turtle

  WiredTiger.wt

  WiredTigerLAS.wt

Can anyone tell me why the collections are not persistent in mongo DB?


问:
Pandas: Keep rows if at least one of them contains certain value
I have the following dataframe in Pandas

```<code>letter  number
------ -------
a       2
a       0
b       1
b       5
b       2
c       1
c       0
c       2
</code>```

I'd like to keep all rows if at least one matching number is 0.
Result would be:

```<code>letter  number
------ -------
a       2
a       0
c       1
c       0
c       2
</code>```

as b has no matching number being 0

What is the best way to do this ?
Thanks !

答:
You need filtration:

```<code>df = df.groupby('letter').filter(lambda x: (x['number'] == 0).any())
print (df)
  letter  number
0      a       2
1      a       0
5      c       1
6      c       0
7      c       2
</code>```

Another solution with transform where get size of 0 rows and filter by boolean indexing:

```<code>print (df.groupby('letter')['number'].transform(lambda x: (x == 0).sum()))
0    1
1    1
2    0
3    0
4    0
5    1
6    1
7    1
Name: number, dtype: int64

df = df[df.groupby('letter')['number'].transform(lambda x: (x == 0).sum()) > 0]
print (df)
  letter  number
0      a       2
1      a       0
5      c       1
6      c       0
7      c       2
</code>```

EDIT:

Faster is not use groupby, better is loc with isin:

```<code>df1 = df[df['letter'].isin(df.loc[df['number'] == 0, 'letter'])]
print (df1)
  letter  number
0      a       2
1      a       0
5      c       1
6      c       0
7      c       2
</code>```

Comparing with another solution:

```<code>In [412]: %timeit df[df['letter'].isin(df[df['number'] == 0]['letter'])]
1000 loops, best of 3: 815 µs per loop

In [413]: %timeit df[df['letter'].isin(df.loc[df['number'] == 0, 'letter'])]
1000 loops, best of 3: 657 µs per loop
</code>```

Body:
I have the following dataframe in Pandas

letter  number
------ -------
a       2
a       0
b       1
b       5
b       2
c       1
c       0
c       2

I'd like to keep all rows if at least one matching number is 0.
Result would be:

letter  number
------ -------
a       2
a       0
c       1
c       0
c       2

as b has no matching number being 0

What is the best way to do this ?
Thanks !

Body:
You need filtration:

df = df.groupby('letter').filter(lambda x: (x['number'] == 0).any())
print (df)
  letter  number
0      a       2
1      a       0
5      c       1
6      c       0
7      c       2

Another solution with transform where get size of 0 rows and filter by boolean indexing:

print (df.groupby('letter')['number'].transform(lambda x: (x == 0).sum()))
0    1
1    1
2    0
3    0
4    0
5    1
6    1
7    1
Name: number, dtype: int64

df = df[df.groupby('letter')['number'].transform(lambda x: (x == 0).sum()) > 0]
print (df)
  letter  number
0      a       2
1      a       0
5      c       1
6      c       0
7      c       2

EDIT:

Faster is not use groupby, better is loc with isin:

df1 = df[df['letter'].isin(df.loc[df['number'] == 0, 'letter'])]
print (df1)
  letter  number
0      a       2
1      a       0
5      c       1
6      c       0
7      c       2

Comparing with another solution:

In [412]: %timeit df[df['letter'].isin(df[df['number'] == 0]['letter'])]
1000 loops, best of 3: 815 µs per loop

In [413]: %timeit df[df['letter'].isin(df.loc[df['number'] == 0, 'letter'])]
1000 loops, best of 3: 657 µs per loop


问:
Android javax.net.ssl and FIPS compliance openSSL
AFAIK Android javax.net.ssl classes uses openSSL/BoringSSL library at C/Low level for any SSL/TLS.

Intention: Load FIPS compliance openSSL libaray in my application and make javax.net.ssl(okhttp) classes use the that library?

Simlilar to WolfSSL provider,but its not JSSE compatible.

is this feasible with FIPS openSSL+ android, what are configuration at android java level ?

Thanks

答:
Modified OKHTTP and OKIO code to use the WolfSSL java wrappers and made it work.

Now any https requests made will go to WolfSSL layer instead of stock android BoringSSL/OpenSSL.


问:
Should i use std::vector of std::unique_ptr<T[]> if memory is sparse and i'm not going to resize
Suppose i have physics engine which need to solve systems of linear equation size of which is unknown in forward, but after i know it, i will not change it. One such matrix may easily take hundreds of kilobytes. The problem with vector is that i never really know how much space it has allocated and i don't want to allocate more than needed.

Most discussion tell us to use std::vector, but should i use std::unique_ptr<T[]> instead? Hm... maybe i need to use std allocator as this answer suggests?

From the standard:

After reserve(), capacity() is greater or equal to the argument of
  reserve if reallocation happens; and equal to the previous value of
  capacity() otherwise.

So it is not the option for me to use reserve.

I also found that there was proposition for dynarray which should have handled my case, and for now that is the way i'm going to take, if no other propositions will come.

答:
From what you have said in your question, I would say that usage of std::vector should be fine: as soon as you know the size, you can reserve it in your vector(s) and there will ne no additional overhead because no allocation will never happen again in that part.

Of course, as a vector does allocate a raw array under the hood, you can also allocate it as soon as the size if known and deallocate it when done, but the memory gain should be limited to size of the vector struct itself, at least for 1-D arrays.

If you have huge multi-dimensional arrays, the gain will be higher because you will have on vector struct per row (and per plane in 3-D array), so using raw arrays instead of vector of size nn will be nsizeof(vector)

But it is a low level optimization, so you should only worry for that after all higher level optimizations have been exhausted (storing only one half for symetric matrixes for example).


问:
on click the control's size changes
I have an input type as below with me for the Date of Birth.

```<code><div class="input-div spanicon">
   <input placeholder="Enter Date of Birth" class="textbox-n" type="text" id="txtDOB">
   <i class="fa fa-calendar" id="triggerCal" aria-hidden="true"></i>
</div>
</code>```

Here's the fiddle for the same.

On click of the icon, field's size changes, Can someone help on this.

答:
This happen type=text change to type=date and applies different style. this is just a simple trick.

  <input placeholder="Enter Date of Birth" class="textbox-n" type="text" id="txtDOB" onfocus="(this.type='date')">

```

Title: on click the control's size changes

Body:
I have an input type as below with me for the Date of Birth.

   <input placeholder="Enter Date of Birth" class="textbox-n" type="text" id="txtDOB">

Here's the fiddle for the same.

On click of the icon, field's size changes, Can someone help on this.

Body:
This happen type=text change to type=date and applies different style. this is just a simple trick.

<div class="input-div spanicon">
  <input placeholder="Enter Date of Birth" class="textbox-n" type="text" id="txtDOB" onfocus="(this.type='date')">
  <i class="fa fa-calendar" id="triggerCal" aria-hidden="true"></i></div>


问:
How to send file from a system accessible from load balancer through attachment in mail using java?
My two server machines are deployed behind a load balancer for high availability. When a user upload a file through browser, the file is stored on any of the server machine behind load balancer.
I want that file to send as an attachment through mail to the user using java but I don't know how to get the file path behind the load balancer?</p>

答:
I had faced this problem recently, and did some research about this. The best solution that I found was to keep a shared memory on some third machine, which would be accessible by both of your server machines. The file would be read and written from that machine only. The location of the file can be either kept in central logs, or central database.

Note that the way you are trying to do this requires the two machines to communicate with each other (network communication). By doing this, you would increase the request service time. Also, you'll get rid of the "high availability" requirement because one download request will invoke both the server machines (in worst case).


问:
Camera option is disabled in settings but getting PHAuthorizationStatus as PHAuthorizationStatusAuthorized
// Checking for authorization

```<code>PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

if (status == PHAuthorizationStatusAuthorized) {
    // Access has been granted.

}
else if (status == PHAuthorizationStatusDenied) {
    // Access has been denied.

}
else if (status == PHAuthorizationStatusNotDetermined) {
    // Access has not been determined.
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            // Access has been granted.

        }
        else {
            // Access has been denied.

        }
    }];
}
else if (status == PHAuthorizationStatusRestricted) {
    // Restricted access - normally won't happen.

}
</code>```

I have set the keys in Info.plist both for Camera and Photos still getting the same result.

答:
You should use another method to check camera authorization status:

```<code>NSString *mediaType = AVMediaTypeVideo;
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
if(authStatus == AVAuthorizationStatusAuthorized) {
  // do your logic
} else if(authStatus == AVAuthorizationStatusDenied){
  // denied
} else if(authStatus == AVAuthorizationStatusRestricted){
  // restricted, normally won't happen
} else if(authStatus == AVAuthorizationStatusNotDetermined){
  // not determined?!
  [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
    if(granted){
      NSLog(@"Granted access to %@", mediaType);
    } else {
      NSLog(@"Not granted access to %@", mediaType);
    }
  }];
} else {
  // impossible, unknown authorization status
}
</code>```

Link to related question

Body:
// Checking for authorization

PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

if (status == PHAuthorizationStatusAuthorized) {
    // Access has been granted.

}
else if (status == PHAuthorizationStatusDenied) {
    // Access has been denied.

}
else if (status == PHAuthorizationStatusNotDetermined) {
    // Access has not been determined.
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            // Access has been granted.

        }
        else {
            // Access has been denied.

        }
    }];
}
else if (status == PHAuthorizationStatusRestricted) {
    // Restricted access - normally won't happen.

}

I have set the keys in Info.plist both for Camera and Photos still getting the same result.

Body:
You should use another method to check camera authorization status:

NSString *mediaType = AVMediaTypeVideo;
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
if(authStatus == AVAuthorizationStatusAuthorized) {
  // do your logic
} else if(authStatus == AVAuthorizationStatusDenied){
  // denied
} else if(authStatus == AVAuthorizationStatusRestricted){
  // restricted, normally won't happen
} else if(authStatus == AVAuthorizationStatusNotDetermined){
  // not determined?!
  [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
    if(granted){
      NSLog(@"Granted access to %@", mediaType);
    } else {
      NSLog(@"Not granted access to %@", mediaType);
    }
  }];
} else {
  // impossible, unknown authorization status
}

Link to related question


问:
Horizontal aligment WPF expander header
I want to show my GroupName on left and button "ShowOnly" on the right of header row.
I tried with this code but doesn't works.
Could anyone help me?
Thx

My code :

```<code><Expander IsExpanded="True" >
    <Expander.Header>
        <DockPanel HorizontalAlignment="Stretch">
            <TextBlock Text="{Binding Path=Name}" FontSize="18"></TextBlock>
            <Button Style="{StaticResource ButtonStyle}" Content="Show Only" HorizontalAlignment="Right" Padding="15,0,15,0" Click="Button_Click"></Button>
        </DockPanel>
    </Expander.Header>
    <Expander.Style>
        <Style TargetType="{x:Type Expander}">
            <Setter Property="Background" Value="#f0f0f5"></Setter>
            <Setter Property="TextElement.FontFamily" Value="Arial Nova"/>
        </Style>
    </Expander.Style>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>
</code>```

My ButtonStyle :

```<code><Style x:Key="ButtonStyle" TargetType="Button">

            <Setter Property="Background" Value="#66e0ff" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="FontSize" Value="15" />
            <Setter Property="SnapsToDevicePixels" Value="True" />

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border CornerRadius="4" Background="{TemplateBinding Background}">
                            <Grid>
                                <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="White" />
                                <Setter Property="Foreground" Value="#66e0ff" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

    </Style>
</code>```

I tried also with an DockPanel, but same result.

答:
You can refer to these solutions:

https://joshsmithonwpf.wordpress.com/2007/02/24/stretching-content-in-an-expander-header/

Title: Horizontal aligment WPF expander header

Body:
I want to show my GroupName on left and button "ShowOnly" on the right of header row.
I tried with this code but doesn't works.
Could anyone help me?
Thx

My code :

<Expander IsExpanded="True" >
    <Expander.Header>
        <DockPanel HorizontalAlignment="Stretch">
            <TextBlock Text="{Binding Path=Name}" FontSize="18"></TextBlock>
            <Button Style="{StaticResource ButtonStyle}" Content="Show Only" HorizontalAlignment="Right" Padding="15,0,15,0" Click="Button_Click"></Button>
        </DockPanel>
    </Expander.Header>
    <Expander.Style>

    </Expander.Style>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>

My ButtonStyle :

I tried also with an DockPanel, but same result.


问:
BizTalk WCF returns 413 when using client certificates authentication
I have found the following behavior of WCF in combination with BizTalk:

I have a BizTalk application, in which I published the orchestration as a WCF Service and I changed the binding to allow a maximum received file size of 2 GB. When I submit a request larger than 65KB it works fine with basic authentication and anonymous. As soon as I enable Client certificate authentication I get 413 Request Entity Too Large. Is this a known issue in BizTalk, or is there something I am not doing correctly?

答:
I thought my question was related to BizTalk, but as I soon discovered, it was a general issue with WCF and IIS. I found my answer here:
Getting 413 errors on IIS with concurrent sessions using the same HTTPS client certificate

As it turns out: I needed to add this to my config:

```<code><system.webServer>
    <serverRuntime enabled="true" uploadReadAheadSize="20747520" />
</system.webServer>
</code>```

Don't forget to unlock the  tag:
%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/serverRuntime

Body:
I thought my question was related to BizTalk, but as I soon discovered, it was a general issue with WCF and IIS. I found my answer here:
Getting 413 errors on IIS with concurrent sessions using the same HTTPS client certificate

As it turns out: I needed to add this to my config:

<system.webServer>
    <serverRuntime enabled="true" uploadReadAheadSize="20747520" />
</system.webServer>

Don't forget to unlock the  tag:
%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/serverRuntime


问:
Two different transitions on one element
I'm making a menu with CSS that uses a transition: all .6s when the user has scrolled to an amount. In this menu, I have a ul that I want to use a fade-transition when hovering. This sadly messes everything up when the user scrolls, the repositioning-effect is delayed. Example

Question is; how can I fix this?

The CSS for the transition when scrolling:

```<code>.menu, nav, img {
    transition: all .6s;
    -moz-transition: all .6s;
    -o-transition: all .6s;
    -webkit-transition: all .6s;
}
</code>```

The buttons that I want hovering:

```<code>nav ul li a {
    color: rgba(0,0,0,.7);
    font-family: dinot;
    font-weight: 100;
    text-transform: uppercase;
    text-decoration: none;
    transition: ease-in-out .2s;
}
</code>```

HTML:

```<code><div class="menu">
    <nav>
        <a href=""><img src="style/img/logo.png" alt="logo"></a>
        <ul>
            <li><a href="">Hem</a></li>
            <li><a href="">Om oss</a></li>
            <li><a href="">Tjänster</a></li>
            <li><a href="">projekt</a></li>
            <li><a href="">kontakt</a></li>
        </ul>
    </nav>
</div>
</code>```

答:
You need to specify the transition type for the a tags. Here's the fix:</p>

```<code>nav ul li a {
    color: rgba(0,0,0,.7);
    font-family: dinot;
    font-weight: 100;
    text-transform: uppercase;
    text-decoration: none;
    transition: color ease-in-out .2s;
}
</code>```

Body:
I'm making a menu with CSS that uses a transition: all .6s when the user has scrolled to an amount. In this menu, I have a ul that I want to use a fade-transition when hovering. This sadly messes everything up when the user scrolls, the repositioning-effect is delayed. Example

Question is; how can I fix this?

The CSS for the transition when scrolling:

.menu, nav, img {
    transition: all .6s;
    -moz-transition: all .6s;
    -o-transition: all .6s;
    -webkit-transition: all .6s;
}

The buttons that I want hovering:

nav ul li a {
    color: rgba(0,0,0,.7);
    font-family: dinot;
    font-weight: 100;
    text-transform: uppercase;
    text-decoration: none;
    transition: ease-in-out .2s;
}

HTML:

Hem

Om oss

Tjänster

projekt

kontakt

Body:
You need to specify the transition type for the a tags. Here's the fix:

nav ul li a {
    color: rgba(0,0,0,.7);
    font-family: dinot;
    font-weight: 100;
    text-transform: uppercase;
    text-decoration: none;
    transition: color ease-in-out .2s;
}


问:
Send signals through headphone cable
I've done quite a bit of searching on this but haven't found anything.

I have an idea for an app to control a device, that would need to connect through the headphone cable.

Is it possible to send signals through the headphone socket?

答: Arbitrary data can be played out audio jack using Media Player with a raw resource.  The signal would be limited by the bandwidth of the particular device, for example between 20 Hz and 16 KHz.

Title: Send signals through headphone cable


答:
on the fast way

```<code>SELECT round(SUM(Cena)::NUMERIC,2) AS CelkovaCena, a.Meno, a.Priezvisko,Nazov
FROM Predstavenie
JOIN Autor a ON Predstavenie.ID_Autor = a.ID_Autor
WHERE a.Meno = 'Juraj' AND a.Priezvisko = 'Klein'
GROUP BY a.Meno,a.Priezvisko,Nazov
union all
SELECT round(SUM(Cena)::NUMERIC,2) AS CelkovaCena,null as Meno,null as Nazov
FROM Predstavenie
JOIN Autor a ON Predstavenie.ID_Autor = a.ID_Autor
WHERE a.Meno = 'Juraj' AND a.Priezvisko = 'Klein'
</code>```

but better approach is create new query to calculate total

Title: PostgreSQL Need to make TOTAL ROW

Body:
on the fast way

SELECT round(SUM(Cena)::NUMERIC,2) AS CelkovaCena, a.Meno, a.Priezvisko,Nazov
FROM Predstavenie
JOIN Autor a ON Predstavenie.ID_Autor = a.ID_Autor
WHERE a.Meno = 'Juraj' AND a.Priezvisko = 'Klein'
GROUP BY a.Meno,a.Priezvisko,Nazov
union all
SELECT round(SUM(Cena)::NUMERIC,2) AS CelkovaCena,null as Meno,null as Nazov
FROM Predstavenie
JOIN Autor a ON Predstavenie.ID_Autor = a.ID_Autor
WHERE a.Meno = 'Juraj' AND a.Priezvisko = 'Klein'

but better approach is create new query to calculate total


问:
Count where value is 1
I got this SELECT. And I want to count (or sum?) Yellow and Red card of players (Count Yellow cards only where YellowCard = 1, and Count Red cards only where RedCard = 1).. This SELECT does not work correctly. It count card even if there are 0 or NULL.. How can i correct it? </p>

```<code>SELECT Firstname, Lastname, COUNT(YellowCard) AS Yellow, COUNT(RedCard) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC
</code>```

答:
No, NULLs are not counted. If YellowCard, RedCard take only 0,1,NULL values:

```<code>SELECT Firstname, Lastname, COUNT(nullif(YellowCard,0)) AS Yellow, COUNT(nullif(RedCard,0)) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC
</code>```

Title: Count where value is 1

Body:
I got this SELECT. And I want to count (or sum?) Yellow and Red card of players (Count Yellow cards only where YellowCard = 1, and Count Red cards only where RedCard = 1).. This SELECT does not work correctly. It count card even if there are 0 or NULL.. How can i correct it?

SELECT Firstname, Lastname, COUNT(YellowCard) AS Yellow, COUNT(RedCard) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC

Body:
No, NULLs are not counted. If YellowCard, RedCard take only 0,1,NULL values:

SELECT Firstname, Lastname, COUNT(nullif(YellowCard,0)) AS Yellow, COUNT(nullif(RedCard,0)) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC