问:
jquery datatables custom search form
I'm creating to jquery datatables custom search form.The form contains inputs, checkboxes, selectboxes. But not posting any data. I have tried a few methods but I have not been successful.</p>

```<code>$('#search-form').on('submit', function () {
    var datas = $(this).serializeArray();

    $.each( datas, function( i, data ) {

      table.columns(i).search(data.value).draw();

    });
});
</code>```

答:
Actually you don't have to submit any form, just use button on click. Look at my solution below, click on the filter button to expand the input box, then try type in something and click the search button. The datatable will re-draw after that.

The code is self explanatory, let me know if you need further clarifications.

$("#filter-button").click(function() {
  $(this).toggleClass("active");
  $('#filter-body').slideToggle(100);
});

$("#btnSearch").click(function(e){
  var table = $('#custTable').DataTable();
  var txtCustName = $("#txtCustName").val();
  var txtIntroducer = $("#txtIntroducer").val();
  var txtNRIC = $("#txtNRIC").val();
  var txtNickName = $("#txtNickName").val();
  var txtAddress = $("#txtAddress").val();
  var txtPhone = $("#txtPhone").val();
  var txtRemark = $("#txtRemark").val();

  table
    .columns(1).search(txtCustName)
    .columns(2).search(txtIntroducer)
    .columns(3).search(txtNRIC)
    .columns(4).search(txtNickName)
    .columns(5).search(txtAddress)
    .columns(6).search(txtPhone)
    .columns(7).search(txtRemark)
    .draw();
});

$('#custTable').DataTable({
  responsive: {
    details: {
      type: 'column',
      target: 'tr'
    }
  },
  columnDefs: [
  {
    className: 'control',
    orderable: false,
    targets:   0
  }],
  "dom": 'iti',
  iDisplayLength: -1
});

$('#custTable thead th:first-child').css({'background-image':'none'});

$("#custTable a.cust_id").on('click', function(event){
  event.stopPropagation();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/responsive/2.2.0/js/dataTables.responsive.min.js"></script>
<link href="https://cdn.datatables.net/responsive/2.2.0/css/responsive.dataTables.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="filter-container">
<button class="accordion" id="filter-button" data-toggle="collapse" data-parent="#accordion">Filter Customer</button>

<div id="filter-body" class="panel-collapse collapse">
<div class="panel-body filter-body">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtCustName">Name</label>
<input type="text" id="txtCustName">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtIntroducer">Introducer</label>
<input type="text" id="txtIntroducer">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtNRIC">NRIC</label>
<input type="text" id="txtNRIC">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtNickName">Nick Name</label>
<input type="text" id="txtNickName">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtAddress">Address</label>
<input type="text" id="txtAddress">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtPhone">Phone</label>
<input type="text" id="txtPhone">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtRemark">Remark</label>
<input type="text" id="txtRemark">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="text-align:initial;">
<div class="filter-group">
<button class="btn btn-success" id="btnSearch"><i class="mdi mdi-filter-outline"></i> Search</button>
</div>
</div>
</div>
</div>
</div>

<table id="custTable" class="table table-striped table-bordered table-hover dataTable no-footer dtr-column" cellspacing="0" width="100%" aria-describedby="custTable_info" role="grid" style="width: 100%;"><thead>
<tr role="row"><th class="control sorting_asc" rowspan="1" colspan="1" style="width: 13px; display: none; background-image: none;" aria-label=""></th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 74px;" aria-label="Name: activate to sort column ascending">Name</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 121px;" aria-label="Introducer: activate to sort column ascending">Introducer</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 67px;" aria-label="NRIC: activate to sort column ascending">NRIC</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 124px;" aria-label="Nick Name: activate to sort column ascending">Nick Name</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 101px;" aria-label="Address: activate to sort column ascending">Address</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 79px;" aria-label="Phone: activate to sort column ascending">Phone</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 93px;" aria-label="Remark: activate to sort column ascending">Remark</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 94px;" aria-label="Actions: activate to sort column ascending">Actions</th></tr>
</thead><tbody><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td>abed</td>
<td>abba</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr><tr role="row" class="even">
<td class="control sorting_1" style="display: none;"></td>
<td>accure</td>
<td>abandon</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td>async</td>
<td>acura</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr><tr role="row" class="even">
<td class="control sorting_1" style="display: none;"></td>
<td>bbb</td>
<td>brazil</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td>john</td>
<td>alan</td>
<td>1234</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr><tr role="row" class="even">
<td class="control sorting_1" style="display: none;"></td>
<td>pencil</td>
<td>taylor</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td>steve</td>
<td>alan</td>
<td>123321</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr><tr role="row" class="even">
<td class="control sorting_1" style="display: none;"></td>
<td>taylor</td>
<td>zayn</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td>zack bro</td>
<td>zack</td>
<td>123131</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr></tbody></table></code>```

Title: jquery datatables custom search form

Body:
I'm creating to jquery datatables custom search form.The form contains inputs, checkboxes, selectboxes. But not posting any data. I have tried a few methods but I have not been successful.

$('#search-form').on('submit', function () {
    var datas = $(this).serializeArray();

    $.each( datas, function( i, data ) {

      table.columns(i).search(data.value).draw();

    });
});

Body:
Actually you don't have to submit any form, just use button on click. Look at my solution below, click on the filter button to expand the input box, then try type in something and click the search button. The datatable will re-draw after that.

The code is self explanatory, let me know if you need further clarifications.

$("#filter-button").click(function() {
  $(this).toggleClass("active");
  $('#filter-body').slideToggle(100);
});

$("#btnSearch").click(function(e){
  var table = $('#custTable').DataTable();
  var txtCustName = $("#txtCustName").val();
  var txtIntroducer = $("#txtIntroducer").val();
  var txtNRIC = $("#txtNRIC").val();
  var txtNickName = $("#txtNickName").val();
  var txtAddress = $("#txtAddress").val();
  var txtPhone = $("#txtPhone").val();
  var txtRemark = $("#txtRemark").val();

  table
    .columns(1).search(txtCustName)
    .columns(2).search(txtIntroducer)
    .columns(3).search(txtNRIC)
    .columns(4).search(txtNickName)
    .columns(5).search(txtAddress)
    .columns(6).search(txtPhone)
    .columns(7).search(txtRemark)
    .draw();
});

$('#custTable').DataTable({
  responsive: {
    details: {
      type: 'column',
      target: 'tr'
    }
  },
  columnDefs: [
  {
    className: 'control',
    orderable: false,
    targets:   0
  }],
  "dom": 'iti',
  iDisplayLength: -1
});

$('#custTable thead th:first-child').css({'background-image':'none'});

$("#custTable a.cust_id").on('click', function(event){
  event.stopPropagation();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/responsive/2.2.0/js/dataTables.responsive.min.js"></script>
<link href="https://cdn.datatables.net/responsive/2.2.0/css/responsive.dataTables.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="filter-container">
<button class="accordion" id="filter-button" data-toggle="collapse" data-parent="#accordion">Filter Customer</button>

<div id="filter-body" class="panel-collapse collapse">
<div class="panel-body filter-body">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtCustName">Name</label>
<input type="text" id="txtCustName">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtIntroducer">Introducer</label>
<input type="text" id="txtIntroducer">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtNRIC">NRIC</label>
<input type="text" id="txtNRIC">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtNickName">Nick Name</label>
<input type="text" id="txtNickName">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtAddress">Address</label>
<input type="text" id="txtAddress">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtPhone">Phone</label>
<input type="text" id="txtPhone">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-3" style="text-align:initial;">
<div class="filter-group">
<label for="txtRemark">Remark</label>
<input type="text" id="txtRemark">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="text-align:initial;">
<div class="filter-group">
<button class="btn btn-success" id="btnSearch"><i class="mdi mdi-filter-outline"></i> Search</button>
</div>
</div>
</div>
</div>
</div>

<table id="custTable" class="table table-striped table-bordered table-hover dataTable no-footer dtr-column" cellspacing="0" width="100%" aria-describedby="custTable_info" role="grid" style="width: 100%;"><thead>
<tr role="row"><th class="control sorting_asc" rowspan="1" colspan="1" style="width: 13px; display: none; background-image: none;" aria-label=""></th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 74px;" aria-label="Name: activate to sort column ascending">Name</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 121px;" aria-label="Introducer: activate to sort column ascending">Introducer</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 67px;" aria-label="NRIC: activate to sort column ascending">NRIC</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 124px;" aria-label="Nick Name: activate to sort column ascending">Nick Name</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 101px;" aria-label="Address: activate to sort column ascending">Address</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 79px;" aria-label="Phone: activate to sort column ascending">Phone</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 93px;" aria-label="Remark: activate to sort column ascending">Remark</th><th class="sorting" tabindex="0" aria-controls="custTable" rowspan="1" colspan="1" style="width: 94px;" aria-label="Actions: activate to sort column ascending">Actions</th></tr>
</thead><tbody><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=27">abed</a></td>
<td>abba</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="27"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr><tr role="row" class="even">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=28">accure</a></td>
<td>abandon</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="28"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=29">async</a></td>
<td>acura</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="29"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr><tr role="row" class="even">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=30">bbb</a></td>
<td>brazil</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="30"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=20">john</a></td>
<td>alan</td>
<td>1234</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="20"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr><tr role="row" class="even">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=26">pencil</a></td>
<td>taylor</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="26"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=21">steve</a></td>
<td>alan</td>
<td>123321</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="21"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr><tr role="row" class="even">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=25">taylor</a></td>
<td>zayn</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="25"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr><tr role="row" class="odd">
<td class="control sorting_1" style="display: none;"></td>
<td><a class="cust_id" href="customer-detail.php?id=24">zack bro</a></td>
<td>zack</td>
<td>123131</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="" class="btnDelete" id="24"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></a></td>
</tr></tbody></table>


来源: stackexchange

问:
How to convert XmlNode into XElement?
I have an old XmlNode-based code. but the simplest way to solve my current task is to use XElement and LINQ-to-XML. The only problem is that there is no direct or obvious method for converting a XmlNode to a XElement in .NET Framework.

So for starters, I want to implement a method that receives a XmlNode instance and converts it to a XElement instance.

How can I implement this conversion?

答:
There actually is a very straightforward way to convert an XNode to an XElement:

```<code>static XElement ToXElement( XNode node)
{
    return node as XElement; // returns null if node is not an XElement
}
</code>```

If you are 100% certain the node is an XElement (or you are prepared to deal with the exception if it is not, then you can simply cast: (XElement)node.

ContentLicense: CC BY-SA 3.0

Title: How to convert XmlNode into XElement?

Body:
There actually is a very straightforward way to convert an XNode to an XElement:

static XElement ToXElement( XNode node)
{
    return node as XElement; // returns null if node is not an XElement
}

If you are 100% certain the node is an XElement (or you are prepared to deal with the exception if it is not, then you can simply cast: (XElement)node.


问:
Populating dictionary values from a list
I'm trying to construct a dictionary in python. Code looks like this:

```<code>dicti = {}
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9]
dicti = dicti.fromkeys(keys)

values = [2, 3, 4, 5, 6, 7, 8, 9]
</code>```

How can I populate values of dictionary using a list? Is there some built in function?

The result should be like this:

```<code>dicti = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9}
</code>```

答:
this will work but the list have to be the same size (drop the 9 in the keys list)   </p>

```<code>keys = [1, 2, 3, 4, 5, 6, 7, 8]
values = [2, 3, 4, 5, 6, 7, 8, 9]
dicti = {}

for x in range(len(keys)):
     dicti[keys[x]] = values[x]
</code>```

Body:
I'm trying to construct a dictionary in python. Code looks like this:

dicti = {}
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9]
dicti = dicti.fromkeys(keys)

values = [2, 3, 4, 5, 6, 7, 8, 9]

How can I populate values of dictionary using a list? Is there some built in function?

The result should be like this:

dicti = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9}

Body:
this will work but the list have to be the same size (drop the 9 in the keys list)

keys = [1, 2, 3, 4, 5, 6, 7, 8]
values = [2, 3, 4, 5, 6, 7, 8, 9]
dicti = {}

for x in range(len(keys)):
     dicti[keys[x]] = values[x]


问:
CSS div height fill remaing space and scroll if reach max height of screen
I have searched everywhere on the web for this but i couldn't find anyone that really fits me or even work. The answers that I found are very old and/or are not 100% what I am looking for so I hope if anyone can help me with this.

I use bootstrap 4 in my application so if it can be done with bootstrap then yeay but pure css is ok as well.

What I try to do is having 4 div side by side

example:

```<code><div class="row">
    <div class="col">
        <h1>Item 1</h1>
    </div>

    <div class="col">
        <h1>Item 2</h1>
    </div>
    <div class="col">
        <h1>Item 2</h1>
    </div>
    <div class="col">
        <h1>Item 2</h1>
    </div>
</div>
</code>```

This works because of bootstrap 4 but now I also want the div height will extend till the bottom of the screen  and if the content of that div is longer then the screen height, then it should scroll (inside the div).

I was thinking about flex boxes but I couldn't get it to work.

答:
You might want to do this in jQuery.
Explanation:

If the height of the div is longer than height of the document, show a scroll in the div

Code:

```<code>$(document).ready(fuction(){

var docHeight = $(document).height();

var divHeight = $('.the-four-divs').height();
If(divHeight > docHeight){
$('.the-four-divs').css('overflow-x', 'scroll');

}

});
</code>```

`

Hop it helps sir.

Body:
I have searched everywhere on the web for this but i couldn't find anyone that really fits me or even work. The answers that I found are very old and/or are not 100% what I am looking for so I hope if anyone can help me with this.

I use bootstrap 4 in my application so if it can be done with bootstrap then yeay but pure css is ok as well.

What I try to do is having 4 div side by side

example:

Item 1

Item 2

Item 2

Item 2

This works because of bootstrap 4 but now I also want the div height will extend till the bottom of the screen  and if the content of that div is longer then the screen height, then it should scroll (inside the div).

I was thinking about flex boxes but I couldn't get it to work.

Body:
You might want to do this in jQuery.
Explanation:

If the height of the div is longer than height of the document, show a scroll in the div

Code:

$(document).ready(fuction(){

var docHeight = $(document).height();

var divHeight = $('.the-four-divs').height();
If(divHeight > docHeight){
$('.the-four-divs').css('overflow-x', 'scroll');

}

});

`

Hop it helps sir.


问:
Convert integers inside a list into strings and then a date in python 3.x
i've just started studying python in college and i have a problem with this exercise:
basically i have to take a list of integers, like for example [10,2,2013,11,2,2014,5,23,2015], turn the necessary elements to form a date into a string, like ['1022013',1122014,5232015] and then put a / between the strings so i have this ['10/2/2013', '11/22/2014','05/23/2015']. It needs to be a function, and the length of the list is assumed to be a multiple of 3. How do i go about doing this?
I wrote this code to start:

```<code>def convert(lst):
     ...:     for element in lst:
     ...:      result = str(element)
     ...:      return result
     ...:
</code>```

but from a list [1,2,3] only returns me '1'.

答:
Use datetime to extract the date and and strftime to format it:

```<code>from datetime import datetime

dates = [10,2,2013,11,2,2014,5,23,2015]
for i in range(0, len(dates), 3):
    d = datetime(dates[i+2], dates[i], dates[i+1])
    print(d.strftime("%m/%d/%y"))
</code>```

OUTPUT

```<code>10/02/13
11/02/14
05/23/15
</code>```

Body:
i've just started studying python in college and i have a problem with this exercise:
basically i have to take a list of integers, like for example [10,2,2013,11,2,2014,5,23,2015], turn the necessary elements to form a date into a string, like ['1022013',1122014,5232015] and then put a / between the strings so i have this ['10/2/2013', '11/22/2014','05/23/2015']. It needs to be a function, and the length of the list is assumed to be a multiple of 3. How do i go about doing this?
I wrote this code to start:

def convert(lst):
     ...:     for element in lst:
     ...:      result = str(element)
     ...:      return result
     ...:

but from a list [1,2,3] only returns me '1'.

Body:
Use datetime to extract the date and and strftime to format it:

from datetime import datetime

dates = [10,2,2013,11,2,2014,5,23,2015]
for i in range(0, len(dates), 3):
    d = datetime(dates[i+2], dates[i], dates[i+1])
    print(d.strftime("%m/%d/%y"))

OUTPUT

10/02/13
11/02/14
05/23/15


问:
MSI installer VS 2008
I want to read the users directory which user chooses to install my MSI, so that i can write the path to the registry which is required for my application to run. I want to know how to do this, if using any scripts then kindly let me know the script as i am totally new here for this installer.</p>

答: You can put [TARGETDIR] ( or the name of any other directory property inside of [] ) in the registry value and the value of TARGETDIR will be written to the registry. </p>

ContentLicense: CC BY-SA 2.5

Title: MSI installer VS 2008


问:
Selenium Chrome WebDriver is opening Setting as default tab asking to reset the setting
Selenium Chrome WebDriver is opening Setting as default tab asking to reset the setting.

答: I have version 62.0.3202.94 and I've tried updating my chrome driver using webdriver-manager update --versions.chrome 2.33 but when i run my protractor tests it still keeps opening tabs for chrome:settings/help during the tests even if I keep closing them. </p>


问:
Add content before and after table (jsPDF autotable)
i have a question to jsPDF autotable.

My Code:

```<code>    $('#printBtn').on('click', function() {
    var pdf = new jsPDF('p', 'pt', 'a4');
    var res = pdf.autoTableHtmlToJson(document.getElementById("tablePrint"));

    pdf.autoTable(res.columns, res.data, {
        theme : 'plain',
        styles: {
            fontSize: 12
        },
        showHeader: 'never',
        createdCell: function(cell, data) {
            var tdElement = cell.raw;
            if (tdElement.classList.contains('hrow')) {
                cell.styles.fontStyle = 'bold';
            }
        }
    });

    pdf.save("test.pdf");
});
</code>```

I want add Text before and after the Table from a div.
I have found this Code Snippet in jsPDF autotable examples:

```<code>    var before = "text before";
    pdf.text(before, 14, 30);
</code>```

This code works good. I have insert that before pdf.autoTable(...});.
But i dont know what the number 14 and 30 for?

Then i have the code insert after the pdf.autoTable function call and the Text printed on the last page of pdf but on the top of the page, not on the end, why?

Sorry for my bad englisch.
Thanks for help.

答:
Here's my stab at an answer:

So this is your Autotable's function call:

```<code>var pdf = new jsPDF('p', 'pt', 'a4');
</code>```

Since jsPDF Autotables is based on jsPDF, you'll have to go here:

pt is a unit of measurement called points, so 14 and 30 are points. At the first position, 14, moves elements left and right.  The second position, 30, moves elements down and up.  I'm guessing they're like pixels(px).  Seems like you have to move your text to your desired locations by using points.

Body:
i have a question to jsPDF autotable.

My Code:

    $('#printBtn').on('click', function() {
    var pdf = new jsPDF('p', 'pt', 'a4');
    var res = pdf.autoTableHtmlToJson(document.getElementById("tablePrint"));

    pdf.autoTable(res.columns, res.data, {
        theme : 'plain',
        styles: {
            fontSize: 12
        },
        showHeader: 'never',
        createdCell: function(cell, data) {
            var tdElement = cell.raw;
            if (tdElement.classList.contains('hrow')) {
                cell.styles.fontStyle = 'bold';
            }
        }
    });

    pdf.save("test.pdf");
});

I want add Text before and after the Table from a div.
I have found this Code Snippet in jsPDF autotable examples:

    var before = "text before";
    pdf.text(before, 14, 30);

This code works good. I have insert that before pdf.autoTable(...});.
But i dont know what the number 14 and 30 for?

Then i have the code insert after the pdf.autoTable function call and the Text printed on the last page of pdf but on the top of the page, not on the end, why?

Sorry for my bad englisch.
Thanks for help.

Body:
Here's my stab at an answer:

So this is your Autotable's function call:

var pdf = new jsPDF('p', 'pt', 'a4');

Since jsPDF Autotables is based on jsPDF, you'll have to go here:

pt is a unit of measurement called points, so 14 and 30 are points. At the first position, 14, moves elements left and right.  The second position, 30, moves elements down and up.  I'm guessing they're like pixels(px).  Seems like you have to move your text to your desired locations by using points.


问:
CosmosDB - DocumentDB - Bulk insert without saturating collection RU
I am investigating using Azure CosmosDB for an application that would require high read throughput, and the ability to scale. 99% of the activity would be reads, but occasionally we would need to insert somewhere from just a few documents to potentially a batch of a few million.

I have created a collection to test with and provisioned 2500 RU/sec. However I am running into issues with inserting even just 120 small (500 bytes) documents (I get "request rate is large" error).

How can I possibly use document db in any useful way, if any time I want to insert some documents it will use all my RU and prevent anyone from reading it?

Yes, I can increase the RUs provisioned, but if I only need 2500 for reads, I don't want to have to pay for 10000 just for the occasional insert.

Reads need to be as fast as possible, ideally in the "single-digit-millisecond" range that Microsoft advertises. The inserts do not need to be as fast as possible, but faster is better.

I have tried using a stored procedure which I have seen suggested, but that also fails to insert all reliably, I have tried creating my own bulk insert method using multiple threads as suggested in the answer here but this produces very slow results and also often errors for at least some documents, and seems to average a RU rate of well below what I've provisioned.

I feel like I must be missing something, do I have to massively over provision RU just for writes? Is there some kind of functionality built in to limit the RU use for inserting? How is it possible to insert hundreds of thousands of documents in a reasonable amount of time, and without making the collection unusuable?

答:
If you can't improve the cost of your inserts, you might go the other way and slow down the process to that your overall performance is not impacted. If you look at the offical performance benchmarking sample (which inserts documents), you could take this as an idea on how to limit the RU/s you require for inserts. It shows a lot of parameters that can be tweaked to improve performance, but those can obviously also be used to tailor your RU/s consumption to a certain level.

The answer by KranthiKiran pretty much sums up all other things I can think of.


问:
Retrain mxnet model in R
I have created a neural network with mxnet. Now I want to train this model iteratively on new data points. After I simulated a new data point I want to make a new gradient descent update on this model. I do not want to save the model to an external file and load it again.

I have written the following code, but the weights do not change after a new training step. I also get NaN as a training error.

```<code>library(mxnet)
data <- mx.symbol.Variable("data")
fc1 <- mx.symbol.FullyConnected(data, num_hidden = 2, no.bias = TRUE)
lro <- mx.symbol.LinearRegressionOutput(fc1)

# first data observation
train.x = matrix(0, ncol = 3)
train.y = matrix(0, nrow = 2)

# first training step
model = mx.model.FeedForward.create(lro,
  X = train.x, y = train.y, initializer = mx.init.uniform(0.001),
  num.round = 1, array.batch.size = 1, array.layout = "rowmajor",
  learning.rate = 0.1, eval.metric = mx.metric.mae)
print(model$arg.params)

# second data observation
train.x = matrix(0, ncol = 3)
train.x[1] = 1
train.y = matrix(0, nrow = 2)
train.y[1] = -33

# retrain model on new data
# pass on params of old model
model = mx.model.FeedForward.create(symbol = model$symbol,
  arg.params = model$arg.params, aux.params = model$aux.params,
  X = train.x, y = train.y, num.round = 1,
  array.batch.size = 1, array.layout = "rowmajor",
  learning.rate = 0.1, eval.metric = mx.metric.mae)
# weights do not change
print(model$arg.params)
</code>```

答: did you try to call mx.model.FeedForward.create only once and then use the fit function for incremental training?

Title: Retrain mxnet model in R

Body:
I have created a neural network with mxnet. Now I want to train this model iteratively on new data points. After I simulated a new data point I want to make a new gradient descent update on this model. I do not want to save the model to an external file and load it again.

I have written the following code, but the weights do not change after a new training step. I also get NaN as a training error.

library(mxnet)
data <- mx.symbol.Variable("data")
fc1 <- mx.symbol.FullyConnected(data, num_hidden = 2, no.bias = TRUE)
lro <- mx.symbol.LinearRegressionOutput(fc1)

# first data observation
train.x = matrix(0, ncol = 3)
train.y = matrix(0, nrow = 2)

# first training step
model = mx.model.FeedForward.create(lro,
  X = train.x, y = train.y, initializer = mx.init.uniform(0.001),
  num.round = 1, array.batch.size = 1, array.layout = "rowmajor",
  learning.rate = 0.1, eval.metric = mx.metric.mae)
print(model$arg.params)

# second data observation
train.x = matrix(0, ncol = 3)
train.x[1] = 1
train.y = matrix(0, nrow = 2)
train.y[1] = -33

# retrain model on new data
# pass on params of old model
model = mx.model.FeedForward.create(symbol = model$symbol,
  arg.params = model$arg.params, aux.params = model$aux.params,
  X = train.x, y = train.y, num.round = 1,
  array.batch.size = 1, array.layout = "rowmajor",
  learning.rate = 0.1, eval.metric = mx.metric.mae)
# weights do not change
print(model$arg.params)


问:
Remote Powershell scripting and Jenkins not working
I am having an issue running a remote script using Jenkins. I have installed the PowerShell plug-in and can run PowerShell scripts on the local build server, but when I try to run it on a remote server, it fails all the time. I can run the same script outside of Jenkins locally and remotely and it works just fine. My assumption is that there is a security setting I am missing but for the life of me, I can not find it.

Any insight/help would be greatly appreciate it.

The code below runs using PowerShell on the server but not through Jenkins:

```<code>$ErrorActionPreference = 'Stop'

# Create a PSCredential Object using the "User" and "Password" parameters
that you passed to the job
$SecurePassword = 'xxxxxxx' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'ci-user', $SecurePassword

# Invoke a command on the remote machine.
# It depends on the type of job you are executing on the remote machine as
to if you want to use "-ErrorAction Stop" on your Invoke-Command.
Invoke-Command -ComputerName xxx.xx.xx.xxx -Credential $cred -ScriptBlock {
    # Restart the W32Time service
    Restart-Service -Name W32Time
}
</code>```

The error below is what I get when I run it in Jenkins. I am using the same username and password when I run it outside of Jenkins and works:

```<code>Connecting to remote server xxx.xx.xx.xxx failed with the
following error message : WinRM cannot process the request. The following
error with errorcode 0x8009030d occurred while using Negotiate authentication:
A specified logon session does not exist. It may already have been terminated.

 Possible causes are:
  -The user name or password specified are invalid.
  -Kerberos is used when no authentication method and no user name are
specified.
  -Kerberos accepts domain user names, but not local user names.
  -The Service Principal Name (SPN) for the remote computer name and port does
not exist.
  -The client and remote computers are in different domains and there is no
trust between the two domains.
 After checking for the above issues, try the following:
  -Check the Event Viewer for events related to authentication.
  -Change the authentication method; add the destination computer to the WinRM
TrustedHosts configuration setting or use HTTPS transport.
 Note that computers in the TrustedHosts list might not be authenticated.
   -For more information about WinRM configuration, run the following command:
winrm help config. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\Windows\TEMP\jenkins3589460126620702793.ps1:12 char:1
+ Invoke-Command -ComputerName xxx.xx.xx.xxx -Credential $cred -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (xxx.xx.xx.xxx:String) [], PSRemoting
   TransportException
    + FullyQualifiedErrorId : 1312,PSSessionStateBroken
</code>```

答:
I found the error of my ways but hopefully this answer will help anyone else that encounters it.

The problem was that the user I am using is a local user and it needs to be treated as a workgroup user. So instead of ci-user, I needed to pass it as \ci-user. Once I did this, it works like a charm.

Thank you for all your input.

Body:
I am having an issue running a remote script using Jenkins. I have installed the PowerShell plug-in and can run PowerShell scripts on the local build server, but when I try to run it on a remote server, it fails all the time. I can run the same script outside of Jenkins locally and remotely and it works just fine. My assumption is that there is a security setting I am missing but for the life of me, I can not find it.

Any insight/help would be greatly appreciate it.

The code below runs using PowerShell on the server but not through Jenkins:

$ErrorActionPreference = 'Stop'

# Create a PSCredential Object using the "User" and "Password" parameters
that you passed to the job
$SecurePassword = 'xxxxxxx' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'ci-user', $SecurePassword

# Invoke a command on the remote machine.
# It depends on the type of job you are executing on the remote machine as
to if you want to use "-ErrorAction Stop" on your Invoke-Command.
Invoke-Command -ComputerName xxx.xx.xx.xxx -Credential $cred -ScriptBlock {
    # Restart the W32Time service
    Restart-Service -Name W32Time
}

The error below is what I get when I run it in Jenkins. I am using the same username and password when I run it outside of Jenkins and works:

Connecting to remote server xxx.xx.xx.xxx failed with the
following error message : WinRM cannot process the request. The following
error with errorcode 0x8009030d occurred while using Negotiate authentication:
A specified logon session does not exist. It may already have been terminated.

 Possible causes are:
  -The user name or password specified are invalid.
  -Kerberos is used when no authentication method and no user name are
specified.
  -Kerberos accepts domain user names, but not local user names.
  -The Service Principal Name (SPN) for the remote computer name and port does
not exist.
  -The client and remote computers are in different domains and there is no
trust between the two domains.
 After checking for the above issues, try the following:
  -Check the Event Viewer for events related to authentication.
  -Change the authentication method; add the destination computer to the WinRM
TrustedHosts configuration setting or use HTTPS transport.
 Note that computers in the TrustedHosts list might not be authenticated.
   -For more information about WinRM configuration, run the following command:
winrm help config. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\Windows\TEMP\jenkins3589460126620702793.ps1:12 char:1
+ Invoke-Command -ComputerName xxx.xx.xx.xxx -Credential $cred -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (xxx.xx.xx.xxx:String) [], PSRemoting
   TransportException
    + FullyQualifiedErrorId : 1312,PSSessionStateBroken


问:
Rmarkdown calls different Python than bash
I am trying to call a Python script from within Rmarkdown. The script relies on Biopython but this library is not found if called from rmarkdown

from Rmarkdown

```<code>```{r, engine = "bash"}
python --version
```
</code>```

Python 2.7.10

from the bash shell

```<code>python --version
</code>```

Python 2.7.12

How can I control which version is called?

(I recall having installed a different python version with homebrew which might have led to this mess...)

答:
You need to set the engine.path variable in your chunk. If you are using Anaconda, it might look like this...

```<code>```{python, engine.path="~/anaconda3/bin/python"}
your code here...
```
</code>```

When you are running the correct python in your terminal you can run...

```<code>import sys
print(sys.executable)
</code>```

This should point you to the location of the python executable you should pass as an argument to engine.path in RMarkdown/knitr.

Body:
I am trying to call a Python script from within Rmarkdown. The script relies on Biopython but this library is not found if called from rmarkdown

from Rmarkdown

```{r, engine = "bash"}
python --version
```

Python 2.7.10

from the bash shell

python --version

Python 2.7.12

How can I control which version is called?

(I recall having installed a different python version with homebrew which might have led to this mess...)

Body:
You need to set the engine.path variable in your chunk. If you are using Anaconda, it might look like this...

```{python, engine.path="~/anaconda3/bin/python"}
your code here...
```

When you are running the correct python in your terminal you can run...

import sys
print(sys.executable)

This should point you to the location of the python executable you should pass as an argument to engine.path in RMarkdown/knitr.


问:
Insert tables in PHP
I have two tables, Order and OrderDetails.

```<code>Order Table
 OrderID
 Order_Details_Id
 Date
 Cust_Id

Order Details
 Order_Details_Id
 prod_name
 prod_amt
 OrderID
</code>```

Basically i want to insert several order details in one order table. My issue is i am not quite sure how to set OrderID in the Order table to the OrderID in Order Details in PHP. I have made an attempt at it with no luck, this is what i have so far :

```<code>$order = "INSERT INTO Order (orderID, cust_id, date)
        VALUES ('$cust_id, '23/11/2017')";
$DBcon->exec($order);

foreach ($prodname as $prodname) {

    foreach ($prodamount as $prodamount) {

        $od = "INSERT INTO Order_Details (OrderDetails_id, prod_name, prod_amt,orderID)
        VALUES ('$prodname' , '$prodamount',orderID(?) )";

    $DBcon->exec($od);

    }
}
</code>```

Any help would be greatly appreciated, i am relatively new to using PHP and SQL!

答:
Use mysqli::$insert_id to get last inserted id

```<code>$DBcon->exec($order);
$orderID = $DBcon->insert_id;
</code>```

Now use this varibale instead of orderID(?) in your Second INSERTcode.

Title: Insert tables in PHP

Body:
I have two tables, Order and OrderDetails.

Order Table
 OrderID
 Order_Details_Id
 Date
 Cust_Id

Order Details
 Order_Details_Id
 prod_name
 prod_amt
 OrderID

Basically i want to insert several order details in one order table. My issue is i am not quite sure how to set OrderID in the Order table to the OrderID in Order Details in PHP. I have made an attempt at it with no luck, this is what i have so far :

$order = "INSERT INTO Order (orderID, cust_id, date)
        VALUES ('$cust_id, '23/11/2017')";
$DBcon->exec($order);

foreach ($prodname as $prodname) {

    foreach ($prodamount as $prodamount) {

        $od = "INSERT INTO Order_Details (OrderDetails_id, prod_name, prod_amt,orderID)
        VALUES ('$prodname' , '$prodamount',orderID(?) )";

    $DBcon->exec($od);

    }
}

Any help would be greatly appreciated, i am relatively new to using PHP and SQL!

Body:
Use mysqli::$insert_id to get last inserted id

$DBcon->exec($order);
$orderID = $DBcon->insert_id;

Now use this varibale instead of orderID(?) in your Second INSERTcode.


问:
Calculate average of a list of datetime objects
I would like to calculate the mean time of a list of datetime objects. Here is a piece of code for testing:

```<code>import datetime as dt

test_dates = []
d = dt.datetime(2015,1,1,10) # startdate
while d < dt.datetime(2015,1,1,17): # enddate
    test_dates.append(d)
    d += dt.timedelta(hours=1)
</code>```

For these test_dates the result would be: avg_time = datetime.datetime(2015,1,1,13,0)

How do I implement this? Do I have to convert to timestamps before?
Any help is very much appreciated.

答:
I would convert to timestamps:</p>

```<code>dt.datetime.fromtimestamp(sum(d.timestamp() for d in test_dates)/len(test_dates))
</code>```

Body:
I would like to calculate the mean time of a list of datetime objects. Here is a piece of code for testing:

import datetime as dt

test_dates = []
d = dt.datetime(2015,1,1,10) # startdate
while d < dt.datetime(2015,1,1,17): # enddate
    test_dates.append(d)
    d += dt.timedelta(hours=1)

For these test_dates the result would be: avg_time = datetime.datetime(2015,1,1,13,0)

How do I implement this? Do I have to convert to timestamps before?
Any help is very much appreciated.

Body:
I would convert to timestamps:

dt.datetime.fromtimestamp(sum(d.timestamp() for d in test_dates)/len(test_dates))


问:
Using lodash to filter an object property
I'm trying to use the _.filter property to filter an array.  I'd like to use the matchesProperty shorthand, but don't want to do a straight comparison.

eg. This works:
    .each(.filter(this.across, ['len', 3]), dostuff);

but if I want to filter values less than 9, I need to use a function:
    .each(.filter(this.across, function (o) {return o.len<9}), dostuff);

Is there a neater way to do this?

答:
I don't know what dostuff and this.across are, but let's assume you have an array of objects with property len and you want to filter values less than 9.

You can do this in a point free functional style, with just lodash, but it's going to look more convoluted than if you just use an arrow function. The matchesProperty shorthand only works for equality comparison, so can't be used in this case.

See both options below:

const arr = [
  { len: 2 }, // keep
  { len: 5 }, // keep
  { len: 9 },
  { len: 22 },
  { len: 8 } // keep
]

// point free functional style
const filtered = _.filter(arr, _.flow(_.property('len'), _.partial(_.gt, 9)))

// with arrow function
const filtered2 = _.filter(arr, o => o.len < 9)

console.log(filtered)
console.log(filtered2)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Body:
I don't know what dostuff and this.across are, but let's assume you have an array of objects with property len and you want to filter values less than 9.

You can do this in a point free functional style, with just lodash, but it's going to look more convoluted than if you just use an arrow function. The matchesProperty shorthand only works for equality comparison, so can't be used in this case.

See both options below:

const arr = [
  { len: 2 }, // keep
  { len: 5 }, // keep
  { len: 9 },
  { len: 22 },
  { len: 8 } // keep
]

// point free functional style
const filtered = _.filter(arr, _.flow(_.property('len'), _.partial(_.gt, 9)))

// with arrow function
const filtered2 = _.filter(arr, o => o.len < 9)

console.log(filtered)
console.log(filtered2)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
Saving Git SHA1 when building with Hudson similar to the CVS_BRANCH tag for CVS
We have migrated from CVS to Git.  Our Hudson build script used to save the value of the CVS_BRANCH environment variable in the generated build along with the Hudson BUILD_ID to allow for later investigation.

I cannot figure out how Hudson (or the Git plugin) presents the Git SHA1 name of the current commit to the ant script, as I cannot locate any definite source saying where I should look.

I'd prefer not to invoke git to get it if it is present in the environment, but can do if that is necessary.

What have I missed?

答: It turned out that jGit supports the "rev-parse HEAD" command, which in combination with the <java jar="jgit...jar" fork="true" args="rev-parse HEAD" outputproperty="git.SHA1" /> did exactly what I wanted, namely got the SHA1 into an ant property so I could use it later.


问:
How to extract file names in a loop into a character array?
I have a code like below. I want to generate an array with all the file names and combine with the data that I collected from each file.

```<code>  DataCC = dir('*-CC.xls'); %select the file type
  MeanAreaCC=[];
  PlateNameCC=[];
  for w = 1: numel(DataCC)
      basefilenamedata=DataCC(w).name; %extract the file name
      T=readtable(basefilenamedata); %read table in
      PlateNameCC=[PlateNameCC basefilenamedata]; %generate the file name array
      MeanAreaCC = [MeanAreaCC mean(T.Area)]; %generate the data array
  end

  x=array2table([PlateNameCC, transpose(MeanAreaCC)],'VariableNames',{'Iso-Condi-Rep','MeanAreaCC'}); %combine two arrays just generated
  writetable(x,fullfile(DataFolder,'DataSummary.xls'),'Sheet',1,'Range','A1');
</code>```

But my code didn't work, as the PlateNameCC is generated as one character but not an array. This came to an error complaining different array size, when I combine PlateNameCC with MeanAreaCC. Could somebody check it for me? Thank you!

答:
There are a couple things wrong here.

First, PlateNameCC = [PlateNameCC basefilenamedata]; is going to create one long string of garbage.

For example:

```<code>fnames = dir('*.m')
namelist = [];
for ii = 1:numel(fnames)
    namelist = [namelist fnames(ii).name]
end
</code>```

Gives me:

```<code>namelist =

    'SOcode.mcallbacksclass.mtestcode.m'
</code>```

You want to use a string array or a cell array:

```<code>fnames = dir('*.m');
namelist1 = string({fnames.name});
namelist2 = {fnames.name};
</code>```

Which returns:

```<code>namelist1 =

  1×3 string array

    "SOcode.m"    "callbacksclass.m"    "testcode.m"

namelist2 =

  1×3 cell array

    {'SOcode.m'}    {'callbacksclass.m'}    {'testcode.m'}
</code>```

Second, there's no point trying to concatenate two (very) unlike arrays to create a table when you can just use the table constructor itself:

```<code>fnames = dir('*.m');
namelist = string({fnames.name});
data = [1, 2, 3];

T = table(namelist.', data.');
</code>```

Which gives:

```<code>T =

  3×2 table

           Var1           Var2
    __________________    ____

    "SOcode.m"            1
    "callbacksclass.m"    2
    "testcode.m"          3
</code>```

Body:
I have a code like below. I want to generate an array with all the file names and combine with the data that I collected from each file.

  DataCC = dir('*-CC.xls'); %select the file type
  MeanAreaCC=[];
  PlateNameCC=[];
  for w = 1: numel(DataCC)
      basefilenamedata=DataCC(w).name; %extract the file name
      T=readtable(basefilenamedata); %read table in
      PlateNameCC=[PlateNameCC basefilenamedata]; %generate the file name array
      MeanAreaCC = [MeanAreaCC mean(T.Area)]; %generate the data array
  end

  x=array2table([PlateNameCC, transpose(MeanAreaCC)],'VariableNames',{'Iso-Condi-Rep','MeanAreaCC'}); %combine two arrays just generated
  writetable(x,fullfile(DataFolder,'DataSummary.xls'),'Sheet',1,'Range','A1');

But my code didn't work, as the PlateNameCC is generated as one character but not an array. This came to an error complaining different array size, when I combine PlateNameCC with MeanAreaCC. Could somebody check it for me? Thank you!

Body:
There are a couple things wrong here.

First, PlateNameCC = [PlateNameCC basefilenamedata]; is going to create one long string of garbage.

For example:

fnames = dir('*.m')
namelist = [];
for ii = 1:numel(fnames)
    namelist = [namelist fnames(ii).name]
end

Gives me:

namelist =

    'SOcode.mcallbacksclass.mtestcode.m'

You want to use a string array or a cell array:

fnames = dir('*.m');
namelist1 = string({fnames.name});
namelist2 = {fnames.name};

Which returns:

namelist1 =

  1×3 string array

    "SOcode.m"    "callbacksclass.m"    "testcode.m"

namelist2 =

  1×3 cell array

    {'SOcode.m'}    {'callbacksclass.m'}    {'testcode.m'}

Second, there's no point trying to concatenate two (very) unlike arrays to create a table when you can just use the table constructor itself:

fnames = dir('*.m');
namelist = string({fnames.name});
data = [1, 2, 3];

T = table(namelist.', data.');

Which gives:

T =

  3×2 table

           Var1           Var2
    __________________    ____

    "SOcode.m"            1
    "callbacksclass.m"    2
    "testcode.m"          3


问:
'props' of undefined inside map closure
I get TypeError: Cannot read property 'props' of undefined. I need to my Li component to receive props. I'm using styled-component by the way.

```<code>const Li = styled.li`
  border-top: 0 none;
`;

class Popular extends Component {
    render() {
        var languages = ['All', 'Javascript', 'Java', 'Python'];
        return (
            <ul className='list-group'>
                {languages.map(function(lang){
                    return (
                        <Li className={`list-group-item p-2 ${this.props.className}`}>
                            {lang}
                        </Li>
                    )
                })}
            </ul>
        );
    }
}

export default Popular;
</code>```

答:
You need to bind the callback of languages.map to the popular class. You can either use arrow function like this

```<code>{languages.map((lang) => {
</code>```

or just pass this as the second argument of map function like this

```<code>{languages.map(function(lang){
       ...
}, this)}
</code>```

or you can bind it using bind function like this

```<code>{languages.map((function(lang){
       ...
}).bind(this))}
</code>```

Title: 'props' of undefined inside map closure

Body:
I get TypeError: Cannot read property 'props' of undefined. I need to my Li component to receive props. I'm using styled-component by the way.

const Li = styled.li`
  border-top: 0 none;
`;

class Popular extends Component {
    render() {
        var languages = ['All', 'Javascript', 'Java', 'Python'];
        return (

                {languages.map(function(lang){
                    return (
                        <Li className={`list-group-item p-2 ${this.props.className}`}>
                            {lang}

                    )
                })}

        );
    }
}

export default Popular;

Body:
You need to bind the callback of languages.map to the popular class. You can either use arrow function like this

{languages.map((lang) => {

or just pass this as the second argument of map function like this

{languages.map(function(lang){
       ...
}, this)}

or you can bind it using bind function like this

{languages.map((function(lang){
       ...
}).bind(this))}


答:
To split your list into size 3 chunks you use a range with a step of 3

```<code>for i in range(0, len(l), 3):
    print(l[i:i+3])
</code>```

And joining the pieces with / is as simple as

```<code>'/'.join([str(x) for x in l[i:i+3]])
</code>```

Throwing it all together into a function:

```<code>def make_times(l):
    results = []
    for i in range(0, len(l), 3):
        results.append('/'.join([str(x) for x in l[i:i+3]]))
    return results
</code>```

Title: Convert integers inside a list into strings and then a date in python 3.x

Body:
i've just started studying python in college and i have a problem with this exercise:
basically i have to take a list of integers, like for example [10,2,2013,11,2,2014,5,23,2015], turn the necessary elements to form a date into a string, like ['1022013',1122014,5232015] and then put a / between the strings so i have this ['10/2/2013', '11/22/2014','05/23/2015']. It needs to be a function, and the length of the list is assumed to be a multiple of 3. How do i go about doing this?
I wrote this code to start:

def convert(lst):
     ...:     for element in lst:
     ...:      result = str(element)
     ...:      return result
     ...:

but from a list [1,2,3] only returns me '1'.

Body:
To split your list into size 3 chunks you use a range with a step of 3

for i in range(0, len(l), 3):
    print(l[i:i+3])

And joining the pieces with / is as simple as

'/'.join([str(x) for x in l[i:i+3]])

Throwing it all together into a function:

def make_times(l):
    results = []
    for i in range(0, len(l), 3):
        results.append('/'.join([str(x) for x in l[i:i+3]]))
    return results


问:
Spliting Python string interpolation onto multiple lines
I've got a logging statement, something like:

```<code>get_logger().info(
    'Logger logging %s because we need to log it.' % response['foo']['bar']
)
</code>```

With indentation it comes out well over 80 rows. If I could split it around the %, it would be fine.

How can I split this into multiple lines. (ideally without just putting response['foo']['bar'] into a variable)

答:
It might be worth noting that, for logging,

```<code>get_logger().info(
    'Logger logging %s because we need to log it.'
    % response['foo']['bar']
)
</code>```

is the same as:

```<code>get_logger().info(
    'Logger logging %s because we need to log it.',
    response['foo']['bar']
)
</code>```

since the debug(), info(), etc . methods interpret *args as to be used for string formatting the message.

https://docs.python.org/2/library/logging.html#logging.Logger.debug

In general for long strings, ones that ought to wrap around column 80, use parentheses, taking advantage of python's built-in string joining:

```<code>deeplyNested = True
thing = 'feedback'
class Contrived(object):
    def __init__(self):
        if deeplyNested:
            logger.info(
                ("Sometimes there's a lot to say in %s and you need to write"
                 " longer messages than what nicely fits in the 80 column"
                 " limit."),
                thing
            )
</code>```

Body:
I've got a logging statement, something like:

get_logger().info(
    'Logger logging %s because we need to log it.' % response['foo']['bar']
)

With indentation it comes out well over 80 rows. If I could split it around the %, it would be fine.

How can I split this into multiple lines. (ideally without just putting response['foo']['bar'] into a variable)

Body:
It might be worth noting that, for logging,

get_logger().info(
    'Logger logging %s because we need to log it.'
    % response['foo']['bar']
)

is the same as:

get_logger().info(
    'Logger logging %s because we need to log it.',
    response['foo']['bar']
)

since the debug(), info(), etc . methods interpret *args as to be used for string formatting the message.

https://docs.python.org/2/library/logging.html#logging.Logger.debug

In general for long strings, ones that ought to wrap around column 80, use parentheses, taking advantage of python's built-in string joining:

deeplyNested = True
thing = 'feedback'
class Contrived(object):
    def __init__(self):
        if deeplyNested:
            logger.info(
                ("Sometimes there's a lot to say in %s and you need to write"
                 " longer messages than what nicely fits in the 80 column"
                 " limit."),
                thing
            )


问:
Zend AMF and exception handling
I have created an Zend AMF service using the FlashBuilder tools. What I wanted to try was to change one of those automatically created methods to throw an exception in order to see the behaviour. Instead of the exception being serialized back to my Flex app it gives me the following:

[RPC Fault faultString="Channel disconnected" faultCode="Client.Error.DeliveryInDoubt" faultDetail="Channel disconnected before an acknowledgement was received"]
 at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:345]
 at mx.rpc::Responder/fault()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\Responder.as:68]
 at mx.rpc::AsyncRequest/fault()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:113]
 at NetConnectionMessageResponder/channelDisconnectHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:684]
 at flash.events::EventDispatcher/dispatchEventFunction()
 at flash.events::EventDispatcher/dispatchEvent()
 at mx.messaging::Channel/disconnectSuccess()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\Channel.as:1214]
 at mx.messaging.channels::NetConnectionChannel/internalDisconnect()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:175]
 at mx.messaging.channels::AMFChannel/internalDisconnect()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\AMFChannel.as:355]
 at mx.messaging.channels::AMFChannel/statusHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\AMFChannel.as:445]

The channel disconnects...

[RPC Fault faultString="Channel disconnected" faultCode="Client.Error.DeliveryInDoubt" faultDetail="Channel disconnected before an acknowledgement was received"]

This is the code:

public function getAllUser() {

```<code>$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");
$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$rows = array();

mysqli_stmt_bind_result($stmt, $row->id, $row->user_group_id, $row->username, $row->password, $row->active, $row->activation_key, $row->timezone, $row->created_on, $row->modified_on);

while (mysqli_stmt_fetch($stmt)) {
 $row->created_on = new DateTime($row->created_on);
 $row->modified_on = new DateTime($row->modified_on);
 $rows[] = $row;
 $row = new stdClass();
 mysqli_stmt_bind_result($stmt, $row->id, $row->user_group_id, $row->username, $row->password, $row->active, $row->activation_key, $row->timezone, $row->created_on, $row->modified_on);
}

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);

$errorCode = 1;

            throw(new Exception('the error message you want', $errorCode));

return $rows;
</code>```

}

Notice the throw statement:

throw(new Exception('the error message you want', $errorCode));

I really didn't expect this. How can I make it work?

Thank you in advanced!!!

答:
Well it does serialize the exception message and code which does the job for us. Partially but does it. I didn't notice that the service component I copied the code from in my question contained an exception handler which would suppress the exception and just disconnect the channel. I removed the exception handler letting the exception bubble up to Zend which in turn send the exception message and message code to the client.

I would like to have the actual exception sent as an AS3 object but what can I say. In this way I would have the properties of the exception serialized also. Unfortunately the same goes for custom exceptions.

Title: Zend AMF and exception handling

Body:
I have created an Zend AMF service using the FlashBuilder tools. What I wanted to try was to change one of those automatically created methods to throw an exception in order to see the behaviour. Instead of the exception being serialized back to my Flex app it gives me the following:

[RPC Fault faultString="Channel disconnected" faultCode="Client.Error.DeliveryInDoubt" faultDetail="Channel disconnected before an acknowledgement was received"]
 at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:345]
 at mx.rpc::Responder/fault()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\Responder.as:68]
 at mx.rpc::AsyncRequest/fault()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:113]
 at NetConnectionMessageResponder/channelDisconnectHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:684]
 at flash.events::EventDispatcher/dispatchEventFunction()
 at flash.events::EventDispatcher/dispatchEvent()
 at mx.messaging::Channel/disconnectSuccess()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\Channel.as:1214]
 at mx.messaging.channels::NetConnectionChannel/internalDisconnect()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:175]
 at mx.messaging.channels::AMFChannel/internalDisconnect()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\AMFChannel.as:355]
 at mx.messaging.channels::AMFChannel/statusHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\AMFChannel.as:445]

The channel disconnects...

[RPC Fault faultString="Channel disconnected" faultCode="Client.Error.DeliveryInDoubt" faultDetail="Channel disconnected before an acknowledgement was received"]

This is the code:

public function getAllUser() {

$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");
$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$rows = array();

mysqli_stmt_bind_result($stmt, $row->id, $row->user_group_id, $row->username, $row->password, $row->active, $row->activation_key, $row->timezone, $row->created_on, $row->modified_on);

while (mysqli_stmt_fetch($stmt)) {
 $row->created_on = new DateTime($row->created_on);
 $row->modified_on = new DateTime($row->modified_on);
 $rows[] = $row;
 $row = new stdClass();
 mysqli_stmt_bind_result($stmt, $row->id, $row->user_group_id, $row->username, $row->password, $row->active, $row->activation_key, $row->timezone, $row->created_on, $row->modified_on);
}

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);

$errorCode = 1;

            throw(new Exception('the error message you want', $errorCode));

return $rows;

}

Notice the throw statement:

throw(new Exception('the error message you want', $errorCode));

I really didn't expect this. How can I make it work?

Thank you in advanced!!!


问:
Unable to check for status indicator in protractor
I'm working on protractor for end to end testing and need to check for status indicator to disappear before clicking on a button. Right now I'm unable to do it.
I have tried to use invisibilityOf() as well as stalenessOf() but it's not working. It shows error ' is not clickable at point (540,823), Other element would receive the click: <#api-status-indicator>'

Here's my code in PageObject:

```<code>public isNotPresent(elem) {
    return browser.wait(protractor.ExpectedConditions.stalenessOf(elem), 5000).then(function () {
        console.log("Status indicator is not present in DOM");
        return true; //success
    },function () {
        console.log("Status indicator is present in DOM");
        return false; //Failure
    });
}

public waitForStatusIndicator(){
    console.log('in method wait for status indicator');
    return this.isNotPresent(element(by.css('#api-status-indicator'))).then((isNotPresent)=>{
        return isNotPresent;
    });
}
</code>```

Here's where I'm trying to check for status indicator:

```<code>PageObject.waitForStatusIndicator().then(function (isNotPresent) {
       if(isNotPresent == true) {
       someButton.click();
       return expect(browser.getCurrentUrl()).not.toBe(browser.baseUrl + "/login");
      }
})
</code>```

Where am I going wrong?

答:
If the element just appears and was not in the DOM first, you first need to wait until it's present and visible before you check, that it's gone again.

Overall something like this:

```<code>public isNoLongerPresent(elem) {
    //NOTE: If any of the expected conditions don't happen, your code times out.
    //No need for false-check or similar
    var EC = protractor.ExpectedConditions;
    browser.wait(EC.presenceOf(elem), 5000);
    browser.wait(EC.visibilityOf(elem), 5000); //Note, that visibilityOf requires presence
    return browser.wait(EC.stalenessOf(elem), 5000);
}

public waitForStatusIndicator(){
    console.log('in method wait for status indicator');
    return this.isNoLongerPresent(element(by.css('#api-status-indicator')));
}
</code>```

And your spec:
There is again no need for any then(). Protractor executes it synchronous and in case of any false on the way, your code would timeout.

```<code>PageObject.waitForStatusIndicator();
someButton.click();
return expect(browser.getCurrentUrl()).not.toBe(browser.baseUrl + "/login");
</code>```

Body:
I'm working on protractor for end to end testing and need to check for status indicator to disappear before clicking on a button. Right now I'm unable to do it.
I have tried to use invisibilityOf() as well as stalenessOf() but it's not working. It shows error ' is not clickable at point (540,823), Other element would receive the click: <#api-status-indicator>'

Here's my code in PageObject:

public isNotPresent(elem) {
    return browser.wait(protractor.ExpectedConditions.stalenessOf(elem), 5000).then(function () {
        console.log("Status indicator is not present in DOM");
        return true; //success
    },function () {
        console.log("Status indicator is present in DOM");
        return false; //Failure
    });
}

public waitForStatusIndicator(){
    console.log('in method wait for status indicator');
    return this.isNotPresent(element(by.css('#api-status-indicator'))).then((isNotPresent)=>{
        return isNotPresent;
    });
}

Here's where I'm trying to check for status indicator:

PageObject.waitForStatusIndicator().then(function (isNotPresent) {
       if(isNotPresent == true) {
       someButton.click();
       return expect(browser.getCurrentUrl()).not.toBe(browser.baseUrl + "/login");
      }
})

Where am I going wrong?

Body:
If the element just appears and was not in the DOM first, you first need to wait until it's present and visible before you check, that it's gone again.

Overall something like this:

public isNoLongerPresent(elem) {
    //NOTE: If any of the expected conditions don't happen, your code times out.
    //No need for false-check or similar
    var EC = protractor.ExpectedConditions;
    browser.wait(EC.presenceOf(elem), 5000);
    browser.wait(EC.visibilityOf(elem), 5000); //Note, that visibilityOf requires presence
    return browser.wait(EC.stalenessOf(elem), 5000);
}

public waitForStatusIndicator(){
    console.log('in method wait for status indicator');
    return this.isNoLongerPresent(element(by.css('#api-status-indicator')));
}

And your spec:
There is again no need for any then(). Protractor executes it synchronous and in case of any false on the way, your code would timeout.

PageObject.waitForStatusIndicator();
someButton.click();
return expect(browser.getCurrentUrl()).not.toBe(browser.baseUrl + "/login");


问:
Filtering OLAP fields in VBA
I update several OLAP fields regularly and was thinking of automating this task.

I tried recording some macros to understand the behind-the-scenes working of OLAP pivot tables and got this.

The following code is generated when I select all the months from October-2016 to October-2017 (the hierarchy in Fiscal Period is Year, Quarter and then Month):

```<code>  ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").CubeFields(5). _
        TreeviewControl.Drilled = Array(Array(""), Array( _
        "[Fiscal Period].[All Fiscal Period].[2017]"))
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Year]").HiddenItemsList = Array( _
        "[Fiscal Period].[All Fiscal Period].[2004]", _
        "[Fiscal Period].[All Fiscal Period].[2005]", _
        "[Fiscal Period].[All Fiscal Period].[2006]", _
        "[Fiscal Period].[All Fiscal Period].[2007]", _
        "[Fiscal Period].[All Fiscal Period].[2008]", _
        "[Fiscal Period].[All Fiscal Period].[2009]", _
        "[Fiscal Period].[All Fiscal Period].[2010]", _
        "[Fiscal Period].[All Fiscal Period].[2011]", _
        "[Fiscal Period].[All Fiscal Period].[2012]", _
        "[Fiscal Period].[All Fiscal Period].[2013]", _
        "[Fiscal Period].[All Fiscal Period].[2014]", _
        "[Fiscal Period].[All Fiscal Period].[2015]", _
        "[Fiscal Period].[All Fiscal Period].[2019]", _
        "[Fiscal Period].[All Fiscal Period].[2016]")
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Quarter]").HiddenItemsList = Array( _
        "[Fiscal Period].[All Fiscal Period].[2017].[1]")
    Range("B8").Select
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Year]").DrilledDown = True
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotSelect _
        "'[Fiscal Period].[All Fiscal Period].[2017].[2]'", xlDataAndLabel, True
    Range("B9").Select
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Quarter]").DrilledDown = True
    Range("E9").Select
</code>```

I have been searching the internet for any clues on this task and only see VisibleItemsList used. When I implement the VisibleItemsList code that I see on the internet on my own work, I get errors.

For example the following:

```<code>Worksheets(1).PivotTables(1).PivotFields("[Fiscal Period].[Year].[Year]").VisibleItemsList = Array("[Fiscal Period].[All Fiscal Period].[2015]", "[Fiscal Period].[All Fiscal Period].[2016]")
</code>```

gives the error:

"Unable to get the PivotFields property of PivotTable class"

I am trying to select only the fiscal years 2015 and 2016 using the above code.

I would be extremely grateful if someone will walk me through this task. This has started proving to be one of the most excruciating I have ever faced. I just need a few pointers on the VisibleItemsList property. I am using Excel 2007 if thats relevant.

Here is an image of the pivottable layout:

Additional Information:

The code when i record the macro selecting only 2015 and 2016 (and not expanding them. The code when i expand the Years and Quarters can be seen above, in which I select all the months from Oct-2016 to Oct-2017) is:

```<code>ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").CubeFields(5). _
        TreeviewControl.Drilled = Array("")
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Year]").HiddenItemsList = Array( _
        "[Fiscal Period].[All Fiscal Period].[2004]", _
        "[Fiscal Period].[All Fiscal Period].[2005]", _
        "[Fiscal Period].[All Fiscal Period].[2006]", _
        "[Fiscal Period].[All Fiscal Period].[2007]", _
        "[Fiscal Period].[All Fiscal Period].[2008]", _
        "[Fiscal Period].[All Fiscal Period].[2009]", _
        "[Fiscal Period].[All Fiscal Period].[2010]", _
        "[Fiscal Period].[All Fiscal Period].[2011]", _
        "[Fiscal Period].[All Fiscal Period].[2012]", _
        "[Fiscal Period].[All Fiscal Period].[2013]", _
        "[Fiscal Period].[All Fiscal Period].[2014]", _
        "[Fiscal Period].[All Fiscal Period].[2019]", _
        "[Fiscal Period].[All Fiscal Period].[2017]", _
        "[Fiscal Period].[All Fiscal Period].[2018]")
</code>```

答:
The code the Macro recorder gave to select the Pivotfield was:

```<code>PivotFields("[Fiscal Period].[Year]")
</code>```

...but you are using:

```<code>PivotFields("[Fiscal Period].[Year].[Year]")
</code>```

...so perhaps this explains the error.

Title: Filtering OLAP fields in VBA

Body:
I update several OLAP fields regularly and was thinking of automating this task.

I tried recording some macros to understand the behind-the-scenes working of OLAP pivot tables and got this.

The following code is generated when I select all the months from October-2016 to October-2017 (the hierarchy in Fiscal Period is Year, Quarter and then Month):

  ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").CubeFields(5). _
        TreeviewControl.Drilled = Array(Array(""), Array( _
        "[Fiscal Period].[All Fiscal Period].[2017]"))
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Year]").HiddenItemsList = Array( _
        "[Fiscal Period].[All Fiscal Period].[2004]", _
        "[Fiscal Period].[All Fiscal Period].[2005]", _
        "[Fiscal Period].[All Fiscal Period].[2006]", _
        "[Fiscal Period].[All Fiscal Period].[2007]", _
        "[Fiscal Period].[All Fiscal Period].[2008]", _
        "[Fiscal Period].[All Fiscal Period].[2009]", _
        "[Fiscal Period].[All Fiscal Period].[2010]", _
        "[Fiscal Period].[All Fiscal Period].[2011]", _
        "[Fiscal Period].[All Fiscal Period].[2012]", _
        "[Fiscal Period].[All Fiscal Period].[2013]", _
        "[Fiscal Period].[All Fiscal Period].[2014]", _
        "[Fiscal Period].[All Fiscal Period].[2015]", _
        "[Fiscal Period].[All Fiscal Period].[2019]", _
        "[Fiscal Period].[All Fiscal Period].[2016]")
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Quarter]").HiddenItemsList = Array( _
        "[Fiscal Period].[All Fiscal Period].[2017].[1]")
    Range("B8").Select
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Year]").DrilledDown = True
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotSelect _
        "'[Fiscal Period].[All Fiscal Period].[2017].[2]'", xlDataAndLabel, True
    Range("B9").Select
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Quarter]").DrilledDown = True
    Range("E9").Select

I have been searching the internet for any clues on this task and only see VisibleItemsList used. When I implement the VisibleItemsList code that I see on the internet on my own work, I get errors.

For example the following:

Worksheets(1).PivotTables(1).PivotFields("[Fiscal Period].[Year].[Year]").VisibleItemsList = Array("[Fiscal Period].[All Fiscal Period].[2015]", "[Fiscal Period].[All Fiscal Period].[2016]")

gives the error:

"Unable to get the PivotFields property of PivotTable class"

I am trying to select only the fiscal years 2015 and 2016 using the above code.

I would be extremely grateful if someone will walk me through this task. This has started proving to be one of the most excruciating I have ever faced. I just need a few pointers on the VisibleItemsList property. I am using Excel 2007 if thats relevant.

Here is an image of the pivottable layout:

Additional Information:

The code when i record the macro selecting only 2015 and 2016 (and not expanding them. The code when i expand the Years and Quarters can be seen above, in which I select all the months from Oct-2016 to Oct-2017) is:

ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").CubeFields(5). _
        TreeviewControl.Drilled = Array("")
    ActiveSheet.PivotTables("Microsoft Office PivotTable 10.0").PivotFields( _
        "[Fiscal Period].[Year]").HiddenItemsList = Array( _
        "[Fiscal Period].[All Fiscal Period].[2004]", _
        "[Fiscal Period].[All Fiscal Period].[2005]", _
        "[Fiscal Period].[All Fiscal Period].[2006]", _
        "[Fiscal Period].[All Fiscal Period].[2007]", _
        "[Fiscal Period].[All Fiscal Period].[2008]", _
        "[Fiscal Period].[All Fiscal Period].[2009]", _
        "[Fiscal Period].[All Fiscal Period].[2010]", _
        "[Fiscal Period].[All Fiscal Period].[2011]", _
        "[Fiscal Period].[All Fiscal Period].[2012]", _
        "[Fiscal Period].[All Fiscal Period].[2013]", _
        "[Fiscal Period].[All Fiscal Period].[2014]", _
        "[Fiscal Period].[All Fiscal Period].[2019]", _
        "[Fiscal Period].[All Fiscal Period].[2017]", _
        "[Fiscal Period].[All Fiscal Period].[2018]")

Body:
The code the Macro recorder gave to select the Pivotfield was:

PivotFields("[Fiscal Period].[Year]")

...but you are using:

PivotFields("[Fiscal Period].[Year].[Year]")

...so perhaps this explains the error.


问:
Full Outer Join self with null values
I want to do a full outer self-join that includes nulls.  For example, if the table Data looks like:

```<code>N   Name   Val
--------------
1   ABC    8
1   DEF    7
2   ABC    9
2   XYZ    6
</code>```

(where N is a general index column to enable a self-join on sequential groups) and I do:

```<code>SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name
</code>```

I want:

```<code>N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6
</code>```

but what I get is more like a cross-join:

```<code>n  Name  A    B
--------------
1  ABC   8    9
1  DEF   7    NULL
2  ABC   9    NULL
2  XYZ   6    NULL
1  ABC   NULL    8
1  DEF   NULL    7
2  XYZ   NULL    6
</code>```

How do I perform this full outer join in order to get the condensed self-join results?

(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)

答:
Since we want to handle a generalized self-join index column N let's extend the sample set a little further:

```<code>create table #Data (n int, name char(3), val int)
insert into #Data values (1, 'ABC',8)
insert into #Data values (1, 'DEF',7)
insert into #Data values (2, 'ABC',9)
insert into #Data values (2, 'XYZ',6)
insert into #Data values (3, 'ABC',9)
insert into #Data values (3, 'DEF',5)
insert into #Data values (3, 'XYZ',4)
</code>```

For this sample we want the SQL to produce this output:

```<code>N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6
2  ABC   9    9
2  DEF   NULL 5
2  XYZ   6    4
</code>```

The following code works on the general case:

```<code>SELECT COALESCE(a.n, b.n-1) as i, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM #Data a
    FULL OUTER JOIN #Data b ON a.N = b.N - 1 AND a.Name = b.Name
WHERE a.n < (SELECT MAX(n) FROM #Data) -- Deals with end index case
    OR (a.n is null AND b.n-1 IN (SELECT DISTINCT n FROM #Data))
ORDER BY COALESCE(a.n, b.n-1), Name
</code>```

To see why this works, a good intermediate step is to note that when a.N = 1 we want the rows where n = 1 from:

```<code>SELECT COALESCE(a.n, b.n - 1) as n, COALESCE(a.Name, b.Name) as Name,
    a.Val as A, b.Val as B
FROM #Data a
    FULL OUTER JOIN #Data b ON a.N = b.N - 1 AND a.Name = b.Name
</code>```

Title: Full Outer Join self with null values

Body:
I want to do a full outer self-join that includes nulls.  For example, if the table Data looks like:

N   Name   Val
--------------
1   ABC    8
1   DEF    7
2   ABC    9
2   XYZ    6

(where N is a general index column to enable a self-join on sequential groups) and I do:

SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name

I want:

N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6

but what I get is more like a cross-join:

n  Name  A    B
--------------
1  ABC   8    9
1  DEF   7    NULL
2  ABC   9    NULL
2  XYZ   6    NULL
1  ABC   NULL    8
1  DEF   NULL    7
2  XYZ   NULL    6

How do I perform this full outer join in order to get the condensed self-join results?

(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)

Body:
Since we want to handle a generalized self-join index column N let's extend the sample set a little further:

create table #Data (n int, name char(3), val int)
insert into #Data values (1, 'ABC',8)
insert into #Data values (1, 'DEF',7)
insert into #Data values (2, 'ABC',9)
insert into #Data values (2, 'XYZ',6)
insert into #Data values (3, 'ABC',9)
insert into #Data values (3, 'DEF',5)
insert into #Data values (3, 'XYZ',4)

For this sample we want the SQL to produce this output:

N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6
2  ABC   9    9
2  DEF   NULL 5
2  XYZ   6    4

The following code works on the general case:

SELECT COALESCE(a.n, b.n-1) as i, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM #Data a
    FULL OUTER JOIN #Data b ON a.N = b.N - 1 AND a.Name = b.Name
WHERE a.n < (SELECT MAX(n) FROM #Data) -- Deals with end index case
    OR (a.n is null AND b.n-1 IN (SELECT DISTINCT n FROM #Data))
ORDER BY COALESCE(a.n, b.n-1), Name

To see why this works, a good intermediate step is to note that when a.N = 1 we want the rows where n = 1 from:

SELECT COALESCE(a.n, b.n - 1) as n, COALESCE(a.Name, b.Name) as Name,
    a.Val as A, b.Val as B
FROM #Data a
    FULL OUTER JOIN #Data b ON a.N = b.N - 1 AND a.Name = b.Name


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

```<code>import pandas

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

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

print(df)

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

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

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

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

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

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

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

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

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

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

Many thanks!

答:
I've provided an example of how you can achieve your desired date formatting in a .xlsx output using pandas.  It would also require adding the datetime module.

As @jmcnamara mentioned, I think the best and most flexible solution would be to use xlsxwriter directly.

Here's a link to another SO answer that provides further background on the excel "serial date" format and getting it from a datetime object in python.  This is essentially the same as what I did to convert the column to an excel date.  I've also added an additional format (called "centre_date_format_wb").

Here's the full code with my additions/changes:

```<code>import pandas
import datetime

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

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

excel_start_date = datetime.date(1899, 12, 30)
df['fechas'] = df['fechas'] - excel_start_date
df.fechas = df.fechas.dt.days

print(df)

xlsx_writer = pandas.ExcelWriter(
    'test.xlsx'
    , engine='xlsxwriter'
)

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

dollar_format = '_($* #,##0.00" "_);_($* (#,##0.0);_($* "-"??_);_(@_)'
dollar_format_wb = wb.add_format({'num_format': dollar_format, 'valign': 'vcenter'})
centre_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter'})
#additional format added below
centre_date_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter', 'num_format' : 'mm/dd/yyyy' })

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

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

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

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

And an image of the resulting worksheet:

Title: python xlsxwriter won't align dates

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

import pandas

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

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

print(df)

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

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

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

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

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

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

xlsx_writer.save()

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

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

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

Many thanks!

Body:
I've provided an example of how you can achieve your desired date formatting in a .xlsx output using pandas.  It would also require adding the datetime module.

As @jmcnamara mentioned, I think the best and most flexible solution would be to use xlsxwriter directly.

Here's a link to another SO answer that provides further background on the excel "serial date" format and getting it from a datetime object in python.  This is essentially the same as what I did to convert the column to an excel date.  I've also added an additional format (called "centre_date_format_wb").

Here's the full code with my additions/changes:

import pandas
import datetime

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

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

excel_start_date = datetime.date(1899, 12, 30)
df['fechas'] = df['fechas'] - excel_start_date
df.fechas = df.fechas.dt.days

print(df)

xlsx_writer = pandas.ExcelWriter(
    'test.xlsx'
    , engine='xlsxwriter'
)

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

dollar_format = '_($* #,##0.00" "_);_($* (#,##0.0);_($* "-"??_);_(@_)'
dollar_format_wb = wb.add_format({'num_format': dollar_format, 'valign': 'vcenter'})
centre_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter'})
#additional format added below
centre_date_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter', 'num_format' : 'mm/dd/yyyy' })

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

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

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

xlsx_writer.save()

And an image of the resulting worksheet:


问:
How to change pointer variables within a struct?
So I am trying to implement a linked list and I have this struct for each of the nodes:

```<code>    typedef struct listNode {
        struct listNode *next;
        void *data;
    } NODE;
</code>```

Previously, I had made a game where the spacecraft struct looked like this:

```<code>   typedef struct {
       int height;
       int width;
   } SPACECRAFT;
</code>```

and I could make a new spacecraft by doing

```<code>  SPACECRAFT plyrShip = {
      .width = //someInt;
      .height = //someInt;
  };
</code>```

Though with the nodes, the variables are pointers and it isn't allowing me to create a new node by doing

```<code>  NODE newNode = {
      .*next = null;
      .*data = *data //function has *data as parameter so I can pass it
                     //into the node
  }
</code>```

What am I doing wrong?

答:
Officially, this is called Designated Initializer which was introduced since C99.

First, you should realize pointer types. struct listNode next; is to declare a variable, next, whose type is struct listNode. struct listNode *next is to declare a variable, next, whose type does be a type which points to a value whose type is struct listNode. So you should do it like that.

```<code>  NODE newNode = {
  .next = null,
  .data = data
  }
</code>```

Moreover, this is what structure looks like in memory. You could remember this to eliminate confusion. And this clearly points out why you couldn't do that. (member next in the structure can't be dereferenced individually because of the structure layout here).

```<code>|--------------|
| newNode.next | &newNode
|--------------|
| newNode.data |
|--------------|
</code>```

Updated Response: Check edit Summary.

Body:
So I am trying to implement a linked list and I have this struct for each of the nodes:

    typedef struct listNode {
        struct listNode *next;
        void *data;
    } NODE;

Previously, I had made a game where the spacecraft struct looked like this:

   typedef struct {
       int height;
       int width;
   } SPACECRAFT;

and I could make a new spacecraft by doing

  SPACECRAFT plyrShip = {
      .width = //someInt;
      .height = //someInt;
  };

Though with the nodes, the variables are pointers and it isn't allowing me to create a new node by doing

  NODE newNode = {
      .*next = null;
      .*data = *data //function has *data as parameter so I can pass it
                     //into the node
  }

What am I doing wrong?

Body:
Officially, this is called Designated Initializer which was introduced since C99.

First, you should realize pointer types. struct listNode next; is to declare a variable, next, whose type is struct listNode. struct listNode *next is to declare a variable, next, whose type does be a type which points to a value whose type is struct listNode. So you should do it like that.

  NODE newNode = {
  .next = null,
  .data = data
  }

Moreover, this is what structure looks like in memory. You could remember this to eliminate confusion. And this clearly points out why you couldn't do that. (member next in the structure can't be dereferenced individually because of the structure layout here).

|--------------|
| newNode.next | &newNode
|--------------|
| newNode.data |
|--------------|

Updated Response: Check edit Summary.