问:
Connection failed: Connection refused mysql (LAMP)
When I try to connect to mysql it refuses my script. I have mysql installed on ubuntu 16.10 (LAMP).

When I run this:

```<code><?php
$servername = "ip";
$username = "user";
$password = "pw";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
</code>```

It shows:

Connection failed: Connection refused mysql (LAMP)

I tried to change the bind-address to 0.0.0.0, then it showed:

Connection failed: Host 'webserver1' is not allowed to connect to this MySQL server

I tried to comment (#) the bind-address. That didn't work either.

I am running the scripts on a client with another ip-range/subnet then the mysql-server. When I run phpmyadmin on the client I have no problem.

答:
Its possible to have a security precaution. You could try adding a new administrator account in mysql.

```<code>mysql> CREATE USER 'yourUser'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'yourUser'@'localhost'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'yourUser'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'yourUser'@'%'
    ->     WITH GRANT OPTION;
</code>```

Try newly created user in your code.

Hope it helps!

Body:
When I try to connect to mysql it refuses my script. I have mysql installed on ubuntu 16.10 (LAMP).

When I run this:

<?php
$servername = "ip";
$username = "user";
$password = "pw";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

It shows:

Connection failed: Connection refused mysql (LAMP)

I tried to change the bind-address to 0.0.0.0, then it showed:

Connection failed: Host 'webserver1' is not allowed to connect to this MySQL server

I tried to comment (#) the bind-address. That didn't work either.

I am running the scripts on a client with another ip-range/subnet then the mysql-server. When I run phpmyadmin on the client I have no problem.

Body:
Its possible to have a security precaution. You could try adding a new administrator account in mysql.

mysql> CREATE USER 'yourUser'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'yourUser'@'localhost'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'yourUser'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'yourUser'@'%'
    ->     WITH GRANT OPTION;

Try newly created user in your code.

Hope it helps!


来源: stackexchange

问:
How to remove dashed line around WPF control when focused
About a few days ago, we ran our WPF application, some of us(in several developer's computers) found very a lot controls has dashed border when they got focused, such as below:

The outer control is Grid, and in other place, Border and others also has same issue.

And in the past days, it's gone. Today, all of our team can see this issue.

We tried to set the element FocusVisualStyle="{x:Null}", it has no effect at all, and we couldn't find what changes affected it.

So, does this issue related to the computer environment? And what possible reason can cause this strange issue?

Updated:

We just tried our application in a clean virtual machine, it can be reproduced, so maybe the only point of this issue is our code.

Since we haven't found the related code caused this issue, we didn't know upload what XAML code to show this issue.

答:
I guess this won't be of much use to the OP but in case anyone else is struggling with issue...

I strongly suspect setting FocusVisualStyle="{x:Null}" is the answer but sometimes it may not be obvious which control(s?) in the visual tree to set it on. I suggest using Snoop, snoop the application, enable the preview, expand the preview area, recreate the issue in snoop by clicking on the visual tree then re-selecting the problem area in your application like so:

Then try deleting the FocusVisualStyle by simply clicking on the Value (in yellow in my screenshot) and deleting. Rinse and repeat until you find the culprit(s). The visual tree tree probably won't quite match the logical tree but through trial and error you work it out.

In my example above I found it was the ScrollViewer causing my annoying dotted rectangle rather than the canvas that I first assumed it would be.

Regards David

ContentLicense: CC BY-SA 3.0


问:
Error in add and delete the details in the table
i am new to js i am writing a code to add and delete the details in the table? i have some error please check th code once

答:
Below is working snippet change onclick="save_row('n') to onclick="save_row('1') and do the same for save and delete as well and on edit row function change below lines we need to find elements rather than those values so i have remove value from those you can read more about .value of javascript

```<code> var name=document.getElementById("name_row"+no);
 var lname=document.getElementById("lname_row"+no);
 var country=document.getElementById("country_row"+no);
 var age=document.getElementById("age_row"+no);
</code>```

function edit_row(no)
{
 document.getElementById("edit_button");
 document.getElementById("save_button");
 var name=document.getElementById("name_row"+no);
 var lname=document.getElementById("lname_row"+no);
 var country=document.getElementById("country_row"+no);
 var age=document.getElementById("age_row"+no);

 var name_data=name.innerHTML;
 var lname_data=lname.innerHTML;
 var country_data=country.innerHTML;
 var age_data=age.innerHTML;

 name.innerHTML="<input type='text' id='name_text"+no+"' value='"+name_data+"'>";
 lname.innerHTML="<input type='text' id='lname_text"+no+"' value='"+lname_data+"'>";
 country.innerHTML="<input type='text' id='country_text"+no+"' value='"+country_data+"'>";
 age.innerHTML="<input type='text' id='age_text"+no+"' value='"+age_data+"'>";
}

function save_row(no)
{
 var name_val=document.getElementById("name_text"+no).value;
 var lname_val=document.getElementById("lname_text"+no).value;
 var country_val=document.getElementById("country_text"+no).value;
 var age_val=document.getElementById("age_text"+no).value;

 document.getElementById("name_row"+no).innerHTML=name_val;
 document.getElementById("lname_row"+no).innerHTML=lname_val;
 document.getElementById("country_row"+no).innerHTML=country_val;
 document.getElementById("age_row"+no).innerHTML=age_val;

 document.getElementById("edit_button"+no);
 document.getElementById("save_button"+no);
}
function delete_row(no)
{
debugger;
 document.getElementById("row"+no+"").innerHTML="";
}
function add_row()
{
debugger;
 var new_name=document.getElementById("new_name").value;
 var new_lname=document.getElementById("new_lname").value;
 var new_country=document.getElementById("new_country").value;
 var new_age=document.getElementById("new_age").value;

 var table=document.getElementById("data_table");
 var table_len=(table.rows.length)-1;
 var row = table.insertRow(table_len);
row.id =  "row"+ table_len;
row.innerHTML= ""+new_name+"	"+new_lname+"	"+new_country+"	"+new_age+"	<button id='edit_button"+table_len+"' value='Edit' onclick='edit_row("+table_len+")'>Edit</button><button id='delet_button"+table_len+"' value='Delete' onclick='delete_row("+table_len+")'> Delete </button> <button id='save_button"+table_len+"' value='Save'  onclick='save_row("+table_len+")'> Save</button>	";

 document.getElementById("new_name").value="";
 document.getElementById("new_lname").value="";
 document.getElementById("new_country").value="";
 document.getElementById("new_age").value="";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table  id="data_table" border=1>
<tr>
<th>First Name</th>
<th>Last Name </th>
<th>Country</th>
<th>Age</th>
</tr>
<tr id="row1">
<td id="name_row1">sai</td>
<td id="lname_row1">Kunal</td>
<td id="country_row1">India</td>
<td id="age_row1">20</td>
<td>
<button id="edit_button"   value="Edit"   onclick="edit_row('1')">Edit</button>
<button id="save_button"   value="Save"   onclick="save_row('1')"> Save </button>
<button id="delete_button" value="Delete" onclick="delete_row('1')"> Delete</button>
</td>
</tr>
<tr>
<td><input type="text" id="new_name" value = "" ></td>
<td><input type="text" id="new_lname" value = ""></td>
<td><input type="text" id="new_country" value = ""></td>
<td><input type="text" id="new_age" value = ""></td>
<td><button  onclick="add_row();" value="Add Row">Add Row</button> </td>
</tr>
</table></code>```

Body:
Below is working snippet change onclick="save_row('n') to onclick="save_row('1') and do the same for save and delete as well and on edit row function change below lines we need to find elements rather than those values so i have remove value from those you can read more about .value of javascript

 var name=document.getElementById("name_row"+no);
 var lname=document.getElementById("lname_row"+no);
 var country=document.getElementById("country_row"+no);
 var age=document.getElementById("age_row"+no);

function edit_row(no)
{
 document.getElementById("edit_button");
 document.getElementById("save_button");
 var name=document.getElementById("name_row"+no);
 var lname=document.getElementById("lname_row"+no);
 var country=document.getElementById("country_row"+no);
 var age=document.getElementById("age_row"+no);

 var name_data=name.innerHTML;
 var lname_data=lname.innerHTML;
 var country_data=country.innerHTML;
 var age_data=age.innerHTML;

 name.innerHTML="<input type='text' id='name_text"+no+"' value='"+name_data+"'>";
 lname.innerHTML="<input type='text' id='lname_text"+no+"' value='"+lname_data+"'>";
 country.innerHTML="<input type='text' id='country_text"+no+"' value='"+country_data+"'>";
 age.innerHTML="<input type='text' id='age_text"+no+"' value='"+age_data+"'>";
}

function save_row(no)
{
 var name_val=document.getElementById("name_text"+no).value;
 var lname_val=document.getElementById("lname_text"+no).value;
 var country_val=document.getElementById("country_text"+no).value;
 var age_val=document.getElementById("age_text"+no).value;

 document.getElementById("name_row"+no).innerHTML=name_val;
 document.getElementById("lname_row"+no).innerHTML=lname_val;
 document.getElementById("country_row"+no).innerHTML=country_val;
 document.getElementById("age_row"+no).innerHTML=age_val;

 document.getElementById("edit_button"+no);
 document.getElementById("save_button"+no);
}
function delete_row(no)
{
debugger;
 document.getElementById("row"+no+"").innerHTML="";
}
function add_row()
{
debugger;
 var new_name=document.getElementById("new_name").value;
 var new_lname=document.getElementById("new_lname").value;
 var new_country=document.getElementById("new_country").value;
 var new_age=document.getElementById("new_age").value;

 var table=document.getElementById("data_table");
 var table_len=(table.rows.length)-1;
 var row = table.insertRow(table_len);
row.id =  "row"+ table_len;
row.innerHTML= "<td id='name_row"+table_len+"'>"+new_name+"</td><td id='lname_row"+table_len+"'>"+new_lname+"</td><td id='country_row"+table_len+"'>"+new_country+"</td><td id='age_row"+table_len+"'>"+new_age+"</td><td><button id='edit_button"+table_len+"' value='Edit' onclick='edit_row("+table_len+")'>Edit</button><button id='delet_button"+table_len+"' value='Delete' onclick='delete_row("+table_len+")'> Delete </button> <button id='save_button"+table_len+"' value='Save'  onclick='save_row("+table_len+")'> Save</button></td>";

 document.getElementById("new_name").value="";
 document.getElementById("new_lname").value="";
 document.getElementById("new_country").value="";
 document.getElementById("new_age").value="";
}

<table  id="data_table" border=1>
<tr>
<th>First Name</th>
<th>Last Name </th>
<th>Country</th>
<th>Age</th>
</tr>
<tr id="row1">
<td id="name_row1">sai</td>
<td id="lname_row1">Kunal</td>
<td id="country_row1">India</td>
<td id="age_row1">20</td>
<td>
<button id="edit_button"   value="Edit"   onclick="edit_row('1')">Edit</button>
<button id="save_button"   value="Save"   onclick="save_row('1')"> Save </button>
<button id="delete_button" value="Delete" onclick="delete_row('1')"> Delete</button>
</td>
</tr>
<tr>
<td><input type="text" id="new_name" value = "" ></td>
<td><input type="text" id="new_lname" value = ""></td>
<td><input type="text" id="new_country" value = ""></td>
<td><input type="text" id="new_age" value = ""></td>
<td><button  onclick="add_row();" value="Add Row">Add Row</button> </td>
</tr>
</table>


问:
How to take array as an input in android?
Actually I am designing an android application in which I would be taking array as an input by using EditText.  so the thing is I am trying a lot by I am not getting how to do it so. Can anyone help me please.
I don't have a proper code so I am not attaching that but please help me with your code.

How can I take input as an array using EditText in android.
I want to insert n elements by EditText and than want to convert them in a single array.
like if I give input 1 and 2 and 3 and 4. than I can have a array like a[4] = {1,2,3,4}

答:
maybe you can have a text field that keeps taking an element one at a time until the user click on stop.
So you would have one text field and 2 buttons
one button would just add an element to the array(say add to array button), and the other element would be used to denote that the user has finished entering all elements.

so the user would enter an element, click on add to array button, then the the field gets cleared, so that the user can enter the next element. and he can keep doing this until he clicks on "done" button.

On the backend instead of an array, you can have an ArrayList so that you can keep calling list.add(element) every time the add to array button is clicked.

```<code>List<String> list = new ArrayList<String>;
onAddToArrayButtonClick(View v){
list.add(editText.getText().toString();
editText.getText().clear(); //this clears the edit text
}
</code>```

If you want to take the input of the array in one go you can use "," as a delimeter and then call string.split(",");

Something like:

```<code>onAddToArrayButtonClick(View v){
String[] array = editText.getText().toString().trim().split(","); /*for a user input of 1,2,3,4 split will return a string array = {"1","2","3","4"} */
}
</code>```

Body:
maybe you can have a text field that keeps taking an element one at a time until the user click on stop.
So you would have one text field and 2 buttons
one button would just add an element to the array(say add to array button), and the other element would be used to denote that the user has finished entering all elements.

so the user would enter an element, click on add to array button, then the the field gets cleared, so that the user can enter the next element. and he can keep doing this until he clicks on "done" button.

On the backend instead of an array, you can have an ArrayList so that you can keep calling list.add(element) every time the add to array button is clicked.

List<String> list = new ArrayList<String>;
onAddToArrayButtonClick(View v){
list.add(editText.getText().toString();
editText.getText().clear(); //this clears the edit text
}

If you want to take the input of the array in one go you can use "," as a delimeter and then call string.split(",");

Something like:

onAddToArrayButtonClick(View v){
String[] array = editText.getText().toString().trim().split(","); /*for a user input of 1,2,3,4 split will return a string array = {"1","2","3","4"} */
}


问:
Is it possible to load an image from it's thumbnail to it's high quality with an animation.
I have both thumbnail and real images, by now, loading thumbnail first so that user don't have to wait, then after show its real (high quality) image.
But It should not be like this.
Blur to High quality with nice animations.
using Picasso for Image loading.</p>

答:
Thanks to @Vlad Matvienko

```<code>Picasso.with(context)
   .load(thumb) // thumbnail url goes here
   .into(imageView, new Callback() {
        @Override
        public void onSuccess() {
            Picasso.with(context)
                    .load(url) // image url goes here
                    .placeholder(imageView.getDrawable())
                    .into(imageView);
        }
        @Override
        public void onError() {

        }
    });
</code>```

This is how it roll.

Body:
Thanks to @Vlad Matvienko

Picasso.with(context)
   .load(thumb) // thumbnail url goes here
   .into(imageView, new Callback() {
        @Override
        public void onSuccess() {
            Picasso.with(context)
                    .load(url) // image url goes here
                    .placeholder(imageView.getDrawable())
                    .into(imageView);
        }
        @Override
        public void onError() {

        }
    });

This is how it roll.


问:
What is the colContainer property and where i can find its documentation
I have just started to discover the ui-grid last couple of days.
The documentation of the ui.grid.class:GridOptions shows an example on how to use the rowTemplate property :

rowTemplate

'ui-grid/ui-grid-row' by default. When provided, this setting uses a custom row template. Can be set to either the name of a template file:

```<code>$scope.gridOptions.rowTemplate = 'row_template.html';
</code>```

inline html

```<code>$scope.gridOptions.rowTemplate = '<div style="background-color: aquamarine" ng-click="grid.appScope.fnOne(row)" ng-repeat="col in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ui-grid-cell></div>';
</code>```

As you can see in the rowTemplate html code there is an ng-repeat which iterates over colContainer.renderedColumns's col items and there is the track by option which uses col.colDef.name.

the same template was also used in the 317_custom_templates tutorial example.

I was looking in the documentation for the origin of the colContainer property and i only could found a property having the same name under ui.grid.cellNav.object:CellNav without any details for it (i already don't know if it's exactly the same colContainer property used in the rowTemplate example above and in the 317_custom_templates tutorial example because in the 202 Cell Navigation tutorial it's said :
> To enable, you must include the 'ui.grid.cellNav' module and in the 317_custom_templates tutorial example there is no such as injection for this module)
there is also a property sourceColContainer under the ui.grid.class:ScrollEvent but it's not the same poperty name but maybe it can be its origin.

I would like to find the colContainer property's documentation and understand it better and know what are its own sub-properties if any exists (other than the colDef.name) or at least i would know its origin and look into its code source if there is no documentation for it maybe that would be useful too.

Best regards.

答:
I found this /src/js/core/directives/ui-grid-render-container.js:47 :

```<code> var colContainer = $scope.colContainer = grid.renderContainers[$scope.colContainerName];
</code>```

So colContainer is in fact a render Container that you can access outside directives and templates by doing $scope.gridApi.grid.renderContainers["nameOfColContainer"]

to know the nameOfColContainer you will have to check your template here

(/src/templates/ui-grid/ui-grid.html:33) :

```<code> <div ui-grid-render-container
      container-id="'body'"
      col-container-name="'body'"
      row-container-name="'body'"
      bind-scroll-horizontal="true"
      bind-scroll-vertical="true"
      enable-horizontal-scrollbar="grid.options.enableHorizontalScrollbar"
      enable-vertical-scrollbar="grid.options.enableVerticalScrollbar">
    </div>
</code>```

So it is most certainly body. Within a renderContainer you will have an object called renderedColumns which contains the columns to be rendered.
You can also access other containers other than 'body' : left and right.
This is if you use pinned left and/or right, body being the center container.

Body:
I have just started to discover the ui-grid last couple of days.
The documentation of the ui.grid.class:GridOptions shows an example on how to use the rowTemplate property :

rowTemplate

'ui-grid/ui-grid-row' by default. When provided, this setting uses a custom row template. Can be set to either the name of a template file:

$scope.gridOptions.rowTemplate = 'row_template.html';

inline html

$scope.gridOptions.rowTemplate = '

';

As you can see in the rowTemplate html code there is an ng-repeat which iterates over colContainer.renderedColumns's col items and there is the track by option which uses col.colDef.name.

the same template was also used in the 317_custom_templates tutorial example.

I was looking in the documentation for the origin of the colContainer property and i only could found a property having the same name under ui.grid.cellNav.object:CellNav without any details for it (i already don't know if it's exactly the same colContainer property used in the rowTemplate example above and in the 317_custom_templates tutorial example because in the 202 Cell Navigation tutorial it's said :
> To enable, you must include the 'ui.grid.cellNav' module and in the 317_custom_templates tutorial example there is no such as injection for this module)
there is also a property sourceColContainer under the ui.grid.class:ScrollEvent but it's not the same poperty name but maybe it can be its origin.

I would like to find the colContainer property's documentation and understand it better and know what are its own sub-properties if any exists (other than the colDef.name) or at least i would know its origin and look into its code source if there is no documentation for it maybe that would be useful too.

Best regards.

Body:
I found this /src/js/core/directives/ui-grid-render-container.js:47 :

 var colContainer = $scope.colContainer = grid.renderContainers[$scope.colContainerName];

So colContainer is in fact a render Container that you can access outside directives and templates by doing $scope.gridApi.grid.renderContainers["nameOfColContainer"]

to know the nameOfColContainer you will have to check your template here

(/src/templates/ui-grid/ui-grid.html:33) :

 <div ui-grid-render-container
      container-id="'body'"
      col-container-name="'body'"
      row-container-name="'body'"
      bind-scroll-horizontal="true"
      bind-scroll-vertical="true"
      enable-horizontal-scrollbar="grid.options.enableHorizontalScrollbar"
      enable-vertical-scrollbar="grid.options.enableVerticalScrollbar">
    </div>

So it is most certainly body. Within a renderContainer you will have an object called renderedColumns which contains the columns to be rendered.
You can also access other containers other than 'body' : left and right.
This is if you use pinned left and/or right, body being the center container.


问:
How to disable UITableViewRowAction (without clicking an edit button)?
Normally when this function is called, deleting a table view cell by swiping left is allowed:

```<code>    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        dataSource.remove(at: indexPath.row)

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
}
</code>```

But I created an edit button like this:

```<code>self.navigationItem.leftBarButtonItem = self.editButtonItem
</code>```

and I'd like to enable deleting a cell only when the edit button was clicked and NOT just by swiping. Is this possible?

答:
I solved it this way: </p>

```<code>    var editMode = false

...

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

    if editMode == true {
        return true
    } else {
        return false
    }
}

    override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)

    if(editing) {
        tableView.reloadData()
        editMode = true
    }
    else if(!editing) {
        tableView.reloadData()
        editMode = false
    }
}
</code>```

Body:
Normally when this function is called, deleting a table view cell by swiping left is allowed:

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        dataSource.remove(at: indexPath.row)

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
}

But I created an edit button like this:

self.navigationItem.leftBarButtonItem = self.editButtonItem

and I'd like to enable deleting a cell only when the edit button was clicked and NOT just by swiping. Is this possible?

Body:
I solved it this way:

    var editMode = false

...

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

    if editMode == true {
        return true
    } else {
        return false
    }
}

    override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)

    if(editing) {
        tableView.reloadData()
        editMode = true
    }
    else if(!editing) {
        tableView.reloadData()
        editMode = false
    }
}


问:
how to pass array in ajax call using php
I have an array like this

```Array
(
    [0] => 131

    [1] => 103

    [2] => 21

    [3] => 94

    [4] => 107

    [5] => 130

    [6] => 92

    [7] => 128

    [8] => 115

    [9] => 81
)

```

How to pass this array in ajax call

Javascript Code is:

```<code>$(document).ready(function(){
 var recentchatfriendids = [];
//actual array
 $.ajax({
    url: '/friends/message/getmessagestatus';
    data: {
        recentchatfriendids : recentchatfriendids
    },
    success: function(response){
    },
  });
});
</code>```

答:
convert it into json and try it.
hope that works for you.</p>

Body:
I have an array like this

Array
(
    [0] => 131

    [1] => 103

    [2] => 21

    [3] => 94

    [4] => 107

    [5] => 130

    [6] => 92

    [7] => 128

    [8] => 115

    [9] => 81
)

How to pass this array in ajax call

Javascript Code is:

$(document).ready(function(){
 var recentchatfriendids = [];
//actual array
 $.ajax({
    url: '/friends/message/getmessagestatus';
    data: {
        recentchatfriendids : recentchatfriendids
    },
    success: function(response){
    },
  });
});


问:
How to remove a column from an iTextSharp table
In my c# app, I have a function to generate a PDF document using iTextSharp, which includes a table of figures. The table (PdfPTable specifically) is populated and then inserted into the document. After it has been populated, under certain conditions, I would like to remove one of the columns - does anyone know how to do this?

I know I could conditionally exclude cells when populating the table, but this will be quite complex in my situation. Thanks

答:
You can adjust the column width to 0 so it does not appear by using the PdfPTable.SetWidths(float[])

For example

```<code>float[] ColumnWidths = new float[] { 10,0,10,0 };

PdfPTable table = new PdfPTable(ColumnWidths.Length);
table.SetWidths(ColumnWidths);
</code>```

Now column 2 and 4 will no longer appear visually on the PDF, you can change the widths of the table at any point by passing a new float array to it.

ContentLicense: CC BY-SA 2.5

Body:
You can adjust the column width to 0 so it does not appear by using the PdfPTable.SetWidths(float[])

For example

float[] ColumnWidths = new float[] { 10,0,10,0 };

PdfPTable table = new PdfPTable(ColumnWidths.Length);
table.SetWidths(ColumnWidths);

Now column 2 and 4 will no longer appear visually on the PDF, you can change the widths of the table at any point by passing a new float array to it.


问:
How to bring ImageView over the CardView? Please see details
I'm developing an app and I have made the below shown layout:

There is a CircleImageView and a CardView.

Here's the XML code:

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.playrapp.playr.Profile"
    tools:showIn="@layout/activity_profile">

    <android.support.v7.widget.CardView
        android:id="@+id/profileCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        app:contentPadding="10dp">

    </android.support.v7.widget.CardView>

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/userImageProfile"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginTop="50dp"
        android:src="@mipmap/ic_launcher"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>
</code>```

Here, the CardView is over the ImageView. I want ImageView to be over the CardView. How can I do that?

Please let me know.

答:
Elevation of CardView is more higher than CircleImageView. So, you have to set higher elevation to CircleImageView to show it over CardVew.

Set CardView elevation as app:cardElevation="4dp" and set CircleImageView elevation as android:elevation="8dp"

Here is the working XML code. Try this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.CardView
        android:id="@+id/profileCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        app:cardCornerRadius="4dp"
        app:cardElevation="4dp"
        app:cardUseCompatPadding="false" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_marginTop="75dp"
            android:padding="24dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hammad Nasir"
                android:textSize="32sp"
                android:textColor="#727272"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="\@hammadnasir"
                android:textSize="24sp"
                android:textColor="#727272" />

        </LinearLayout>
    </android.support.v7.widget.CardView>

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/userImageProfile"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginTop="75dp"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher"
        android:elevation="8dp" />

</RelativeLayout>
</code>```

OUTPUT:

Hope this will help~

ContentLicense: CC BY-SA 4.0

Body:
I'm developing an app and I have made the below shown layout:

There is a CircleImageView and a CardView.

Here's the XML code:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.playrapp.playr.Profile"
    tools:showIn="@layout/activity_profile">

    <android.support.v7.widget.CardView
        android:id="@+id/profileCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        app:contentPadding="10dp">

    </android.support.v7.widget.CardView>

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/userImageProfile"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginTop="50dp"
        android:src="@mipmap/ic_launcher"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

Here, the CardView is over the ImageView. I want ImageView to be over the CardView. How can I do that?

Please let me know.

Body:
Elevation of CardView is more higher than CircleImageView. So, you have to set higher elevation to CircleImageView to show it over CardVew.

Set CardView elevation as app:cardElevation="4dp" and set CircleImageView elevation as android:elevation="8dp"

Here is the working XML code. Try this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.CardView
        android:id="@+id/profileCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        app:cardCornerRadius="4dp"
        app:cardElevation="4dp"
        app:cardUseCompatPadding="false" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_marginTop="75dp"
            android:padding="24dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hammad Nasir"
                android:textSize="32sp"
                android:textColor="#727272"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="\@hammadnasir"
                android:textSize="24sp"
                android:textColor="#727272" />

        </LinearLayout>
    </android.support.v7.widget.CardView>

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/userImageProfile"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginTop="75dp"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher"
        android:elevation="8dp" />

</RelativeLayout>

OUTPUT:

Hope this will help~


问:
how to update the results of a component's query based on the results of an other component's subscription?
I have 2 react components on the same page,

Component 1 query a list of users

Component 2 subscribe to the event
of creating a new user

I can’t figure out a way to update the results of the component 1 based on the results of component 2's subscription.

Component1:

```<code>class Comp1 extends React.Component {

    render() {
        return (
            <div>
            {this.props.data.loading? <span>loading…</span>
        : <span> //show the list of users </span>       }
        </div>
                    );
    }
}

export default graphql(queryAllUsers)(Comp1) ;
</code>```

Component2 :

```<code>class Comp2 extends React.Component {
   constructor(props) {
     super(props);
        this.state = {
        newUserCreated: false
            }
   }
 subscribeToNewUser() {
    this.subscription = this.props.data.subscribeToMore({
        document: subscribeToNewUsersQuery,
        variables: {//        },
    });
    }
    render() {
        return (
            <div>
            {this.state.newUserCreated}
        </div>
                    );
    }
}
</code>```

答:
The solution is to use a reducer function with query of the first component:

class Comp1 extends React.Component {
  render() { ... }
}

export default graphql(queryAllUsers, {
      options: (ownProps) => {
        return ({
            variables: { ...
            },
            reducer: (previousResult, action) => {
              if (action.type === "APOLLO_SUBSCRIPTION_RESULT" && action.operationName === "subscribeToNewUsersQuery") {
                //update the previousResult
                return previousResultWithNewData;
              } else return previousResult;
            })
        }
      })(Comp1);```

Body:
I have 2 react components on the same page,

Component 1 query a list of users

Component 2 subscribe to the event
of creating a new user

I can’t figure out a way to update the results of the component 1 based on the results of component 2's subscription.

Component1:

class Comp1 extends React.Component {

    render() {
        return (

            {this.props.data.loading? loading…
        :  //show the list of users        }

                    );
    }
}

export default graphql(queryAllUsers)(Comp1) ;

Component2 :

class Comp2 extends React.Component {
   constructor(props) {
     super(props);
        this.state = {
        newUserCreated: false
            }
   }
 subscribeToNewUser() {
    this.subscription = this.props.data.subscribeToMore({
        document: subscribeToNewUsersQuery,
        variables: {//        },
    });
    }
    render() {
        return (

            {this.state.newUserCreated}

                    );
    }
}


问:
WPF Data binding: Changing items in the binded collection does not update binding source?
I have two classes:

```<code>public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }
    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            ObservableCollection<AccountDetail> phones;
            phones = new ObservableCollection<AccountDetail>();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            ObservableCollection<AccountDetail> phones;
            phones = value;
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }
            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
}
</code>```

and

```<code>public class AccountDetail
{
    public DetailType Type
    {
        get { return type; }
        set { type = value; }
    }
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailType type;
    private string value;
}
</code>```

In my XAML file I have a ListBox named PhonesListBox which is data bound to the phones list (a property of the Person object):

```<code><Window.Resources>

    <!-- Window controller -->
    <contollers:PersonWindowController
        x:Key="WindowController" />

</Window.Resources>

...

<ListBox
    Name="PhonesListBox"
    Margin="0,25,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top"
    ItemsSource="{Binding Path=SelectedPerson.Phones,
                  Source={StaticResource ResourceKey=WindowController}}"
    HorizontalContentAlignment="Stretch" />

...
</code>```

In its code behind class, there's a handler for a button which adds a new item to that PhonesListBox:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<AccountDetail> phones;

    phones = (ObservableCollection<AccountDetail>)PhonesListBox.ItemsSource;
    phones.Add(new AccountDetail(DetailType.Phone));
}
</code>```

The problem is, the newly added list box item is not added in the person's details observable collection, i.e. the Phones property is not updated (set is never called). Why? Where am I making a mistake?

Thanks for all the help.

UPDATE: I changed the AddPhoneButton_Click method to:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    details = windowController.SelectedPerson.Details;
    details.Add(new AccountDetail(DetailType.Phone));
}
</code>```

This updates the appropriate collection, which is details not Phones (as phones is just a view or a getter of a subset of detail items). Also, I realized I don't even need the Phones setter. The problem I am facing now is that my UI is not updated with the changes made to the details collection (and subsequently phones). I don't know how or where to call for the property changed as neither details nor phones are changing; their collection members are. Help. Please.

答:
it sounds like you have an ObservableCollection<AccountDetail> with more than just phones in it, so it looks like you actually need a CollectionViewSource with a Filter added:

```<code>public class Person
{
    public ObservableCollection<AccountDetail> Details { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

<Window.Resources>
    <CollectionViewSource x:Key="phonesSource"
        Source="{StaticResource ResourceKey=WindowController}"
            Path="SelectedPerson.Details"  />
</Window.Resources>
<Grid>
    <ListBox
        Name="PhonesListBox"
        Margin="0,25,0,0"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Top"
        ItemsSource="{Binding Source={StaticResource phonesSource}}"
        HorizontalContentAlignment="Stretch" />
</Grid>

public MainWindow()
{
    InitializeComponent();
    CollectionViewSource source =
        (CollectionViewSource)FindResource("phonesSource");
    source.Filter += (o, e) =>
            {
                if (((AccountDetail) e.Item).Type == DetailType.Phone)
                    e.Accepted = true;
            };
}
</code>```

Body:
I have two classes:

public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }
    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            ObservableCollection<AccountDetail> phones;
            phones = new ObservableCollection<AccountDetail>();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            ObservableCollection<AccountDetail> phones;
            phones = value;
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }
            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
}

and

public class AccountDetail
{
    public DetailType Type
    {
        get { return type; }
        set { type = value; }
    }
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailType type;
    private string value;
}

In my XAML file I have a ListBox named PhonesListBox which is data bound to the phones list (a property of the Person object):

<Window.Resources>

    <contollers:PersonWindowController
        x:Key="WindowController" />

</Window.Resources>

...

<ListBox
    Name="PhonesListBox"
    Margin="0,25,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top"
    ItemsSource="{Binding Path=SelectedPerson.Phones,
                  Source={StaticResource ResourceKey=WindowController}}"
    HorizontalContentAlignment="Stretch" />

...

In its code behind class, there's a handler for a button which adds a new item to that PhonesListBox:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<AccountDetail> phones;

    phones = (ObservableCollection<AccountDetail>)PhonesListBox.ItemsSource;
    phones.Add(new AccountDetail(DetailType.Phone));
}

The problem is, the newly added list box item is not added in the person's details observable collection, i.e. the Phones property is not updated (set is never called). Why? Where am I making a mistake?

Thanks for all the help.

UPDATE: I changed the AddPhoneButton_Click method to:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    details = windowController.SelectedPerson.Details;
    details.Add(new AccountDetail(DetailType.Phone));
}

This updates the appropriate collection, which is details not Phones (as phones is just a view or a getter of a subset of detail items). Also, I realized I don't even need the Phones setter. The problem I am facing now is that my UI is not updated with the changes made to the details collection (and subsequently phones). I don't know how or where to call for the property changed as neither details nor phones are changing; their collection members are. Help. Please.

Body:
it sounds like you have an ObservableCollection<AccountDetail> with more than just phones in it, so it looks like you actually need a CollectionViewSource with a Filter added:

public class Person
{
    public ObservableCollection<AccountDetail> Details { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

<Window.Resources>
    <CollectionViewSource x:Key="phonesSource"
        Source="{StaticResource ResourceKey=WindowController}"
            Path="SelectedPerson.Details"  />
</Window.Resources>
<Grid>
    <ListBox
        Name="PhonesListBox"
        Margin="0,25,0,0"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Top"
        ItemsSource="{Binding Source={StaticResource phonesSource}}"
        HorizontalContentAlignment="Stretch" />
</Grid>

public MainWindow()
{
    InitializeComponent();
    CollectionViewSource source =
        (CollectionViewSource)FindResource("phonesSource");
    source.Filter += (o, e) =>
            {
                if (((AccountDetail) e.Item).Type == DetailType.Phone)
                    e.Accepted = true;
            };
}


问:
How to determine if DataTable is null, not initialized
I have a method that does some work on a DataTable e.g.

```<code>private void MyMethod(DataTable table)
{
    if(table.Rows.Count > 0)
    {
       //  do some work
    }
 }
</code>```

However, if the method receives a null datatable from the application it serves I get an 'Object reference not set to an instance of an object' error.

I have also tried . . .

```<code>if(table.IsInitialized) { }
</code>```

and

```<code>if(table != null) {  }
</code>```

but I get the same error message.

How do I test to see if the incoming datatable is instantiated and not null please?

The DataTable is coming from a cast of a datagrid in a WinForms app i.e.

```<code>DataTable table = (DataTable)datagridview.DataSource;
</code>```

So the issue arises if the original datagridview is empty.

答:
You get the "reference not set to a instance of object" exception if you got a case like this:

```<code>object someObject = null;
//Throws an exception. You try to call a instance function without specify the instance
someObject.ToString();
</code>```

So either table is null or rows returns null.
Prior to C# 6.0 you have to go the hard way:

```<code>if(table != null && table.Rows != null && table.Rows.Count > 0)
</code>```

I assumed count was not a nullable Integer. If it was, you have to check for it being null too of course.

At least for debugging, you might want to write that code a bit more verbose with a "one operation per line" rule.
That would help you locate which operation exactly returns null. And the JiT will most likely cut out the temporary variables outside of debug runs anyway.

```<code>//If table is null, exception here
var Row = table.Row;
//If Row is null, Exception here.
var Count = Row.Count;
//Nothing is null. Continue.
if(Count > 0);
</code>```

With C# 6.0, you got the new Null conditional operator to write it a bit shorter:
https://msdn.microsoft.com/en-us/library/dn986595.aspx
It is still the same code, however.

Body:
I have a method that does some work on a DataTable e.g.

private void MyMethod(DataTable table)
{
    if(table.Rows.Count > 0)
    {
       //  do some work
    }
 }

However, if the method receives a null datatable from the application it serves I get an 'Object reference not set to an instance of an object' error.

I have also tried . . .

if(table.IsInitialized) { }

and

if(table != null) {  }

but I get the same error message.

How do I test to see if the incoming datatable is instantiated and not null please?

The DataTable is coming from a cast of a datagrid in a WinForms app i.e.

DataTable table = (DataTable)datagridview.DataSource;

So the issue arises if the original datagridview is empty.

Body:
You get the "reference not set to a instance of object" exception if you got a case like this:

object someObject = null;
//Throws an exception. You try to call a instance function without specify the instance
someObject.ToString();

So either table is null or rows returns null.
Prior to C# 6.0 you have to go the hard way:

if(table != null && table.Rows != null && table.Rows.Count > 0)

I assumed count was not a nullable Integer. If it was, you have to check for it being null too of course.

At least for debugging, you might want to write that code a bit more verbose with a "one operation per line" rule.
That would help you locate which operation exactly returns null. And the JiT will most likely cut out the temporary variables outside of debug runs anyway.

//If table is null, exception here
var Row = table.Row;
//If Row is null, Exception here.
var Count = Row.Count;
//Nothing is null. Continue.
if(Count > 0);

With C# 6.0, you got the new Null conditional operator to write it a bit shorter:
https://msdn.microsoft.com/en-us/library/dn986595.aspx
It is still the same code, however.


问:
How do you compile the Hello World program for Java?
I am at step 6 in the process of installing JDK onto windows using instructions from  this website .

When I attempt to “Set the Current Drive to the drive where you saved your source file Hello.java” by typing “c:”, nothing happens (the instructions indicate that something like C:\xxx> should appear).

I have saved the hello world file in the C: directory as indicated in the previous step (step 5).

I am trying to start learning Java and any help would be appreciated.

答:
I would suggest you to go for an IDE like eclipse or Netbeans for learning Java as you are learning you should focus more on language basics than configuration  try use Eclipse IDE its opensource and very good for Java development and my preference too .

http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/marsr

Try this link which makes Hello world easy

http://www.java-made-easy.com/java-hello-world.html

To write a "Hello World" program follow these steps:

```<code>Start Eclipse.
Create a new Java Project:
File->New->Project.
Select "Java" in the category list.
Select "Java Project" in the project list. Click "Next".
Enter a project name into the Project name field, for example, "Hello World Project".
Click "Finish"--It will ask you if you want the Java perspective to open. (You do.)
Create a new Java class:
Click the "Create a Java Class" button in the toolbar. (This is the icon below "Run" and "Window" with a tooltip that says "New Java Class.")
Enter "HelloWorld" into the Name field.
Click the checkbox indicating that you would like Eclipse to create a "public static void main(String[] args)" method.
Click "Finish".
A Java editor for HelloWorld.java will open. In the main method enter the following line.
     System.out.println("Hello World");
Save using ctrl-s. This automatically compiles HelloWorld.java.
Click the "Run" button in the toolbar (looks like a little man running).
You will be prompted to create a Launch configuration. Select "Java Application" and click "New".
Click "Run" to run the Hello World program. The console will open and display "Hello World".
</code>```

Body:
I would suggest you to go for an IDE like eclipse or Netbeans for learning Java as you are learning you should focus more on language basics than configuration  try use Eclipse IDE its opensource and very good for Java development and my preference too .

http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/marsr

Try this link which makes Hello world easy

http://www.java-made-easy.com/java-hello-world.html

To write a "Hello World" program follow these steps:

Start Eclipse.
Create a new Java Project:
File->New->Project.
Select "Java" in the category list.
Select "Java Project" in the project list. Click "Next".
Enter a project name into the Project name field, for example, "Hello World Project".
Click "Finish"--It will ask you if you want the Java perspective to open. (You do.)
Create a new Java class:
Click the "Create a Java Class" button in the toolbar. (This is the icon below "Run" and "Window" with a tooltip that says "New Java Class.")
Enter "HelloWorld" into the Name field.
Click the checkbox indicating that you would like Eclipse to create a "public static void main(String[] args)" method.
Click "Finish".
A Java editor for HelloWorld.java will open. In the main method enter the following line.
     System.out.println("Hello World");
Save using ctrl-s. This automatically compiles HelloWorld.java.
Click the "Run" button in the toolbar (looks like a little man running).
You will be prompted to create a Launch configuration. Select "Java Application" and click "New".
Click "Run" to run the Hello World program. The console will open and display "Hello World".


问:
Parsing a file in backward and forward direction
I have a very long file with a periodical structure (the three dots resembles numbers of lines not necessarily equal, and n is just an index):

```<code>...
string bar text1 (n-2)
...
string bar text1 (n-1)
...
string bar text1 (n)
...
STRING FOO
elements1
elements1
...
string bar text2 (n-2)
...
string bar text2 (n-1)
...
string bar text2 (n)
...
STRING FOO
elements2
elements2
...
</code>```

I am trying to make a bash script to parse this file, and print to another file the following information: find all the appearances of STRING FOO and print to the new file the elements (which can be two, for example) plus the string bar n. In order to achieve that, I have tried the following commands:

```<code>grep -A 2 "STRING FOO"  input_file.txt   >> output_file.txt
grep -B 200 "STRING FOO" input_file.txt | tac | sed -n '/'string bar n'/ { p ; q }' >> output_file.txt
</code>```

Expected output:

```<code>STRING FOO
elements1
elements1
string bar text1
STRING FOO
elements2
elements2
string bar text2
</code>```

Where the number 200 is just a "guess" of how many lines I need to go back. Those commands, besides inefficient, are not working properly. I would really appreciate someone else's help.

答:
You can use this all in one gung-ho Awk command, for this,

```<code>awk '/string bar/{ pat=$0; }/\<STRING FOO\>/{c=NR+2}(NR<=c){print}(NR==c){print pat}' file
</code>```

which outputs only the lines below as you needed,

```<code>STRING FOO
elements1
elements1
string bar text1 (n)
STRING FOO
elements2
elements2
string bar text2 (n)
</code>```

Body:
I have a very long file with a periodical structure (the three dots resembles numbers of lines not necessarily equal, and n is just an index):

...
string bar text1 (n-2)
...
string bar text1 (n-1)
...
string bar text1 (n)
...
STRING FOO
elements1
elements1
...
string bar text2 (n-2)
...
string bar text2 (n-1)
...
string bar text2 (n)
...
STRING FOO
elements2
elements2
...

I am trying to make a bash script to parse this file, and print to another file the following information: find all the appearances of STRING FOO and print to the new file the elements (which can be two, for example) plus the string bar n. In order to achieve that, I have tried the following commands:

grep -A 2 "STRING FOO"  input_file.txt   >> output_file.txt
grep -B 200 "STRING FOO" input_file.txt | tac | sed -n '/'string bar n'/ { p ; q }' >> output_file.txt

Expected output:

STRING FOO
elements1
elements1
string bar text1
STRING FOO
elements2
elements2
string bar text2

Where the number 200 is just a "guess" of how many lines I need to go back. Those commands, besides inefficient, are not working properly. I would really appreciate someone else's help.

Body:
You can use this all in one gung-ho Awk command, for this,

awk '/string bar/{ pat=$0; }/\<STRING FOO\>/{c=NR+2}(NR<=c){print}(NR==c){print pat}' file

which outputs only the lines below as you needed,

STRING FOO
elements1
elements1
string bar text1 (n)
STRING FOO
elements2
elements2
string bar text2 (n)


问:
how to define an array of IPs in Elasticsearch?
I am using Elasticsearch 5.3. In an index, I want to define a field as an array of ip fields. How do I define this in a mapping?

答:
You should use ip data type:

```<code>PUT my_index
{
  "mappings": {
    "my_type": {
      "properties": {
        "ip_addr": {
          "type": "ip"
        }
      }
    }
  }
}
</code>```

Official docs for ip data type

Body:
You should use ip data type:

PUT my_index
{
  "mappings": {
    "my_type": {
      "properties": {
        "ip_addr": {
          "type": "ip"
        }
      }
    }
  }
}

Official docs for ip data type


问:
Error with styling control in XAML "Expression type is not a valid Style value"
The error I receive indicate that I use invalid expression type in my XAML code which is marked as  in the code below:

```<code>    <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:RDictionary="clr-namespace:DLLCustomExtension;assembly=DLLCustomExtension">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary RDictionary:MDExtension.Name="ColorBrushes" Source="Solidbrushes.xaml" />
    </ResourceDictionary.MergedDictionaries>

    <Style x:Key="PrimaryNavToggleButtons" TargetType="{x:Type ToggleButton}">
        <Setter Property="Background" Value="{StaticResource PrimaryNavButtonsBackcolor}" />
        <Setter Property="BorderBrush" Value="{x:Null}" />
        <Setter Property="Foreground" Value="{StaticResource PrimaryNavButtonsForeground}" />
        <Setter Property="HorizontalContentAlignment" Value="Center" />
        <Setter Property="VerticalContentAlignment" Value="Center" />
        <Setter Property="VerticalAlignment" Value="Stretch" />
        <Setter Property="HorizontalAlignment" Value="Stretch" />
        <Setter Property="Margin" Value="3" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}"> <!-- Error start -->
                    <Border
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        CornerRadius="5">
                        <Grid>
                            <ContentPresenter
                                x:Name="ContentPresenter"
                                x:Uid="ContentPresenter"
                                Visibility="Visible" />
                            <AdornerDecorator />
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsMouseOver" Value="True" />
                                <Condition Property="IsChecked" Value="False" />
                            </MultiTrigger.Conditions>
                            <MultiTrigger.Setters>
                                <Setter Property="Background" Value="{StaticResource PrimaryNavButtonHovBackcolor}" />
                            </MultiTrigger.Setters>
                        </MultiTrigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsMouseOver" Value="False" />
                                <Condition Property="IsChecked" Value="False" />
                            </MultiTrigger.Conditions>
                            <MultiTrigger.Setters>
                                <Setter Property="Background" Value="{TemplateBinding Background}" />
                            </MultiTrigger.Setters>
                        </MultiTrigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsMouseOver" Value="True" />
                                <Condition Property="IsChecked" Value="True" />
                            </MultiTrigger.Conditions>
                            <MultiTrigger.Setters>
                                <Setter Property="Background" Value="{StaticResource PrimaryNavButtonHovBackcolor}" />
                            </MultiTrigger.Setters>
                        </MultiTrigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsMouseOver" Value="False" />
                                <Condition Property="IsChecked" Value="True" />
                            </MultiTrigger.Conditions>
                            <MultiTrigger.Setters>
                                <Setter Property="Background" Value="{StaticResource PrimaryNavButtonHovBackcolor}" />
                            </MultiTrigger.Setters>
                        </MultiTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate> <!-- Error end -->
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
</code>```

So what I did wrong? Thank.

答:
```<code><Setter Property="Background" Value="{TemplateBinding Background}" />
</code>```

This line generates error. TemplateBinding doesn't work in ContentTemplate Trigger setter. It should written using Binding with RelativeSource TemplatedParent.

```<code><Setter Property="Background"
        Value="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" />
</code>```

However I don't understand the purpose of that line. There is already {TemplateBinding Background} in Template part. Why repeat it in a Trigger?

Body:
The error I receive indicate that I use invalid expression type in my XAML code which is marked as  in the code below:

    <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:RDictionary="clr-namespace:DLLCustomExtension;assembly=DLLCustomExtension">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary RDictionary:MDExtension.Name="ColorBrushes" Source="Solidbrushes.xaml" />
    </ResourceDictionary.MergedDictionaries>

</ResourceDictionary>

So what I did wrong? Thank.

Body:
<Setter Property="Background" Value="{TemplateBinding Background}" />

This line generates error. TemplateBinding doesn't work in ContentTemplate Trigger setter. It should written using Binding with RelativeSource TemplatedParent.

<Setter Property="Background"
        Value="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" />

However I don't understand the purpose of that line. There is already {TemplateBinding Background} in Template part. Why repeat it in a Trigger?


问:
JSON code to display Multidimensional array using php mysql
I am trying to display multidimensional array in JSON using php and mysql.How to display an multidimensional array in JSON. I am new to JSON code.. I want my JSON code to display in this way

```<code>{"staffdirectory": [
        {
            "teachingstaff":[
                       {
                           "deptA":[
                               {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }]
                       },

                       {
                           "deptB":[
                                {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }
                                ]
                                {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }
                                ]
                       },
                       ]
        },
        {
            "non-teachingstaff":[
                       {
                           "principalA":[
                               {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }
                                ]
                       },

                       {
                           "principalB":[
                                {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }
                                ]
                       },
 ]
        }
    ]
    }
</code>```

I need to create an array for staff which contains teaching and non teaching in again in staff i need to create different departments and again an array to lecturers In each department..

Here is the code

```<code><?php
include_once "db.php";

    if(isset($_POST['updated_date'])) {
        // get all products from products table
        $result = mysql_query("select lecturers1.lname,department1.name,staff_directory1.role
 from lecturers1
  inner join department1 on lecturers1.dept_key=department1.key
  inner join staff_directory1 on lecturers1.sd_key=staff_directory1.key") or die(mysql_error());
    }else{
        // get all products from products table
        $result = mysql_query("select lecturers1.lname,department1.name,staff_directory1.role
 from lecturers1
  inner join department1 on lecturers1.dept_key=department1.key
  inner join staff_directory1 on lecturers1.sd_key=staff_directory1.key") or die(mysql_error());

    }

    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results items node
        $response["staff"] = array();
        while ($row = mysql_fetch_array($result)) {
            // temp user array
            $news = array();

            $news["role"]=$row["role"];
              $dept = array();

            $dept["name"]=$row["name"];
            $lecturer1=array();
            $lecturer1["lname"]=$row["lname"];
            $news['lecturer1']=json_encode($lecturer1);
            $news['dept']=json_encode($dept);
        array_push($response["staff"], $news);

            // push single product into final response array

        }

        // success
        $response["success"] = 1;
        $response["message"] = mysql_num_rows($result)." items found";
        // echoing JSON response
        echo json_encode($response);
    } else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No newsitems found";
        // echo no users JSON
        echo json_encode($response);
    }
   mysql_close($conn);
?>
</code>```

My JSON code displays this way

```<code>"staff": [
  {
"role": "Teaching",
"lecturer1": "{"lname":"c1"}",
"dept": "{"name":"computer science"}"
},
  {
"role": "Teaching",
"lecturer1": "{"lname":"c2"}",
"dept": "{"name":"computer science"}"
},
  {
"role": "Teaching",
"lecturer1": "{"lname":"e1"}",
"dept": "{"name":"english"}"
},
</code>```

答:
Use json_decode() to convert JSon data to multi dimension array.
When TRUE, returned objects will be converted into associative arrays.

print_r(json_decode(json_array, true));

Body:
I am trying to display multidimensional array in JSON using php and mysql.How to display an multidimensional array in JSON. I am new to JSON code.. I want my JSON code to display in this way

{"staffdirectory": [
        {
            "teachingstaff":[
                       {
                           "deptA":[
                               {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }]
                       },

                       {
                           "deptB":[
                                {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }
                                ]
                                {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }
                                ]
                       },
                       ]
        },
        {
            "non-teachingstaff":[
                       {
                           "principalA":[
                               {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }
                                ]
                       },

                       {
                           "principalB":[
                                {
                                  "name":"xxxxxxxxx",
                                  "email":"xxxxxxxx",
                                  "designation":"xxxxxxx"
                                }
                                ]
                       },
 ]
        }
    ]
    }

I need to create an array for staff which contains teaching and non teaching in again in staff i need to create different departments and again an array to lecturers In each department..

Here is the code

<?php
include_once "db.php";

    if(isset($_POST['updated_date'])) {
        // get all products from products table
        $result = mysql_query("select lecturers1.lname,department1.name,staff_directory1.role
 from lecturers1
  inner join department1 on lecturers1.dept_key=department1.key
  inner join staff_directory1 on lecturers1.sd_key=staff_directory1.key") or die(mysql_error());
    }else{
        // get all products from products table
        $result = mysql_query("select lecturers1.lname,department1.name,staff_directory1.role
 from lecturers1
  inner join department1 on lecturers1.dept_key=department1.key
  inner join staff_directory1 on lecturers1.sd_key=staff_directory1.key") or die(mysql_error());

    }

    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results items node
        $response["staff"] = array();
        while ($row = mysql_fetch_array($result)) {
            // temp user array
            $news = array();

            $news["role"]=$row["role"];
              $dept = array();

            $dept["name"]=$row["name"];
            $lecturer1=array();
            $lecturer1["lname"]=$row["lname"];
            $news['lecturer1']=json_encode($lecturer1);
            $news['dept']=json_encode($dept);
        array_push($response["staff"], $news);

            // push single product into final response array

        }

        // success
        $response["success"] = 1;
        $response["message"] = mysql_num_rows($result)." items found";
        // echoing JSON response
        echo json_encode($response);
    } else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No newsitems found";
        // echo no users JSON
        echo json_encode($response);
    }
   mysql_close($conn);
?>

My JSON code displays this way

"staff": [
  {
"role": "Teaching",
"lecturer1": "{"lname":"c1"}",
"dept": "{"name":"computer science"}"
},
  {
"role": "Teaching",
"lecturer1": "{"lname":"c2"}",
"dept": "{"name":"computer science"}"
},
  {
"role": "Teaching",
"lecturer1": "{"lname":"e1"}",
"dept": "{"name":"english"}"
},


问:
php string to date conversion from multiple date format
I want to convert the string date to following format 'Y-m-d' from multiple date format like for example

12-3-17,
12-3-2017,
12.3.17,
12.3.2017,
12.03.17,
12/3/17

```<code>$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');
</code>```

The closest solution that i got so far is from the following article read the article here

is there a better solution, considering the fact that the input date string may be in unknown format ?

答:
I hope this might help you. In dateFormat() function you can assign different type of valid format.

```<code>function dateFormat() {
    $date_format['d.m.Y'] = 'd.m.Y';
    $date_format['d.m.y'] = 'd.m.y';
    $date_format['d-m-Y'] = 'd-m-Y';
    $date_format['d-m-y'] = 'd-m-y';
    $date_format['d/m/Y'] = 'd/m/Y';
    $date_format['d/m/y'] = 'd/m/y';

    return $date_format;
}
</code>```

After that you use this function as below code

```<code>$source = '2017-03-31';
$date = new DateTime($source);
$date_format = dateFormat();
foreach($date_format as $k => $v) {
    $date_list[] = $date->format($k);
}
print_r($date_list);
exit;
</code>```

Output:-

```<code>Array
(
    [0] => 31.03.2017
    [1] => 31.03.17
    [2] => 31-03-2017
    [3] => 31-03-17
    [4] => 31/03/2017
    [5] => 31/03/17
)
</code>```

Live Demo

Body:
I want to convert the string date to following format 'Y-m-d' from multiple date format like for example

12-3-17,
12-3-2017,
12.3.17,
12.3.2017,
12.03.17,
12/3/17

$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');

The closest solution that i got so far is from the following article read the article here

is there a better solution, considering the fact that the input date string may be in unknown format ?

Body:
I hope this might help you. In dateFormat() function you can assign different type of valid format.

function dateFormat() {
    $date_format['d.m.Y'] = 'd.m.Y';
    $date_format['d.m.y'] = 'd.m.y';
    $date_format['d-m-Y'] = 'd-m-Y';
    $date_format['d-m-y'] = 'd-m-y';
    $date_format['d/m/Y'] = 'd/m/Y';
    $date_format['d/m/y'] = 'd/m/y';

    return $date_format;
}

After that you use this function as below code

$source = '2017-03-31';
$date = new DateTime($source);
$date_format = dateFormat();
foreach($date_format as $k => $v) {
    $date_list[] = $date->format($k);
}
print_r($date_list);
exit;

Output:-

Array
(
    [0] => 31.03.2017
    [1] => 31.03.17
    [2] => 31-03-2017
    [3] => 31-03-17
    [4] => 31/03/2017
    [5] => 31/03/17
)

Live Demo


问:
Java Web Start application gets unrestricted access but still asks for permission
I have a Java Web Start (Java 8u121) application that should  run with full access on the users system.

All requirements to run with full access have been taken, basically we are using webstart-maven-plugin to sign the full application (all jars) with an official certificate. The JNLP requests 'all-permissions'. This also sets several properties to the MANIFEST.MF in each jar.

When I start the application (see image) it requests 'unrestricted access'.

When running the application, it tries to download a few images from another webserver, this always causes the following dialog:

The stacktrace of the thread showing the dialog is as follows:

```<code>  java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at com.sun.javaws.ui.JavawsSysRun.delegate(Unknown Source)
    - locked <0x0000000081e16908> (a java.lang.Object)
    at com.sun.deploy.util.DeploySysRun.execute(Unknown Source)
    at com.sun.deploy.util.DeploySysRun$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.util.DeploySysRun.executePrivileged(Unknown Source)
    at com.sun.deploy.ui.UIFactory.showApiDialog(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.ui.UIFactoryImpl.showMessageDialog(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.ui.UIFactoryImpl.showMessageDialog(Unknown Source)
    at com.sun.jnlp.ApiDialog.askUser(Unknown Source)
    at com.sun.jnlp.ApiDialog.askUser(Unknown Source)
    at com.sun.jnlp.ApiDialog.askConnect(Unknown Source)
    at com.sun.javaws.security.JavaWebStartSecurity.checkURLPermissionHelper(Unknown Source)
    at com.sun.javaws.security.JavaWebStartSecurity.checkPermission(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.URLtoSocketPermission(Unknown Source)

...

    at java.util.concurrent.CompletableFuture$AsyncSupply.run(Unknown Source)
    at java.util.concurrent.CompletableFuture$AsyncSupply.exec(Unknown Source)
    at java.util.concurrent.ForkJoinTask.doExec(Unknown Source)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(Unknown Source)
    at java.util.concurrent.ForkJoinPool.runWorker(Unknown Source)
    at java.util.concurrent.ForkJoinWorkerThread.run(Unknown Source)
</code>```

The biggest problem with this is that the dialog asking for permission often appears behind our main screen (but it will still block input to the main screen).

I have been able to trace this problem to the ForkJoinPool. Which apparently always runs with extra protection. See this post by Doug Lea.

What is the best way to disable this? I would prefer this to be an application wide solution.

答: You have mentioned here , Images are getting downloaded from another web server , means a new untrusted connection is getting fired from jvm. which cause jvm to invoke a security prompt. If you want to avoid this popup dialog ,simply embed your images in the jar file and move to the web server directory hosting your java web start application .Then, add this jar file in resource tag with lazy download strategy. Finally, use DownloadService service implementation to load jar file resource when needed.

Body:
I have a Java Web Start (Java 8u121) application that should  run with full access on the users system.

All requirements to run with full access have been taken, basically we are using webstart-maven-plugin to sign the full application (all jars) with an official certificate. The JNLP requests 'all-permissions'. This also sets several properties to the MANIFEST.MF in each jar.

When I start the application (see image) it requests 'unrestricted access'.

When running the application, it tries to download a few images from another webserver, this always causes the following dialog:

The stacktrace of the thread showing the dialog is as follows:

  java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at com.sun.javaws.ui.JavawsSysRun.delegate(Unknown Source)
    - locked <0x0000000081e16908> (a java.lang.Object)
    at com.sun.deploy.util.DeploySysRun.execute(Unknown Source)
    at com.sun.deploy.util.DeploySysRun$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.util.DeploySysRun.executePrivileged(Unknown Source)
    at com.sun.deploy.ui.UIFactory.showApiDialog(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.ui.UIFactoryImpl.showMessageDialog(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.ui.UIFactoryImpl.showMessageDialog(Unknown Source)
    at com.sun.jnlp.ApiDialog.askUser(Unknown Source)
    at com.sun.jnlp.ApiDialog.askUser(Unknown Source)
    at com.sun.jnlp.ApiDialog.askConnect(Unknown Source)
    at com.sun.javaws.security.JavaWebStartSecurity.checkURLPermissionHelper(Unknown Source)
    at com.sun.javaws.security.JavaWebStartSecurity.checkPermission(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.URLtoSocketPermission(Unknown Source)

...

    at java.util.concurrent.CompletableFuture$AsyncSupply.run(Unknown Source)
    at java.util.concurrent.CompletableFuture$AsyncSupply.exec(Unknown Source)
    at java.util.concurrent.ForkJoinTask.doExec(Unknown Source)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(Unknown Source)
    at java.util.concurrent.ForkJoinPool.runWorker(Unknown Source)
    at java.util.concurrent.ForkJoinWorkerThread.run(Unknown Source)

The biggest problem with this is that the dialog asking for permission often appears behind our main screen (but it will still block input to the main screen).

I have been able to trace this problem to the ForkJoinPool. Which apparently always runs with extra protection. See this post by Doug Lea.

What is the best way to disable this? I would prefer this to be an application wide solution.


问:
Filtering a MultiIndex Pandas DataFrame
I have a MultiIndex Pandas DataFrame that looks like the following:

```<code>import pandas as pd
import numpy as np

genotype_data = [
                    ['0/1', '120,60', 180, 5, 0.5, '0/1', '200,2', 202, 99, 0.01],
                    ['0/1', '200,20', 60, 99, 0.1, '0/1', '200,50', 250, 99, 0.4],
                    ['0/1', '200,2', 202, 99, 0.01, '0/1', '200,2', 202, 99, 0.01]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ', 'AB']]
cols = pd.MultiIndex.from_product(genotype_columns)
genotype = pd.DataFrame(data=genotype_data, columns=cols)

info_columns = [['INFO'], ['AC', 'DEPTH']]
cols = pd.MultiIndex.from_product(info_columns)
info = pd.DataFrame(data=[[12, 100], [23, 200], [40, 40]], columns=cols)

df = pd.concat([info, genotype], axis=1)
</code>```

I want to filter the df for any rows where at least one of the Samples (Sample1 or Sample2 in this case) has a DP >= 50 & GQ < 4. Under these conditions all rows should be filtered out except the first row.

I have no idea where to start with this and would appreciate some help.

EDIT:

I arrived at a solution thanks to the help of jezrael's post. The code is as follows:

```<code>genotype = df.ix[:,3:]

DP = genotype.xs('DP', axis=1, level=1)
GQ = genotype.xs('GQ', axis=1, level=1)

conditions = (DP.ge(50) & GQ.le(4)).T.any()
df = df[conditions]

return df
</code>```

答:
stack the first level and use query to identify indices

```<code>df.loc[df.stack(0).query('DP >= 50 & GQ < 4').unstack().index]

  INFO       Sample1                     Sample2
    AC DEPTH      GT      AD  DP GQ   AB      GT      AD   DP  GQ   AB
1   23   200     0/1  200,20  60  3  0.1     0/1  200,50  250  99  0.4
</code>```

I used @jezrael's setup

```<code>genotype_data = [
                    ['0/1', '120,60', 180, 5, 0.5, '0/1', '200,2', 202, 99, 0.01],
                    ['0/1', '200,20', 60, 3, 0.1, '0/1', '200,50', 250, 99, 0.4],
                    ['0/1', '200,2', 202, 99, 0.01, '0/1', '200,2', 202, 99, 0.01]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ', 'AB']]
cols = pd.MultiIndex.from_product(genotype_columns)
genotype = pd.DataFrame(data=genotype_data, columns=cols)

info_columns = [['INFO'], ['AC', 'DEPTH']]
cols = pd.MultiIndex.from_product(info_columns)
info = pd.DataFrame(data=[[12, 100], [23, 200], [40, 40]], columns=cols)

df = pd.concat([info, genotype], axis=1)
</code>```

Title: Filtering a MultiIndex Pandas DataFrame

Body:
I have a MultiIndex Pandas DataFrame that looks like the following:

import pandas as pd
import numpy as np

genotype_data = [
                    ['0/1', '120,60', 180, 5, 0.5, '0/1', '200,2', 202, 99, 0.01],
                    ['0/1', '200,20', 60, 99, 0.1, '0/1', '200,50', 250, 99, 0.4],
                    ['0/1', '200,2', 202, 99, 0.01, '0/1', '200,2', 202, 99, 0.01]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ', 'AB']]
cols = pd.MultiIndex.from_product(genotype_columns)
genotype = pd.DataFrame(data=genotype_data, columns=cols)

info_columns = [['INFO'], ['AC', 'DEPTH']]
cols = pd.MultiIndex.from_product(info_columns)
info = pd.DataFrame(data=[[12, 100], [23, 200], [40, 40]], columns=cols)

df = pd.concat([info, genotype], axis=1)

I want to filter the df for any rows where at least one of the Samples (Sample1 or Sample2 in this case) has a DP >= 50 & GQ < 4. Under these conditions all rows should be filtered out except the first row.

I have no idea where to start with this and would appreciate some help.

EDIT:

I arrived at a solution thanks to the help of jezrael's post. The code is as follows:

genotype = df.ix[:,3:]

DP = genotype.xs('DP', axis=1, level=1)
GQ = genotype.xs('GQ', axis=1, level=1)

conditions = (DP.ge(50) & GQ.le(4)).T.any()
df = df[conditions]

return df

Body:
stack the first level and use query to identify indices

df.loc[df.stack(0).query('DP >= 50 & GQ < 4').unstack().index]

  INFO       Sample1                     Sample2
    AC DEPTH      GT      AD  DP GQ   AB      GT      AD   DP  GQ   AB
1   23   200     0/1  200,20  60  3  0.1     0/1  200,50  250  99  0.4

I used @jezrael's setup

genotype_data = [
                    ['0/1', '120,60', 180, 5, 0.5, '0/1', '200,2', 202, 99, 0.01],
                    ['0/1', '200,20', 60, 3, 0.1, '0/1', '200,50', 250, 99, 0.4],
                    ['0/1', '200,2', 202, 99, 0.01, '0/1', '200,2', 202, 99, 0.01]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ', 'AB']]
cols = pd.MultiIndex.from_product(genotype_columns)
genotype = pd.DataFrame(data=genotype_data, columns=cols)

info_columns = [['INFO'], ['AC', 'DEPTH']]
cols = pd.MultiIndex.from_product(info_columns)
info = pd.DataFrame(data=[[12, 100], [23, 200], [40, 40]], columns=cols)

df = pd.concat([info, genotype], axis=1)


问:
Area Chart with overlapping series in highcharts, overlap point behaving strangely
fiddle: http://jsfiddle.net/nz343opa/

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Stacked Area Chart</title>
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>

</head>
<body>
    <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
<script>
        Highcharts.chart('container', {
            chart: {
                type: 'area'
            },
            title: {
                text: 'Historic and Estimated Worldwide Population Growth by Region'
            },
            subtitle: {
                text: 'Source: Wikipedia.org'
            },
            xAxis: {
                categories: ['1750', '1800', '1850', '1900', '1950', '1999', '2050'],
                tickmarkPlacement: 'on',
                title: {
                    enabled: false
                }
            },
            yAxis: {
                title: {
                    text: 'Billions'
                },
                labels: {
                    formatter: function () {
                        return this.value / 1000;
                    }
                }
            },
            tooltip: {
                split: true,
                valueSuffix: ' millions'
            },
            plotOptions: {
                area: {
                    stacking: 'normal',
                    lineColor: '#666666',
                    lineWidth: 1,
                    marker: {
                        lineWidth: 1,
                        lineColor: '#666666'
                    }
                }
            },
            series: [{
                name: 'Asia',
                data: [502, 635, 809, 947, null, null, null]
            }, {
                name: 'Asia2',
                data: [null, null, null, 947, 800, 767, 1766]
            }, {
                name: 'Europe',
                data: [163, 203, 276, 408, null, null, null]
            }, {
                name: 'Europe2',
                data: [null, null, null, 408, 339, 818, 1201]
            }]
        });
    </script>
</html>
</code>```

Currently the stacked area charts are performing as expected, but the points at year 1990 are way off in the middle of nowhere.

This normally works fine with a non-stacked area chart such as this fiddle: http://jsfiddle.net/D4sbc/95/

Does anyone know if this is kind of behavior is possible using highcharts stacked area?

答:
It happens because on position 3 you defined 4 points which are shifted in a stacked chart. If you want to split stacking, you need to define series.stack property.

```<code>  series: [{
            name: 'Asia',
            data: [502, 635, 809, 947, null, null, null],
        stack: 0
        }, {
            name: 'Asia2',
            data: [null, null, null, 947, 800, 767, 1766],
        stack: 1
        }, {
            name: 'Europe',
            data: [163, 203, 276, 408, null, null, null],
        stack: 0
        }, {
            name: 'Europe2',
            data: [null, null, null, 408, 339, 818, 1201],
        stack: 1
        }]
</code>```

example: http://jsfiddle.net/nz343opa/1/

Body:
fiddle: http://jsfiddle.net/nz343opa/

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Stacked Area Chart</title>

Currently the stacked area charts are performing as expected, but the points at year 1990 are way off in the middle of nowhere.

This normally works fine with a non-stacked area chart such as this fiddle: http://jsfiddle.net/D4sbc/95/

Does anyone know if this is kind of behavior is possible using highcharts stacked area?

Body:
It happens because on position 3 you defined 4 points which are shifted in a stacked chart. If you want to split stacking, you need to define series.stack property.

  series: [{
            name: 'Asia',
            data: [502, 635, 809, 947, null, null, null],
        stack: 0
        }, {
            name: 'Asia2',
            data: [null, null, null, 947, 800, 767, 1766],
        stack: 1
        }, {
            name: 'Europe',
            data: [163, 203, 276, 408, null, null, null],
        stack: 0
        }, {
            name: 'Europe2',
            data: [null, null, null, 408, 339, 818, 1201],
        stack: 1
        }]

example: http://jsfiddle.net/nz343opa/1/


问:
Redirect output of just one command to different file than rest of script
I have a bash script where I'm using the following to direct the stdout/stderr of every command to a file:

```<code>today=`/bin/date '+%Y_%m_%d__%H_%M_%S'`
exec 2> "/home/pi/stream_logs/$today.$RANDOM.txt"
exec 1>&2

[command 1
command 2
command 3
command 4
.... (many more commands)]
</code>```

I'd like to redirect the stdout/stderr of command 2 to a DIFFERENT file, while keeping the stdout/stderr of every other command going to /home/pi/stream_logs/$today.$RANDOM.txt.

How can I override & redirect JUST the output of one command in this script to a separate file?

答:
You can simply do this :

```<code>...
command 1
command 2 >path_of_secondary_output_file
command 3
...
</code>```

Each command can be redirected individually.  When not redirected, the default is to connect to the stdout and stderr of the calling context (which is why exec has an effect on your commands), but that does not prevent redirecting individual commands.

Body:
I have a bash script where I'm using the following to direct the stdout/stderr of every command to a file:

today=`/bin/date '+%Y_%m_%d__%H_%M_%S'`
exec 2> "/home/pi/stream_logs/$today.$RANDOM.txt"
exec 1>&2

[command 1
command 2
command 3
command 4
.... (many more commands)]

I'd like to redirect the stdout/stderr of command 2 to a DIFFERENT file, while keeping the stdout/stderr of every other command going to /home/pi/stream_logs/$today.$RANDOM.txt.

How can I override & redirect JUST the output of one command in this script to a separate file?

Body:
You can simply do this :

...
command 1
command 2 >path_of_secondary_output_file
command 3
...

Each command can be redirected individually.  When not redirected, the default is to connect to the stdout and stderr of the calling context (which is why exec has an effect on your commands), but that does not prevent redirecting individual commands.


答:
you need to enter this command to navigate to C:\ drive (I'm not sure if this is case sensitive or not, just to be safe maintain case sensitivity)

```<code>cd C:\
</code>```

after that enter

```<code>dir
</code>```

to confirm whether your file is there.

Then use javac to compile

Title: How do you compile the Hello World program for Java?

Body:
I am at step 6 in the process of installing JDK onto windows using instructions from  this website .

When I attempt to “Set the Current Drive to the drive where you saved your source file Hello.java” by typing “c:”, nothing happens (the instructions indicate that something like C:\xxx> should appear).

I have saved the hello world file in the C: directory as indicated in the previous step (step 5).

I am trying to start learning Java and any help would be appreciated.

Body:
you need to enter this command to navigate to C:\ drive (I'm not sure if this is case sensitive or not, just to be safe maintain case sensitivity)

cd C:\

after that enter

dir

to confirm whether your file is there.

Then use javac to compile


问:
Invoke method as closure
My understanding of the Groovy operator .& is that it converts a method call to a closure. Therefore it seems like the following code (which can be run in the Groovy console) should work:

```<code>class Foo {
  def method(def param) {
    param + 10
  }
}

def invokeClosure = {Closure closure ->
   return closure.call()
}

def f = new Foo()
invokeClosure f.&method(6)
</code>```

Of course if I change the last line to

```<code>invokeClosure {f.method(6)}
</code>```

it works fine, but what's wrong with my understanding of the .& operator?

Thanks,
Don

答: Use invokeClosure f.&method.curry(6) instead. This is a closure which could be called without parameters

Title: Invoke method as closure

Body:
My understanding of the Groovy operator .& is that it converts a method call to a closure. Therefore it seems like the following code (which can be run in the Groovy console) should work:

class Foo {
  def method(def param) {
    param + 10
  }
}

def invokeClosure = {Closure closure ->
   return closure.call()
}

def f = new Foo()
invokeClosure f.&method(6)

Of course if I change the last line to

invokeClosure {f.method(6)}

it works fine, but what's wrong with my understanding of the .& operator?

Thanks,
Don