问:
How to use confirm (then submit) using sweet alert?
I have a table where each row have a delete button with this form

```<code><form id="tableDelete_1">
 <input type="hidden" name="tipo" value="delete" />
 <input type="submit" name="send" value="Delete" class="btn btn-danger btn-xs" onClick="return confirm(`Are you sure?`)" />
</form>

<form id="tableDelete_2">
 <input type="hidden" name="tipo" value="delete" />
 <input type="submit" name="send" value="Delete" class="btn btn-danger btn-xs" onClick="return confirm(`Are you sure?`)" />
</form>
</code>```

Then this on bottom of the page

```<code>$(document).on('submit', '[id^=tableDelete_]' , function() {
 return callAjax( $(this).serialize() );
});

function callAjax( data ) {
  $.ajax({
   type : 'POST',
   url  : 'call/page.php',
   data : data,
   success :  function(data) { ... },
   error: function(data) { ... }
  });
  return false;
 };
</code>```

Now I want to delete the classic

```<code>onClick="return confirm(`Are you sure?`)"
</code>```

and use sweetalert...
I have problem just at start when I want to show only the popup with this function

```<code>$(document).on('submit', '[id^=tableDelete_]' , function() {
 swal({
  title: "Are you sure?",
  text: "You will not be able to recover this imaginary file!",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, delete it!",
  closeOnConfirm: false
 },
 function(){
  swal("Deleted!", "Your imaginary file has been deleted.", "success");
 });
};
</code>```

The popup is showed only for a second then the page is reloaded because I think the form is submitted...

Please give me help

答:
SweetAlert uses promise for confirmation callback:

```<code>swal({
      title: "Confirm?",
      text: "Are you sure?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Confirm",
      cancelButtonText: "Back"
      }
    ).then(
      function (isConfirm) {
        if (isConfirm) {
          console.log('CONFIRMED');
        }
      },
      function() {
         console.log('BACK');
      }
    );
</code>```

Body:
I have a table where each row have a delete button with this form

<form id="tableDelete_1">
 <input type="hidden" name="tipo" value="delete" />
 <input type="submit" name="send" value="Delete" class="btn btn-danger btn-xs" onClick="return confirm(`Are you sure?`)" />
</form>

<form id="tableDelete_2">
 <input type="hidden" name="tipo" value="delete" />
 <input type="submit" name="send" value="Delete" class="btn btn-danger btn-xs" onClick="return confirm(`Are you sure?`)" />
</form>

Then this on bottom of the page

$(document).on('submit', '[id^=tableDelete_]' , function() {
 return callAjax( $(this).serialize() );
});

function callAjax( data ) {
  $.ajax({
   type : 'POST',
   url  : 'call/page.php',
   data : data,
   success :  function(data) { ... },
   error: function(data) { ... }
  });
  return false;
 };

Now I want to delete the classic

onClick="return confirm(`Are you sure?`)"

and use sweetalert...
I have problem just at start when I want to show only the popup with this function

$(document).on('submit', '[id^=tableDelete_]' , function() {
 swal({
  title: "Are you sure?",
  text: "You will not be able to recover this imaginary file!",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, delete it!",
  closeOnConfirm: false
 },
 function(){
  swal("Deleted!", "Your imaginary file has been deleted.", "success");
 });
};

The popup is showed only for a second then the page is reloaded because I think the form is submitted...

Please give me help

Body:
SweetAlert uses promise for confirmation callback:

swal({
      title: "Confirm?",
      text: "Are you sure?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Confirm",
      cancelButtonText: "Back"
      }
    ).then(
      function (isConfirm) {
        if (isConfirm) {
          console.log('CONFIRMED');
        }
      },
      function() {
         console.log('BACK');
      }
    );


来源: stackexchange

问:
How to force refresh on ObjectListView visible items?
I have an ObjectListView with a RowFormatter that highlights rows with a property above a user threshold.  When the user changes the threshold, I need the control to redraw the items, calling RowFormatter again, so the new threshold will be visually applied.  Invalidating the control doesn't seem to do anything.  There are 45000 objects in the control, so calling SetObjects again results in a 3-5 second delay.  Is there some way to call RefreshObjects() on just the visible objects?</p>

答:
The best I could come up with was executing something like this:

```<code>int lvi = myOLV.TopItemIndex;
for (int i = 0; i < 30; i++)
    myOLV.RefreshItem((OLVListItem)myOLV.Items[i + lvi]);
</code>```

whenever the row formatting rules change.  This refreshes the first 30 items displayed in the list view; I suppose if someone where using a large, portrait oriented monitor that might not be enough.  But it is fast and works for me.

ContentLicense: CC BY-SA 3.0

Body:
The best I could come up with was executing something like this:

int lvi = myOLV.TopItemIndex;
for (int i = 0; i < 30; i++)
    myOLV.RefreshItem((OLVListItem)myOLV.Items[i + lvi]);

whenever the row formatting rules change.  This refreshes the first 30 items displayed in the list view; I suppose if someone where using a large, portrait oriented monitor that might not be enough.  But it is fast and works for me.


问:
AngularJS pre-fill input fields based on data from controller
I'm trying to pre-fill a form with a data from a controller.

Simple code looks like

```<code><div ng-app="app" ng-controller="MainCtrl">
    <input name="widget.title" ng-model="widget.title">
    <input name="widget.content" ng-model="widget.content">
    <button ng-click="set('foo')">set to foo</button>
</div>
</code>```

and

```<code>angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc'};
        $scope.widget = {content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });
</code>```

but it always pre-fill only last input field

JSFiddle: http://jsfiddle.net/b40nLuf2/

答:
In your case, you overrides the first $scope.widget ($scope.widget = {title:'abc'}) with the second ($scope.widget = {content:'test'}).

You have to define one object $scope.widget with two attributes, title and content, in this way:

```<code>angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {
            title: 'abc',
          content: 'test'
        };
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });
</code>```

Body:
I'm trying to pre-fill a form with a data from a controller.

Simple code looks like

    <input name="widget.title" ng-model="widget.title">
    <input name="widget.content" ng-model="widget.content">
    <button ng-click="set('foo')">set to foo</button>

and

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {title: 'abc'};
        $scope.widget = {content: 'test'};
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });

but it always pre-fill only last input field

JSFiddle: http://jsfiddle.net/b40nLuf2/

Body:
In your case, you overrides the first $scope.widget ($scope.widget = {title:'abc'}) with the second ($scope.widget = {content:'test'}).

You have to define one object $scope.widget with two attributes, title and content, in this way:

angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.widget = {
            title: 'abc',
          content: 'test'
        };
        $scope.set = function(new_title) {
            this.widget.title = new_title;
        }
    });


问:
SharePoint 2013 and Bing map web part
I have two questions:
1. On a SharePoint 2013 page the Bing map throws an error Uncaught TypeError: Microsoft.Maps.Location is not a constructor in the Chrome and the Firefox browsers. How can i fix it, please?
2. The Bing v7 migration to v8 will affect SharePoint 2013?

Thank you.

答:
Not sure which web part this is. The built in mapping functionality in SharePoint was wraps the Bing Maps API's and was built and is supported by the Sharepoint team. There was also a basic webpart I believe which the SharePoint or Office team created, but I believe this was deprecated a few years ago. </p>

<p>As for V7 migration, all v7 traffic now points to v8 as v8 is over 95% backwards compatible and majority of v7 apps were able to continue working with a simple redirect of the API. </p>

Title: SharePoint 2013 and Bing map web part

Body:
Not sure which web part this is. The built in mapping functionality in SharePoint was wraps the Bing Maps API's and was built and is supported by the Sharepoint team. There was also a basic webpart I believe which the SharePoint or Office team created, but I believe this was deprecated a few years ago.

As for V7 migration, all v7 traffic now points to v8 as v8 is over 95% backwards compatible and majority of v7 apps were able to continue working with a simple redirect of the API.


问:
How can i launch a new pane in java FX immediately to the right of the previous pane within the same window/stage?
My goal is to have a program with 3 panes. A mulitfactor Auth. The first pane will have the user type in a passphrase, while the second pain will allow the user to pick a image from a drop down list. But I want the 3rd pane to launch just to the right of the 2nd pane after the use selects a image in the same "Main" stage.

Not looking for someone to code a program just point me in the right direction to what im trying to do. My searching skills are failing, either im not explaining it right or theres another word for this.

Edit:
This is my idea of how i want it to work. Now that i look at it using a border pane probably makes since, But im still stuck with, How can I launch each section of the border at a different time, i.e when something is clicked.

答:
I would go about it by having 3 panes side by side and just blank for the first FXML file you load in. I would then have another FXML file with the same layout that contains what you want to show up in those panes.

Then with that, you can have the controller on request (like when a user hits submit or however you are wanting these to show up) grab the content inside of the pane on the second FXML file by ID and load it into the pane.

I've done something similar with changing anchor panes and keeping the toolbar from the original so I can add more on this when I get home and should be able to supply some code that is modified to fit your issue.

Edit 1: Sorry I was in a hurry to submit that dive I had to go but I am on mobile now so I can edit but not able to add a lot, just felt I needed to say, there are different options for what you can use to do this which is why I just said a pane instead of anything specific. Just wanted to submit something so you can start looking in the right direction till I am able to update.

Edit 2: Alright now that I am home I tried this out and was able to get this working. Here is how I did it.

So I had two FXML files. One with the 3 areas that you have your items, however, only the box that you want to show when it starts is shown. Each area is enclosed by an AnchorPane. I used the AnchorPane as a container so I can swap out what is inside of it. I then had a second FXML file that had all of the boxes you want to show all of which enclosed in AnchorPanes. Here are pictures explaining what I mean.

I have the first pane named initial.fxml and the second named grabfrom.fxml. For the pane names, I just have it as pane1, pane2, and pane3. Lastly, the methods I have are show2() and show3() and call them from the FXML when the respective buttons are clicked inside of the AnchorePanes.

With initial, I just load that up as normal from the start method in my main class and that is all that is needed to be done with that. We only had it so we could display something that does not have the boxes showing before needed.

Now for the important part

With what I have in show2(), which is called when the button inside of the first pane (which is there from the start) is pressed.

```<code>public void show2() throws IOException{
    AnchorPane toSetPane2=(AnchorPane) FXMLLoader.load(getClass().getResource("grabfrom.fxml"));
    toSetPane2=(AnchorPane) toSetPane2.lookup("#pane2");
    pane2.getChildren().setAll(toSetPane2);
}
</code>```

What this is doing is loading the grabfrom.fxml into a temp var that we cast to an anchor pane. (Do note that this works since as you can see in the screenshot the whole FXML file is an anchor pane. If you're not using it that way you can take out the casting and cast to something you are using or not even cast depending on what it is.)

It then set the var we just made to just the AnchorPane we need, which is the second one since that's the one we are adding. It does this with the .lookup("#ID"); method to get just the pane we need.

Lastly, it sets everything inside of the current pane2 to toSetPane2.

This could all be compressed down into one line, however, I have left it as is for easier reading.

You should be able to use this method of loading in a portion of your application for loading in the third one and for that matter any other parts you want to in any situation.

Edit 3:

Also as @Swatarianess had said, there are stackpanes, this method will work with anything that you can set an ID to so they would work just as well. I used AnchorPanes because I have done a fair bit with them and had some code I could recycle whilst making a test for it so it was easier. All you would do if you were using those though is just cast to a StackPane instead of an AnchorPane like this:

```<code>public void show2() throws IOException{
    StackPane toSetPane2=(StackPane) FXMLLoader.load(getClass().getResource("grabfrom.fxml"));
    toSetPane2=(StackPane) toSetPane2.lookup("#pane2");
    pane2.getChildren().setAll(toSetPane2);
}
</code>```

Body:
I would go about it by having 3 panes side by side and just blank for the first FXML file you load in. I would then have another FXML file with the same layout that contains what you want to show up in those panes.

Then with that, you can have the controller on request (like when a user hits submit or however you are wanting these to show up) grab the content inside of the pane on the second FXML file by ID and load it into the pane.

I've done something similar with changing anchor panes and keeping the toolbar from the original so I can add more on this when I get home and should be able to supply some code that is modified to fit your issue.

Edit 1: Sorry I was in a hurry to submit that dive I had to go but I am on mobile now so I can edit but not able to add a lot, just felt I needed to say, there are different options for what you can use to do this which is why I just said a pane instead of anything specific. Just wanted to submit something so you can start looking in the right direction till I am able to update.

Edit 2: Alright now that I am home I tried this out and was able to get this working. Here is how I did it.

So I had two FXML files. One with the 3 areas that you have your items, however, only the box that you want to show when it starts is shown. Each area is enclosed by an AnchorPane. I used the AnchorPane as a container so I can swap out what is inside of it. I then had a second FXML file that had all of the boxes you want to show all of which enclosed in AnchorPanes. Here are pictures explaining what I mean.

I have the first pane named initial.fxml and the second named grabfrom.fxml. For the pane names, I just have it as pane1, pane2, and pane3. Lastly, the methods I have are show2() and show3() and call them from the FXML when the respective buttons are clicked inside of the AnchorePanes.

With initial, I just load that up as normal from the start method in my main class and that is all that is needed to be done with that. We only had it so we could display something that does not have the boxes showing before needed.

Now for the important part

With what I have in show2(), which is called when the button inside of the first pane (which is there from the start) is pressed.

public void show2() throws IOException{
    AnchorPane toSetPane2=(AnchorPane) FXMLLoader.load(getClass().getResource("grabfrom.fxml"));
    toSetPane2=(AnchorPane) toSetPane2.lookup("#pane2");
    pane2.getChildren().setAll(toSetPane2);
}

What this is doing is loading the grabfrom.fxml into a temp var that we cast to an anchor pane. (Do note that this works since as you can see in the screenshot the whole FXML file is an anchor pane. If you're not using it that way you can take out the casting and cast to something you are using or not even cast depending on what it is.)

It then set the var we just made to just the AnchorPane we need, which is the second one since that's the one we are adding. It does this with the .lookup("#ID"); method to get just the pane we need.

Lastly, it sets everything inside of the current pane2 to toSetPane2.

This could all be compressed down into one line, however, I have left it as is for easier reading.

You should be able to use this method of loading in a portion of your application for loading in the third one and for that matter any other parts you want to in any situation.

Edit 3:

Also as @Swatarianess had said, there are stackpanes, this method will work with anything that you can set an ID to so they would work just as well. I used AnchorPanes because I have done a fair bit with them and had some code I could recycle whilst making a test for it so it was easier. All you would do if you were using those though is just cast to a StackPane instead of an AnchorPane like this:

public void show2() throws IOException{
    StackPane toSetPane2=(StackPane) FXMLLoader.load(getClass().getResource("grabfrom.fxml"));
    toSetPane2=(StackPane) toSetPane2.lookup("#pane2");
    pane2.getChildren().setAll(toSetPane2);
}


问:
if and else statement java
I am literally new at java and struggling with a part
so I am suppose to set an option to set new price in a car rental program </p>

```<code>public class CarToBuy extends CAR {
    private int price;
    private int registration_Year;
    private int milage;
    private boolean sold;

    public CarToBuy(String Description, int cost, int year, int miles) {
        super(Description);
        price = cost;
        registration_Year = year;
        milage = miles;
        sold = false;
    }

    public int getPrice() {
        return price;
    }

    public int getReg() {
        return registration_Year;
    }

    public int getMilage() {
        return milage;
    }

    public void setNewPrice(int newprice) {
        price = newprice;
        if (sold = false) {
            System.out.println("car not in stock");
        } else {
            System.out.println("The New price is" + newprice);
        }
    }

    public void carBuying(String Customer_name) {

        if (sold = false) {
            System.out.println("The Car is not in stock");
        } else {
            System.out.println("Thank you purchasing" + Customer_name);
        }
    }
}
</code>```

<p>even though the user get a display message "the car is not in stock" the price gets updates however what I am trying to do is that the price does not change if the car is not in stock
so if false = price does not changes
if true price changes </p>

答:
It looks like if condition is wrong. No need to compare boolean variable in if condition.
Try to change below code </p>

```<code>if (sold = false){
....
}
</code>```

<p>with </p>

```<code>if(!sold){
....
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: if and else statement java

Body:
I am literally new at java and struggling with a part
so I am suppose to set an option to set new price in a car rental program

public class CarToBuy extends CAR {
    private int price;
    private int registration_Year;
    private int milage;
    private boolean sold;

    public CarToBuy(String Description, int cost, int year, int miles) {
        super(Description);
        price = cost;
        registration_Year = year;
        milage = miles;
        sold = false;
    }

    public int getPrice() {
        return price;
    }

    public int getReg() {
        return registration_Year;
    }

    public int getMilage() {
        return milage;
    }

    public void setNewPrice(int newprice) {
        price = newprice;
        if (sold = false) {
            System.out.println("car not in stock");
        } else {
            System.out.println("The New price is" + newprice);
        }
    }

    public void carBuying(String Customer_name) {

        if (sold = false) {
            System.out.println("The Car is not in stock");
        } else {
            System.out.println("Thank you purchasing" + Customer_name);
        }
    }
}

even though the user get a display message "the car is not in stock" the price gets updates however what I am trying to do is that the price does not change if the car is not in stock
so if false = price does not changes
if true price changes

Body:
It looks like if condition is wrong. No need to compare boolean variable in if condition.
Try to change below code

if (sold = false){
....
}

with

if(!sold){
....
}


问:
BufferedWriter write string line by line
Hello I am building a program that writes an output to a text file.
In my program my String looks like this:

```<code>MyName
Addres
Location
Paycheck
</code>```

But when I write it to a text file it looks like this:

```<code>MyName Addres Location Paycheck
</code>```

I am writing everything from a single toString method. How can I use bufferedwriter so that it formats the string while writing it?

Here's my code:

```<code>                               if (file != null) {
                                    FileWriter fileWriter = null;
                                    try {
                                        fileWriter = new FileWriter(file.getAbsolutePath());

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    BufferedWriter out = new BufferedWriter(fileWriter);
                                    try {
                                        out.write(emp.toString());
                                        out.close();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
</code>```

EDIT:

Here is the toString method for the emp class:

```<code>@Override
public String toString() {
    return "Name: " + name + " \nDOB: " + dob + " \nAddress: " + address + " \n******Paycheck******\nSalary: "
            + myPaycheck.getSalary() + "\nFederal Income: " + myPaycheck.getTaxes() + "\nSocial Security: "+ myPaycheck.getSocialSecurity() + "\nMedicare: " + myPaycheck.getMedicare()
             + "\nNet Salary: " + myPaycheck.getNetPay() + "";
}
</code>```

答:
bufferedwriter API
You can use "newLine" easily .</p>

```<code>bw.newLine();
</code>```

Body:
Hello I am building a program that writes an output to a text file.
In my program my String looks like this:

MyName
Addres
Location
Paycheck

But when I write it to a text file it looks like this:

MyName Addres Location Paycheck

I am writing everything from a single toString method. How can I use bufferedwriter so that it formats the string while writing it?

Here's my code:

                               if (file != null) {
                                    FileWriter fileWriter = null;
                                    try {
                                        fileWriter = new FileWriter(file.getAbsolutePath());

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    BufferedWriter out = new BufferedWriter(fileWriter);
                                    try {
                                        out.write(emp.toString());
                                        out.close();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }

EDIT:

Here is the toString method for the emp class:

@Override
public String toString() {
    return "Name: " + name + " \nDOB: " + dob + " \nAddress: " + address + " \n******Paycheck******\nSalary: "
            + myPaycheck.getSalary() + "\nFederal Income: " + myPaycheck.getTaxes() + "\nSocial Security: "+ myPaycheck.getSocialSecurity() + "\nMedicare: " + myPaycheck.getMedicare()
             + "\nNet Salary: " + myPaycheck.getNetPay() + "";
}

Body:
bufferedwriter API
You can use "newLine" easily .

bw.newLine();


问:
What is the random string I am seeing when I use get_query_var?
I am setting up an advanced search page with ACF fields with a custom post type in wordpress.

In my example I am sending 'Students' in ?licenseType=Students

I have registered my query_vars

```<code> add_filter( 'query_vars', 'software_register_query_vars' );
 function software_register_query_vars( $vars ) {
    $vars[] = 'licenseType';
  return $vars;
 }
</code>```

and set up my pre_get_posts filter

```<code>add_action('pre_get_posts','software_pre_get_posts');
function software_pre_get_posts( $query ) {
  if ( is_main_query() && $query->get('post_type') == 'uc_software' ) {
    $query->set('nopaging','true');
    $query->set( 'orderby', 'title' );
    $query->set( 'order', 'ASC' );

    $meta_query = array();

    if( !empty( get_query_var( 'licenseType' ) ) ){
    $meta_query[] = array( 'key' => 'software_license_type', 'value' =>
    get_query_var( 'licenseType' ), 'compare' => 'LIKE' );
    }
// ...
//I will add more fields here...
// ...
    if( count( $meta_query ) > 1 ){
      $meta_query['relation'] = 'AND';
    }

    if( count( $meta_query ) > 0 ){
      $query->set( 'meta_query', $meta_query );
    }
  }
}
</code>```

When I view the query that is being created I see

```<code>SELECT wp_125_posts.* FROM wp_125_posts INNER JOIN wp_125_postmeta ON (
wp_125_posts.ID = wp_125_postmeta.post_id ) WHERE 1=1 AND ( (
wp_125_postmeta.meta_key = 'software_license_type' AND
wp_125_postmeta.meta_value LIKE
 '{4d69cec85576e5c23416d1afb6df73c1a4a288f24aff1da852b18ad70b464309}Students{4d69cec85576e5c23416d1afb6df73c1a4a288f24aff1da852b18ad70b464309}'
) ) AND wp_125_posts.post_type = 'uc_software' AND (wp_125_posts.post_status = 'publish'
OR wp_125_posts.post_status = 'acf-disabled' OR wp_125_posts.post_status = 'private')
GROUP BY wp_125_posts.ID ORDER BY wp_125_posts.post_title ASC
</code>```

What is the random string that is being captured along with my query_var? Is there a way I can retrieve my query_var without it? I see the same thing when I use $_GET['licenseType'].

答:
My question was answered on wordpress.stackexchange

"This is a symptom of having a % character in your meta query value. Since 4.8.3 % characters are being escaped (actually replaced by a semi random string) and should be unescaped before executing the sql query."

I also found that "when using a meta_compare value of 'LIKE', WordPress automatically wraps the wildcard character ( % ) around the meta_value string."

I changed my compare operator from LIKE to = and the random string is removed.

Body:
I am setting up an advanced search page with ACF fields with a custom post type in wordpress.

In my example I am sending 'Students' in ?licenseType=Students

I have registered my query_vars

 add_filter( 'query_vars', 'software_register_query_vars' );
 function software_register_query_vars( $vars ) {
    $vars[] = 'licenseType';
  return $vars;
 }

and set up my pre_get_posts filter

add_action('pre_get_posts','software_pre_get_posts');
function software_pre_get_posts( $query ) {
  if ( is_main_query() && $query->get('post_type') == 'uc_software' ) {
    $query->set('nopaging','true');
    $query->set( 'orderby', 'title' );
    $query->set( 'order', 'ASC' );

    $meta_query = array();

    if( !empty( get_query_var( 'licenseType' ) ) ){
    $meta_query[] = array( 'key' => 'software_license_type', 'value' =>
    get_query_var( 'licenseType' ), 'compare' => 'LIKE' );
    }
// ...
//I will add more fields here...
// ...
    if( count( $meta_query ) > 1 ){
      $meta_query['relation'] = 'AND';
    }

    if( count( $meta_query ) > 0 ){
      $query->set( 'meta_query', $meta_query );
    }
  }
}

When I view the query that is being created I see

SELECT wp_125_posts.* FROM wp_125_posts INNER JOIN wp_125_postmeta ON (
wp_125_posts.ID = wp_125_postmeta.post_id ) WHERE 1=1 AND ( (
wp_125_postmeta.meta_key = 'software_license_type' AND
wp_125_postmeta.meta_value LIKE
 '{4d69cec85576e5c23416d1afb6df73c1a4a288f24aff1da852b18ad70b464309}Students{4d69cec85576e5c23416d1afb6df73c1a4a288f24aff1da852b18ad70b464309}'
) ) AND wp_125_posts.post_type = 'uc_software' AND (wp_125_posts.post_status = 'publish'
OR wp_125_posts.post_status = 'acf-disabled' OR wp_125_posts.post_status = 'private')
GROUP BY wp_125_posts.ID ORDER BY wp_125_posts.post_title ASC

What is the random string that is being captured along with my query_var? Is there a way I can retrieve my query_var without it? I see the same thing when I use $_GET['licenseType'].


问:
jQuery with jQuery mobile bricks form submission
I am trying to implement a collapsable sidebar with a form (search field and submit button) for my site.

I have referenced as script:

```<code>https://code.jquery.com/jquery-1.11.3.min.js
</code>```

and

```<code>https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js
</code>```

However in this combination the form just wont submit, instead it seems to apply the get parameters to the URL and then fires preventDefault of some sort.
It seems like I am using an old version of jQuery , however when I tried to update to:

```<code>https://code.jquery.com/jquery-3.2.1.min.js
</code>```

I noticed that my collapsable menu wont work anymore and the complete style is broken. Also I cant put it in a fiddle since they are mostly already using jQuery.

Sample 1 (Collapse works but form not):

```<code><html>

<head>
  <title>Test form</title>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>

<body>
  <div data-role="page" id="about">
    <div data-role="header">
      <h1>Header</h1>
    </div>
    <div data-role="main" class="ui-content">
      <div data-role="collapsible">
        <h1>Search</h1>
        <form method="get">
          <input name="test" type="text">
          <button type="submit">Send</button>
        </form>
      </div>
    </div>
  </div>
</body>

</html>
</code>```

Sample 2 (Form works but Collapse not):

```<code><html>

<head>
  <title>Test form</title>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>

<body>
  <div data-role="page" id="about">
    <div data-role="header">
      <h1>Header</h1>
    </div>
    <div data-role="main" class="ui-content">
      <div data-role="collapsible">
        <h1>Search</h1>
        <form method="get">
          <input name="test" type="text">
          <button type="submit">Send</button>
        </form>
      </div>
    </div>
  </div>
</body>

</html>
</code>```

For the first sample I also tried to declare a input type button instead of submit and trigger it manually using:

```<code>$('#submitbutton').click(function() {
    $('#myform').submit();
});
</code>```

Without success.

Thanks in advance!

答:
jquery mobile version 1.4.5 is only locked to certain older jquery versions and have not been tested onto older versions above jquery2.0

Read more about it here if you need to: http://blog.jquerymobile.com/2013/02/20/jquery-mobile-1-3-0-released/.

This would explain why the jqueryversion 3.2.1 doesn't work with your collapsible form.

Meanwhile on the side of the 1.11.3 version, According to the developer console all you have to do is load up your form on a web server instead of loading it locally on your computer (C:/Folder/.html wont work, you need to use browser extensions like https or http)

I hope this helps you as I myself ain't a professional programmer and can't scratch up a working code for you.

Body:
I am trying to implement a collapsable sidebar with a form (search field and submit button) for my site.

I have referenced as script:

https://code.jquery.com/jquery-1.11.3.min.js

and

https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js

However in this combination the form just wont submit, instead it seems to apply the get parameters to the URL and then fires preventDefault of some sort.
It seems like I am using an old version of jQuery , however when I tried to update to:

https://code.jquery.com/jquery-3.2.1.min.js

I noticed that my collapsable menu wont work anymore and the complete style is broken. Also I cant put it in a fiddle since they are mostly already using jQuery.

Sample 1 (Collapse works but form not):

  <title>Test form</title>
  <meta charset="utf-8">

Header

Search

        <form method="get">
          <input name="test" type="text">
          <button type="submit">Send</button>
        </form>

Sample 2 (Form works but Collapse not):

  <title>Test form</title>
  <meta charset="utf-8">

Header

Search

        <form method="get">
          <input name="test" type="text">
          <button type="submit">Send</button>
        </form>

For the first sample I also tried to declare a input type button instead of submit and trigger it manually using:

$('#submitbutton').click(function() {
    $('#myform').submit();
});

Without success.

Thanks in advance!


问:
gcloud: permission denied (public key) when ssh-ing to server
I am trying to set up a new ssh key for a gcloud instance. I followed the instructions here verbatim (https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys), generating a new key, putting the public rsa-ssh key with my username on the SSH Keys section of the Metadata tab in the Google Cloud Platform interface, and setting the appropriate permissions for my public and private keys with chmod.

I am getting an error which ends as follows, when attempting to ss using the -vvv verbose flag:

...

debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/erickofman/.ssh/salsadb
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

I have (with a co-worker) ensured that my public key is contained within the authorized_keys file in the server's .ssh folder. Thinking that perhaps something was just stale, I also tried restarting the ssh server using service sshd restart to no avail.

I also tried setting up ssh using the gcloud tool, same result.

I have the correct role/permissions for the site from what I can tell.

This is what the log looks like on the server side:

admin@awesome-website:~$ tail  /var/log/auth.log
Nov 15 20:40:16 awesome-website sshd[18846]: input_userauth_request: invalid user ekofman [preauth]
Nov 15 20:40:17 awesome-website sshd[18846]: Connection closed by 10.100.100.10 port 90001 [preauth]
Nov 15 20:41:17 awesome-website sshd[18848]: Connection closed by 200.200.20.20 port 90002 [preauth]

Been banging my head on this for a bit, any help much appreciated!

答:
Per this make sure you're .ssh/authorized_keys in your user's directory.

You also want to ensure your .ssh directory and authorized_keys have the proper permissions set. (700 and 600 respectively).

```<code>sudo chmod 700 ~/.ssh
sudo chmod 600 ~/.ssh/authorized_keys
</code>```

Body:
Per this make sure you're .ssh/authorized_keys in your user's directory.

You also want to ensure your .ssh directory and authorized_keys have the proper permissions set. (700 and 600 respectively).

sudo chmod 700 ~/.ssh
sudo chmod 600 ~/.ssh/authorized_keys


问:
how to insert the gap back into a time series so that there is no gap in the result time series?
We have retailer data stored in a database, if there is no sale for one item, then there is no row for that item in the database. So after fetch the data from database to R, there will be same gap in the result time series. Is there any way the remove the time series in R (insert back the missing data with value of 0)? </p>

答:
As shown only yesterday, just construct a vector with the desired timeframe, and merge.

```<code># Your dataframe
DF <- data.frame(day = seq(as.POSIXlt("2011-01-17"),
                           as.POSIXlt("2011-02-14"),
                           by = "days")[seq(1, 30, by = 4)][-6],
                 value = c(5,5,7,8,4,6,5,6,9,8,6,6,4,6))

# new dataframe
full <- data.frame(day = seq(min(DF$day),max(DF$day),by = "days"),
                   value = 0)
# the big merge trick
merge(DF,full,all=T)
</code>```

See also this question from yesterday.

ContentLicense: CC BY-SA 2.5

Body:
As shown only yesterday, just construct a vector with the desired timeframe, and merge.

# Your dataframe
DF <- data.frame(day = seq(as.POSIXlt("2011-01-17"),
                           as.POSIXlt("2011-02-14"),
                           by = "days")[seq(1, 30, by = 4)][-6],
                 value = c(5,5,7,8,4,6,5,6,9,8,6,6,4,6))

# new dataframe
full <- data.frame(day = seq(min(DF$day),max(DF$day),by = "days"),
                   value = 0)
# the big merge trick
merge(DF,full,all=T)

See also this question from yesterday.


问:
Rotate gameobject to north
I want to rotate my map to the north, but it keeps rotating and not stopping to north. I want an output just like google map, where map's rotation is fixed to the north. Please check my Update() method. Check the video here: https://www.youtube.com/watch?v=liXmxdI3Adg&feature=youtu.be

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class GoogleAPI : MonoBehaviour {
    private string url;
    public RawImage img;
    public float latitude;
    public float longitude;
    public Text text;
    public Text northtext;

    private IEnumerator Map(float lat, float lon){

        url = "https://maps.googleapis.com/maps/api/staticmap?key=AIzaSyAG0hDd5mZNla3GFCi0cs9wWTkWu-eBBWA&center="+lat+","+lon+"&zoom=19&format=png&maptype=roadmap&style=element:geometry%7Ccolor:0x1d2c4d&style=element:labels.text.fill%7Ccolor:0x8ec3b9&style=element:labels.text.stroke%7Ccolor:0x1a3646&style=feature:administrative.country%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:administrative.land_parcel%7Celement:labels.text.fill%7Ccolor:0x64779e&style=feature:administrative.province%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:landscape.man_made%7Celement:geometry.stroke%7Ccolor:0x334e87&style=feature:landscape.natural%7Celement:geometry%7Ccolor:0x023e58&style=feature:poi%7Celement:geometry%7Ccolor:0x283d6a&style=feature:poi%7Celement:labels.text%7Cvisibility:off&style=feature:poi%7Celement:labels.text.fill%7Ccolor:0x6f9ba5&style=feature:poi%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:poi.business%7Cvisibility:off&style=feature:poi.park%7Celement:geometry.fill%7Ccolor:0x023e58&style=feature:poi.park%7Celement:labels.text.fill%7Ccolor:0x3C7680&style=feature:road%7Celement:geometry%7Ccolor:0x304a7d&style=feature:road%7Celement:labels.icon%7Cvisibility:off&style=feature:road%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:road%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:road.highway%7Celement:geometry%7Ccolor:0x2c6675&style=feature:road.highway%7Celement:geometry.stroke%7Ccolor:0x255763&style=feature:road.highway%7Celement:labels.text.fill%7Ccolor:0xb0d5ce&style=feature:road.highway%7Celement:labels.text.stroke%7Ccolor:0x023e58&style=feature:transit%7Cvisibility:off&style=feature:transit%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:transit%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:transit.line%7Celement:geometry.fill%7Ccolor:0x283d6a&style=feature:transit.station%7Celement:geometry%7Ccolor:0x3a4762&style=feature:water%7Celement:geometry%7Ccolor:0x0e1626&style=feature:water%7Celement:labels.text.fill%7Ccolor:0x4e6d70&size=360x640&scale=2";
        WWW www = new WWW (url);
        yield return www;
        img.texture = www.texture;
        img.SetNativeSize ();
    }

    private IEnumerator StartLocationService(){
        if (!Input.location.isEnabledByUser) {
            Debug.Log ("enable gps pls");
            yield break;
        }

        Input.location.Start ();

        int maxWait = 20;
        while(Input.location.status == LocationServiceStatus.Initializing && maxWait > 0){
            yield return new WaitForSeconds (1);
            maxWait--;
        }

        if(maxWait <=0 ){
            Debug.Log ("Expired");
            yield break;
        }

        if (Input.location.status == LocationServiceStatus.Failed) {
            Debug.Log ("Unable to determine device location");
            yield break;
        }

        latitude = Input.location.lastData.latitude;
        longitude = Input.location.lastData.longitude;

        yield break;
    }
    // Use this for initialization
    void Start () {
        img = img.GetComponent<RawImage> ();
        StartCoroutine (StartLocationService());
        StartCoroutine (LoadData());
        Input.gyro.enabled = true;
        Input.compass.enabled = true;
    }

    private IEnumerator LoadData(){
        while(true){
            latitude = Input.location.lastData.latitude;
            longitude = Input.location.lastData.longitude;
            text.GetComponent<Text> ().text = "Lat: "+latitude+"\nLon: "+longitude;
            StartCoroutine (Map(latitude, longitude));
            yield return new WaitForSeconds(1);
        }
    }

    void Update(){
        img.GetComponent<RawImage> ().transform.Rotate (0,0,Convert.ToInt16(Input.compass.trueHeading));
        northtext.GetComponent<Text> ().text = Convert.ToInt16(Input.compass.trueHeading).ToString();
    }
}
</code>```

答:
You are rotating infinitely instead of setting rotation.

You can do something like this:

```<code>void Update()
{
    var targetEuler = new Vector3(0,0,Input.compass.trueHeading);
    img.transform.rotation = Quaternion.Lerp(image.transform.rotation, targetEuler, Time.deltaTime);
}
</code>```

Title: Rotate gameobject to north

Body:
I want to rotate my map to the north, but it keeps rotating and not stopping to north. I want an output just like google map, where map's rotation is fixed to the north. Please check my Update() method. Check the video here: https://www.youtube.com/watch?v=liXmxdI3Adg&feature=youtu.be

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class GoogleAPI : MonoBehaviour {
    private string url;
    public RawImage img;
    public float latitude;
    public float longitude;
    public Text text;
    public Text northtext;

    private IEnumerator Map(float lat, float lon){

        url = "https://maps.googleapis.com/maps/api/staticmap?key=AIzaSyAG0hDd5mZNla3GFCi0cs9wWTkWu-eBBWA&center="+lat+","+lon+"&zoom=19&format=png&maptype=roadmap&style=element:geometry%7Ccolor:0x1d2c4d&style=element:labels.text.fill%7Ccolor:0x8ec3b9&style=element:labels.text.stroke%7Ccolor:0x1a3646&style=feature:administrative.country%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:administrative.land_parcel%7Celement:labels.text.fill%7Ccolor:0x64779e&style=feature:administrative.province%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:landscape.man_made%7Celement:geometry.stroke%7Ccolor:0x334e87&style=feature:landscape.natural%7Celement:geometry%7Ccolor:0x023e58&style=feature:poi%7Celement:geometry%7Ccolor:0x283d6a&style=feature:poi%7Celement:labels.text%7Cvisibility:off&style=feature:poi%7Celement:labels.text.fill%7Ccolor:0x6f9ba5&style=feature:poi%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:poi.business%7Cvisibility:off&style=feature:poi.park%7Celement:geometry.fill%7Ccolor:0x023e58&style=feature:poi.park%7Celement:labels.text.fill%7Ccolor:0x3C7680&style=feature:road%7Celement:geometry%7Ccolor:0x304a7d&style=feature:road%7Celement:labels.icon%7Cvisibility:off&style=feature:road%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:road%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:road.highway%7Celement:geometry%7Ccolor:0x2c6675&style=feature:road.highway%7Celement:geometry.stroke%7Ccolor:0x255763&style=feature:road.highway%7Celement:labels.text.fill%7Ccolor:0xb0d5ce&style=feature:road.highway%7Celement:labels.text.stroke%7Ccolor:0x023e58&style=feature:transit%7Cvisibility:off&style=feature:transit%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:transit%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:transit.line%7Celement:geometry.fill%7Ccolor:0x283d6a&style=feature:transit.station%7Celement:geometry%7Ccolor:0x3a4762&style=feature:water%7Celement:geometry%7Ccolor:0x0e1626&style=feature:water%7Celement:labels.text.fill%7Ccolor:0x4e6d70&size=360x640&scale=2";
        WWW www = new WWW (url);
        yield return www;
        img.texture = www.texture;
        img.SetNativeSize ();
    }

    private IEnumerator StartLocationService(){
        if (!Input.location.isEnabledByUser) {
            Debug.Log ("enable gps pls");
            yield break;
        }

        Input.location.Start ();

        int maxWait = 20;
        while(Input.location.status == LocationServiceStatus.Initializing && maxWait > 0){
            yield return new WaitForSeconds (1);
            maxWait--;
        }

        if(maxWait <=0 ){
            Debug.Log ("Expired");
            yield break;
        }

        if (Input.location.status == LocationServiceStatus.Failed) {
            Debug.Log ("Unable to determine device location");
            yield break;
        }

        latitude = Input.location.lastData.latitude;
        longitude = Input.location.lastData.longitude;

        yield break;
    }
    // Use this for initialization
    void Start () {
        img = img.GetComponent<RawImage> ();
        StartCoroutine (StartLocationService());
        StartCoroutine (LoadData());
        Input.gyro.enabled = true;
        Input.compass.enabled = true;
    }

    private IEnumerator LoadData(){
        while(true){
            latitude = Input.location.lastData.latitude;
            longitude = Input.location.lastData.longitude;
            text.GetComponent<Text> ().text = "Lat: "+latitude+"\nLon: "+longitude;
            StartCoroutine (Map(latitude, longitude));
            yield return new WaitForSeconds(1);
        }
    }

    void Update(){
        img.GetComponent<RawImage> ().transform.Rotate (0,0,Convert.ToInt16(Input.compass.trueHeading));
        northtext.GetComponent<Text> ().text = Convert.ToInt16(Input.compass.trueHeading).ToString();
    }
}

Body:
You are rotating infinitely instead of setting rotation.

You can do something like this:

void Update()
{
    var targetEuler = new Vector3(0,0,Input.compass.trueHeading);
    img.transform.rotation = Quaternion.Lerp(image.transform.rotation, targetEuler, Time.deltaTime);
}


问:
Sorting an Array with the SORT_STRING flag cause a NOTICE: Array to string conversion
My code (PHP)

The array

```<code>switch (strtoupper($OBJType))
   {
    case "FILE" :
         $SortWith = "A:";
         break;
    case "DIR" :
         $SortWith = "B:";
         break;
    Default:
         $SortWith = "C:";
   }

$dirArray[] = array(
                    'SortBy' => $SortWith,
                    'Data' => $OBJ
                   );
</code>```

My attempt to sort it

```<code>sort(($dirArray),SORT_STRING);
</code>```

The above creates the "Array to string conversion " notice in the error log file. I tried the following but I'm not sure its working; The array contains a sublist of files and directories from the current directory. I would like all files to float to the top with directories on the bottom. File and DIR names should be sorted withing the return list. I'm think I need to use array_multisort but I can't figure it out - any help would be appreciated

答:
Had to add ignore case in my sort. Here's the final code that I ended up with - which I think works.

```<code>$DSP = "  ";

foreach ($dirArray as $key => $row)
        {
          $SK1[$key] = $row['SortBy'];
          //$SK2[$key] = StrToUpper($row['Data']);   //Don't need this if we use the SORT_FLAG_CASE option on array_multisort
          $SK2[$key] = $row['Data'];
        }
//print "<BR><BR> Before Sort dirArray ";print_r($dirArray);print"<BR>";
//print "<BR>Sort Key: $DSP SK1 "; print_r($SK1); print "<BR>Sort Key: $DSP SK2 "; print_r($SK2);
// This sort is not CASELESS so "A" is not the same as "a"// array_multisort($SK1, SORT_ASC, $SK2, SORT_STRING, SORT_ASC, $dirArray);
array_multisort($SK1, SORT_ASC, $SK2, SORT_STRING|SORT_FLAG_CASE, SORT_ASC, $dirArray);
//print "<BR><BR> After Sort dirArray ";print_r($dirArray);print"<BR>";
</code>```

Kudos to https://doc.bccnsoft.com/docs/php-docs-7-en/function.array-multisort.html which helped me understand

Notice the | in array_multisort($SK1, SORT_ASC, $SK2, SORT_STRING|SORT_FLAG_CASE, SORT_ASC, $dirArray);

Body:
My code (PHP)

The array

switch (strtoupper($OBJType))
   {
    case "FILE" :
         $SortWith = "A:";
         break;
    case "DIR" :
         $SortWith = "B:";
         break;
    Default:
         $SortWith = "C:";
   }

$dirArray[] = array(
                    'SortBy' => $SortWith,
                    'Data' => $OBJ
                   );

My attempt to sort it

sort(($dirArray),SORT_STRING);

The above creates the "Array to string conversion " notice in the error log file. I tried the following but I'm not sure its working; The array contains a sublist of files and directories from the current directory. I would like all files to float to the top with directories on the bottom. File and DIR names should be sorted withing the return list. I'm think I need to use array_multisort but I can't figure it out - any help would be appreciated

Body:
Had to add ignore case in my sort. Here's the final code that I ended up with - which I think works.

$DSP = "&nbsp;&nbsp;";

foreach ($dirArray as $key => $row)
        {
          $SK1[$key] = $row['SortBy'];
          //$SK2[$key] = StrToUpper($row['Data']);   //Don't need this if we use the SORT_FLAG_CASE option on array_multisort
          $SK2[$key] = $row['Data'];
        }
//print "<BR><BR> Before Sort dirArray ";print_r($dirArray);print"<BR>";
//print "<BR>Sort Key: $DSP SK1 "; print_r($SK1); print "<BR>Sort Key: $DSP SK2 "; print_r($SK2);
// This sort is not CASELESS so "A" is not the same as "a"// array_multisort($SK1, SORT_ASC, $SK2, SORT_STRING, SORT_ASC, $dirArray);
array_multisort($SK1, SORT_ASC, $SK2, SORT_STRING|SORT_FLAG_CASE, SORT_ASC, $dirArray);
//print "<BR><BR> After Sort dirArray ";print_r($dirArray);print"<BR>";

Kudos to https://doc.bccnsoft.com/docs/php-docs-7-en/function.array-multisort.html which helped me understand

Notice the | in array_multisort($SK1, SORT_ASC, $SK2, SORT_STRING|SORT_FLAG_CASE, SORT_ASC, $dirArray);


问:
Persisting sorting in vaadin-grid in Polymer 2 app
I am using a vaadin-grid in a Polymer 2.0 application with several columns that almost all have a vaadin-grid-sorter. Since I would like to give the user a chance to persist its sorting preferences my question is:

Can I set the column to sort by and the sort direction in code?

I had a short look at the grid source code but didn't find any (public) property for that.

答:
I think there is a direction attribute for vaadin-grid-sorter, you can set the value to asc or desc. And set the path attribute for the property in the item used for sorting. For example:

```<code><vaadin-grid-column>
    <template class="header">
        <vaadin-grid-sorter path="date" direction="desc">Date</vaadin-grid-sorter>
    </template>
    <template>[[item.date]]</template>
</vaadin-grid-column>
</code>```

Body:
I think there is a direction attribute for vaadin-grid-sorter, you can set the value to asc or desc. And set the path attribute for the property in the item used for sorting. For example:

<vaadin-grid-column>
    <template class="header">
        <vaadin-grid-sorter path="date" direction="desc">Date</vaadin-grid-sorter>
    </template>
    <template>[[item.date]]</template>
</vaadin-grid-column>


问:
When to use Variable classes? (BooleanVar, DoubleVar, IntVar, StringVar)
Can't tkinter.widget.configure(text="our text") be used for all widgets? What is the advantage, or the main purpose of using:

```<code>var_cls = tkinter.StringVar()
tkinter.widget.configure(textvariable=var_cls)
</code>```

Is it that var_cls can be more easily shared among methods/classes etc?

Example with a Variable class:

```<code>import tkinter as tk
root = tk.Tk()
var = tk.StringVar(value="This will be on the label.")
tk.Label(root, textvariable=var).pack()
root.mainloop()
</code>```

Example without a Variable class:

```<code>import tkinter as tk
root = tk.Tk()
tk.Label(root, text="This will be on the label.").pack()
root.mainloop()
</code>```

答:
In a tkinter application, StringVar (as well as IntVar, BooleanVar, and DoubleVar) are very rarely needed. The underlying tcl/tk interpreter provides special features for all of its variables, so these wrappers exist to take advantage of those features.

The two big advantages that these variables have are:

You can associate one variable with more than one widget, so that two or more widgets display exactly the same information all the time

You can bind functions to be called when the values change.

My opinion is that you should not use them unless you specifically need one of those two features. If you just need to get or set the value of a widget there are methods to do that on the widget itself (eg: entry_widget.insert(...), label_widget.configure(text='...'), etc).

I feel that they add overhead by introducing an additional object that needs to be managed, without providing any extra benefit unless you're taking advantage of the two features described above.

Body:
Can't tkinter.widget.configure(text="our text") be used for all widgets? What is the advantage, or the main purpose of using:

var_cls = tkinter.StringVar()
tkinter.widget.configure(textvariable=var_cls)

Is it that var_cls can be more easily shared among methods/classes etc?

Example with a Variable class:

import tkinter as tk
root = tk.Tk()
var = tk.StringVar(value="This will be on the label.")
tk.Label(root, textvariable=var).pack()
root.mainloop()

Example without a Variable class:

import tkinter as tk
root = tk.Tk()
tk.Label(root, text="This will be on the label.").pack()
root.mainloop()


问:
UI testing failure - did not receive view did disappear notifications within 2.0s error
I am writing my test suite UI automation with xcode 8. However I keep occurring into this problem while trying to dismiss alerts.

I am currently using the addUIInterruptionMonitor in order to dismiss my alerts, however when I call the interruption monitor to fire using app.tap()  I get the error UI testing failure - did not receive view did disappear notifications within 2.0s error

Why is this happening and how can I prevent this from happening?

Attached is my start up code for the app

```<code> override func setUp() {
    super.setUp()
    XCUIApplication().terminate()
    continueAfterFailure = false
    app.launch()

    addUIInterruptionMonitorWithDescription("Enable Notifications") { (alert) -> Bool in
       let button =  alert.buttons["OK"]
        if button.exists{
            button.tap()
            return true
        }
        return false
    }
    app.buttons["Enable notifications"].tap()

    app.tap()

    XCTAssert(app.tabBars.buttons["Settings"].exists)
    app.tabBars.buttons["Settings"].tap()
}
</code>```

答:
First, add the monitor before app.launch() and you'll not need app.tap()

Second, is the app.buttons["Enable notifications"].tap() the trigger for the alert to appear, if not, remove that line.

Third, if you return false on the monitor's handler, the system will tap the "cancel" button for that alert. I prefere to fail the test in this case since it's an unexpected system alert.

Body:
I am writing my test suite UI automation with xcode 8. However I keep occurring into this problem while trying to dismiss alerts.

I am currently using the addUIInterruptionMonitor in order to dismiss my alerts, however when I call the interruption monitor to fire using app.tap()  I get the error UI testing failure - did not receive view did disappear notifications within 2.0s error

Why is this happening and how can I prevent this from happening?

Attached is my start up code for the app

 override func setUp() {
    super.setUp()
    XCUIApplication().terminate()
    continueAfterFailure = false
    app.launch()

    addUIInterruptionMonitorWithDescription("Enable Notifications") { (alert) -> Bool in
       let button =  alert.buttons["OK"]
        if button.exists{
            button.tap()
            return true
        }
        return false
    }
    app.buttons["Enable notifications"].tap()

    app.tap()

    XCTAssert(app.tabBars.buttons["Settings"].exists)
    app.tabBars.buttons["Settings"].tap()
}


问:
date comparison in BigQuery
I am trying to filter out certain dates in my query. The line of code I am using in my query is as follows:

```<code>(date(date_add(date_time,-1,'year')) < date(date_add(current_date(),-1,'year')) ) OR year(date_time) = 2017)
</code>```

The idea is to get all data YTD in 2017, as well as the data from 2016 that corresponds to those same days. So if I were to run a proper version of what I want, it would return all data YTD, as well as all 2016 data up until Nov. 16, 2016.

However, whenever I run the query with this in the WHERE clause, my query still returns dates that do not fit within my described parameters. I may be missing something completely obvious but this has been driving me nuts. Is there a particular way to filter dates that I'm missing?

Edit: Here is some of my data

```<code>[date]       [today]    [uniques]
2016-01-01  2017-11-16  363878
2016-01-02  2017-11-16  383813
2016-01-03  2017-11-16  392579
2016-01-04  2017-11-16  709367
..
..
2016-11-15  2017-11-16  841850
2016-11-16  2017-11-16  847831
2016-11-17  2017-11-16  797610
2016-11-18  2017-11-16  187158
2016-11-19  2017-11-16  521100
..
2017-11-12  2017-11-16  297604
2017-11-13  2017-11-16  527858
2017-11-14  2017-11-16  474051
2017-11-15  2017-11-16  569686
</code>```

I added the today row for myself to make sure there wasn't a difference in date formatting. With this data, the bottom 3 rows in the middle section should not be returned, but they are. Everything else should fit the parameters I've set and get returned.

Appreciate any and all help. Thanks!

答:
Below is for BigQuery Standard SQL:

#standardSQL
SELECT date_time, uniques
FROM `project.dataset.yourTable`
WHERE (PARSE_DATE('%Y-%m-%d', date_time) < DATE_SUB(CURRENT_DATE(), INTERVAL 1 YEAR))
OR EXTRACT(YEAR FROM PARSE_DATE('%Y-%m-%d', date_time)) = 2017
```

<p>You can test / play with it using dummy data from your question as it is below   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT '2016-01-01' date_time, 363878 uniques UNION ALL
  SELECT '2016-01-02', 383813 UNION ALL
  SELECT '2016-01-03', 392579 UNION ALL
  SELECT '2016-01-04', 709367 UNION ALL

  SELECT '2016-11-15', 841850 UNION ALL
  SELECT '2016-11-16', 847831 UNION ALL
  SELECT '2016-11-17', 797610 UNION ALL
  SELECT '2016-11-18', 187158 UNION ALL
  SELECT '2016-11-19', 521100 UNION ALL

  SELECT '2017-11-12', 297604 UNION ALL
  SELECT '2017-11-13', 527858 UNION ALL
  SELECT '2017-11-14', 474051 UNION ALL
  SELECT '2017-11-15', 569686
)
SELECT date_time, uniques
FROM `project.dataset.yourTable`
WHERE (PARSE_DATE('%Y-%m-%d', date_time) < DATE_SUB(CURRENT_DATE(), INTERVAL 1 YEAR))
OR EXTRACT(YEAR FROM PARSE_DATE('%Y-%m-%d', date_time)) = 2017
</code>```

It is highly recommended to use BigQuery Standard SQL - so if you are still using Legacy SQL - consider Migrating to Standard SQL

Meantime if you have your code in legacy sql (which is look like to me)  - you can use below

#legacySQL
SELECT date_time, uniques
FROM [project:dataset.yourTable]
WHERE (DATE(date_time) < DATE(DATE_ADD(CURRENT_DATE(), -1, 'year')))
OR YEAR(date_time) = 2017
```

<p>You can test / play with dummy data as below  </p>

<pre class="lang-sql prettyprint-override"><code>#legacySQL
SELECT date_time, uniques
FROM --[project:dataset.yourTable]
  (SELECT '2016-01-01' date_time, 363878 uniques),
  (SELECT '2016-01-02' date_time, 383813 uniques),
  (SELECT '2016-01-03' date_time, 392579 uniques),
  (SELECT '2016-01-04' date_time, 709367 uniques),

  (SELECT '2016-11-15' date_time, 841850 uniques),
  (SELECT '2016-11-16' date_time, 847831 uniques),
  (SELECT '2016-11-17' date_time, 797610 uniques),
  (SELECT '2016-11-18' date_time, 187158 uniques),
  (SELECT '2016-11-19' date_time, 521100 uniques),

  (SELECT '2017-11-12' date_time, 297604 uniques),
  (SELECT '2017-11-13' date_time, 527858 uniques),
  (SELECT '2017-11-14' date_time, 474051 uniques),
  (SELECT '2017-11-15' date_time, 569686 uniques)
WHERE (DATE(date_time) < DATE(DATE_ADD(CURRENT_DATE(), -1, 'year')))
OR YEAR(date_time) = 2017
</code>```

Title: date comparison in BigQuery

Body:
I am trying to filter out certain dates in my query. The line of code I am using in my query is as follows:

(date(date_add(date_time,-1,'year')) < date(date_add(current_date(),-1,'year')) ) OR year(date_time) = 2017)

The idea is to get all data YTD in 2017, as well as the data from 2016 that corresponds to those same days. So if I were to run a proper version of what I want, it would return all data YTD, as well as all 2016 data up until Nov. 16, 2016.

However, whenever I run the query with this in the WHERE clause, my query still returns dates that do not fit within my described parameters. I may be missing something completely obvious but this has been driving me nuts. Is there a particular way to filter dates that I'm missing?

Edit: Here is some of my data

[date]       [today]    [uniques]
2016-01-01  2017-11-16  363878
2016-01-02  2017-11-16  383813
2016-01-03  2017-11-16  392579
2016-01-04  2017-11-16  709367
..
..
2016-11-15  2017-11-16  841850
2016-11-16  2017-11-16  847831
2016-11-17  2017-11-16  797610
2016-11-18  2017-11-16  187158
2016-11-19  2017-11-16  521100
..
2017-11-12  2017-11-16  297604
2017-11-13  2017-11-16  527858
2017-11-14  2017-11-16  474051
2017-11-15  2017-11-16  569686

I added the today row for myself to make sure there wasn't a difference in date formatting. With this data, the bottom 3 rows in the middle section should not be returned, but they are. Everything else should fit the parameters I've set and get returned.

Appreciate any and all help. Thanks!

Body:
Below is for BigQuery Standard SQL:

#standardSQL
SELECT date_time, uniques
FROM `project.dataset.yourTable`
WHERE (PARSE_DATE('%Y-%m-%d', date_time) < DATE_SUB(CURRENT_DATE(), INTERVAL 1 YEAR))
OR EXTRACT(YEAR FROM PARSE_DATE('%Y-%m-%d', date_time)) = 2017

You can test / play with it using dummy data from your question as it is below

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT '2016-01-01' date_time, 363878 uniques UNION ALL
  SELECT '2016-01-02', 383813 UNION ALL
  SELECT '2016-01-03', 392579 UNION ALL
  SELECT '2016-01-04', 709367 UNION ALL

  SELECT '2016-11-15', 841850 UNION ALL
  SELECT '2016-11-16', 847831 UNION ALL
  SELECT '2016-11-17', 797610 UNION ALL
  SELECT '2016-11-18', 187158 UNION ALL
  SELECT '2016-11-19', 521100 UNION ALL

  SELECT '2017-11-12', 297604 UNION ALL
  SELECT '2017-11-13', 527858 UNION ALL
  SELECT '2017-11-14', 474051 UNION ALL
  SELECT '2017-11-15', 569686
)
SELECT date_time, uniques
FROM `project.dataset.yourTable`
WHERE (PARSE_DATE('%Y-%m-%d', date_time) < DATE_SUB(CURRENT_DATE(), INTERVAL 1 YEAR))
OR EXTRACT(YEAR FROM PARSE_DATE('%Y-%m-%d', date_time)) = 2017

It is highly recommended to use BigQuery Standard SQL - so if you are still using Legacy SQL - consider Migrating to Standard SQL

Meantime if you have your code in legacy sql (which is look like to me)  - you can use below

#legacySQL
SELECT date_time, uniques
FROM [project:dataset.yourTable]
WHERE (DATE(date_time) < DATE(DATE_ADD(CURRENT_DATE(), -1, 'year')))
OR YEAR(date_time) = 2017

You can test / play with dummy data as below

#legacySQL
SELECT date_time, uniques
FROM --[project:dataset.yourTable]
  (SELECT '2016-01-01' date_time, 363878 uniques),
  (SELECT '2016-01-02' date_time, 383813 uniques),
  (SELECT '2016-01-03' date_time, 392579 uniques),
  (SELECT '2016-01-04' date_time, 709367 uniques),

  (SELECT '2016-11-15' date_time, 841850 uniques),
  (SELECT '2016-11-16' date_time, 847831 uniques),
  (SELECT '2016-11-17' date_time, 797610 uniques),
  (SELECT '2016-11-18' date_time, 187158 uniques),
  (SELECT '2016-11-19' date_time, 521100 uniques),

  (SELECT '2017-11-12' date_time, 297604 uniques),
  (SELECT '2017-11-13' date_time, 527858 uniques),
  (SELECT '2017-11-14' date_time, 474051 uniques),
  (SELECT '2017-11-15' date_time, 569686 uniques)
WHERE (DATE(date_time) < DATE(DATE_ADD(CURRENT_DATE(), -1, 'year')))
OR YEAR(date_time) = 2017


问:
Adding an item to ScrollView without re-rendering all items
In my current use-case, I'm adding items to a ScrollView. I noticed that if I add an item to the items collection located in state, all the items re-render.

Is there any workaround I can do?
The current implementation has to be ScrollView, so changing to FlatList or any other implementation of List would be irrelevant.

```<code><View style={{flex: 1}}>
    <ScrollView>
      <TouchableWithoutFeedback accessible={false}>
        <View style={{flexDirection: 'column', alignItems: 'center'}}>
        {this.state.items.map(( item, key ) =>
        (
          <Flag country={item} key={key} />
        ))}
        </View>
      </TouchableWithoutFeedback>
    </ScrollView>
  </View>
</code>```

Thank you

答:
I would check into using FlatList instead of using a map from a set of states to render a ScrollView. Essentially, once you update this.state.items, you call for a rerender of anything involved with that state.

I've used this resource and it should help you upgrade your code:

http://matthewsessions.com/2017/05/15/optimizing-list-render-performance.html

Body:
In my current use-case, I'm adding items to a ScrollView. I noticed that if I add an item to the items collection located in state, all the items re-render.

Is there any workaround I can do?
The current implementation has to be ScrollView, so changing to FlatList or any other implementation of List would be irrelevant.

<View style={{flex: 1}}>
    <ScrollView>
      <TouchableWithoutFeedback accessible={false}>
        <View style={{flexDirection: 'column', alignItems: 'center'}}>
        {this.state.items.map(( item, key ) =>
        (
          <Flag country={item} key={key} />
        ))}
        </View>
      </TouchableWithoutFeedback>
    </ScrollView>
  </View>

Thank you


问:
Using Datatables to export a dynamic table
I'm trying to use Datatables to export a table.

The problem I run into is that I have the following table:

```<code><table id="tbl" class="display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th data-field="ID">ID</th>
<th data-field="Name">Name</th>
<th data-formatter="operateFormatter" data-events="operateEvents"></th>
</tr>
</thead>

<tr data-index="0"><td class="sorting_asc" style="">1</td><td class="sorting" style="">asadasd</td><td class="sorting" style="">-</td></tr>
<tr data-index="1"><td class="sorting_asc" style="">2</td><td class="sorting" style="">qwqweqwe</td><td class="sorting" style="">-</td></tr>
</table>
</code>```

I use this to add the buttons to export:

```<code>$('#tbl').DataTable( {
    dom: 'Bfrtip',
    buttons: [
        'copy', 'csv', 'excel', 'pdf', 'print'
    ]
} );
</code>```

This will always export only 2 rows. No matter how many I add to the table with javascript.

Deleted the clone thing since that's not what I'm actually doing.

I populate the table with ajax:

```<code>function Load_ObjectList() {
    var url = urlService + "/TESTLoadAgencies/0";
    var EmpCode = sessionStorage['EmpCode']
    $.ajax({
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        url: url,
        dataType: "json",
        async: true,
        crossDomain: true,
        cache: false,
        data: "{\"Empcode\":\"" + EmpCode + "\"}",
        success: function (response) {
            if (response.Status == "0") {

                if (response.list != null) {
                    objDataAll = response.list;
                    $('#tbl').bootstrapTable('destroy');
                    $('#tbl').bootstrapTable({

                        data: objDataAll,
                        escape: 'false'
                    });
                }

            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR);
        }
    });
}
</code>```

After I call this function I add the buttons. And 0 rows are copied when I press the button.

What am I missing?

答:
It only exports the two rows you added manually in the table because you are clonning the last line after datatable is initialized. You should do it before.

If you want last row to be in the exported files, first clone the row and then initialize your datatable like this:

```<code>    var $tableBody = $('#tbl').find("tbody"),
        $trLast = $tableBody.find("tr:last"),
        $trNew = $trLast.clone();
    $trLast.after($trNew);

    $('#tbl').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    } );
</code>```

Body:
I'm trying to use Datatables to export a table.

The problem I run into is that I have the following table:

ID
Name

1	asadasd	-

2	qwqweqwe	-

I use this to add the buttons to export:

$('#tbl').DataTable( {
    dom: 'Bfrtip',
    buttons: [
        'copy', 'csv', 'excel', 'pdf', 'print'
    ]
} );

This will always export only 2 rows. No matter how many I add to the table with javascript.

Deleted the clone thing since that's not what I'm actually doing.

I populate the table with ajax:

function Load_ObjectList() {
    var url = urlService + "/TESTLoadAgencies/0";
    var EmpCode = sessionStorage['EmpCode']
    $.ajax({
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        url: url,
        dataType: "json",
        async: true,
        crossDomain: true,
        cache: false,
        data: "{\"Empcode\":\"" + EmpCode + "\"}",
        success: function (response) {
            if (response.Status == "0") {

                if (response.list != null) {
                    objDataAll = response.list;
                    $('#tbl').bootstrapTable('destroy');
                    $('#tbl').bootstrapTable({

                        data: objDataAll,
                        escape: 'false'
                    });
                }

            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR);
        }
    });
}

After I call this function I add the buttons. And 0 rows are copied when I press the button.

What am I missing?

Body:
It only exports the two rows you added manually in the table because you are clonning the last line after datatable is initialized. You should do it before.

If you want last row to be in the exported files, first clone the row and then initialize your datatable like this:

    var $tableBody = $('#tbl').find("tbody"),
        $trLast = $tableBody.find("tr:last"),
        $trNew = $trLast.clone();
    $trLast.after($trNew);

    $('#tbl').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    } );


问:
How many levels of inheritance
Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.

答:
There is no best practices regarding maximum depth of inheritance. Instead of looking it in volume, this is the rule of thumb when it comes to inheritance in java (and any OO language for that matter).

1_ Before implementing inheritance check if "is a" relationship is true. Charger is a car. (so inheritance is fine). If you do this, then you will not end up with huge inheritance tree anyway. ( Wheel is not a car, so inheritance here is wrong)

2_ If "is a" relationship fails or you have ambiguity, then probable inheritance is not the way. You need to identify commonality among your classes and use composition.(refactoring common code to a new class).

3_ if you want to establish a type hierrarchy, then you should go with Interface inheritance (Type) not class level inheritance. (May be some of these statements need more explanation, but for that you probably need to pick up some book.)

Title: How many levels of inheritance


问:
issue with image_tag when using html in helper
I have a situation where I need to insert a part of the html inside an existing html block so I am trying first to create this html and as it will be used in many places hence I am using an helper to create this fragment
But the image_tag is throwing errors and it works perfectly if directly used in the view

my helper code

```<code>def create_banner_html_helper(banner)

    if banner.logo.present?
      return "<div class='m3-news_wrap m3-mdcast-banner slide'>
    <a href='" + banner.link_url + "' target=_'blank'>
    <div class='m3-article'>

<div class='m3-section m3-img_holder'>"
      image_tag banner.logo(:small)
      "</div>
    <div class='m3-section m3-desc'>
         <h3 class='m3-title'>" + banner.title+ "</h3>
                    <p>" + banner.subtitle + "</p>
         <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                  </div>
                </div>
              </a>".html_safe

    end

    return "<div class='m3-news_wrap m3-mdcast-banner slide'>
    <a href='" + banner.link_url + "' target=_'blank'>
    <div class='m3-article'>

    <div class='m3-section m3-desc'>
         <h3 class='m3-title'>" + banner.title+ "</h3>
                    <p>" + banner.subtitle + "</p>
         <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                  </div>
                </div>
              </a>".html_safe
  end
</code>```

banner passed is an ActiveRecord object.

I really don't know what is the issue so any help will be highly appreciated

答:
I'm guessing that when you are calling image_tag, it's essentially calling return, which is going to end the execution of the rest of your method (hence why it stops outputting there).

I would suggest moving all of the html from your helper into a partial. Pass any variables you need as locals. This will help with readability and maintainability of your code.

Partial to replace your helper (Let's say it's views/partials/_banner_logo.html.erb):

```<code><div class='m3-news_wrap m3-mdcast-banner slide'>
  <a href='<%= banner.link_url %>' target=_'blank'>
    <div class='m3-article'>
      <% if banner.logo.present? %>
        <div class='m3-section m3-img_holder'>
          <%= image_tag banner.logo(:small) %>
        </div>
      <% end %>
      <div class='m3-section m3-desc'>
        <h3 class='m3-title'><%= banner.title %></h3>
        <p><%= banner.subtitle %></p>
        <a href='<%= banner.link_url %>' target='_blank'><%= banner.link_text %></a>
      </div>
    </div>
  </a>
</div>
</code>```

To use it, call render from whatever view/template you need it rendered in and pass the banner:

```<code><%= render 'partials/banner_logo', banner: your_banner_variable %>
</code>```

Body:
I have a situation where I need to insert a part of the html inside an existing html block so I am trying first to create this html and as it will be used in many places hence I am using an helper to create this fragment
But the image_tag is throwing errors and it works perfectly if directly used in the view

my helper code

def create_banner_html_helper(banner)

    if banner.logo.present?
      return "

"
      image_tag banner.logo(:small)
      "

" + banner.title+ "

" + banner.subtitle + "

         " + banner.link_text + "

              ".html_safe

    end

    return "

" + banner.title+ "

" + banner.subtitle + "

         " + banner.link_text + "

              ".html_safe
  end

banner passed is an ActiveRecord object.

I really don't know what is the issue so any help will be highly appreciated

Body:
I'm guessing that when you are calling image_tag, it's essentially calling return, which is going to end the execution of the rest of your method (hence why it stops outputting there).

I would suggest moving all of the html from your helper into a partial. Pass any variables you need as locals. This will help with readability and maintainability of your code.

Partial to replace your helper (Let's say it's views/partials/_banner_logo.html.erb):

<div class='m3-news_wrap m3-mdcast-banner slide'>
  <a href='<%= banner.link_url %>' target=_'blank'>
    <div class='m3-article'>
      <% if banner.logo.present? %>
        <div class='m3-section m3-img_holder'>
          <%= image_tag banner.logo(:small) %>
        </div>
      <% end %>
      <div class='m3-section m3-desc'>
        <h3 class='m3-title'><%= banner.title %></h3>
        <p><%= banner.subtitle %></p>
        <a href='<%= banner.link_url %>' target='_blank'><%= banner.link_text %></a>
      </div>
    </div>
  </a>
</div>

To use it, call render from whatever view/template you need it rendered in and pass the banner:

<%= render 'partials/banner_logo', banner: your_banner_variable %>


问:
I don't know how to make this shape in python using "#'s" and "*'s"
I'm trying to create a simple python code that will create fairly simple shapes using "#'s" and "*'s" and I'm quite new to python and would like to only use for loops and the range() function. My code may be more complicated than it needs to be, but anyway, Heres my code so far:

```<code>Shapes = int(input("please enter the number size of the shape you want"))
sShapes = input("Would you like a square, triangle, Triangle 2 or Pyramid?")
s = 0
ss = Shapes + 1

##This is the code to make a square##
if sShapes == "Square":
    for i in range(0, Shapes):
        print('*'*Shapes)

##This is the code to make a triangle##
elif sShapes == "Triangle":
    for b in range(0, ss, 1):
        print('*'*(s+1)*b)

##This is the code that does not work##
elif sShapes == "T2":
    for c in range(ss,0,-1):
        print('#'*(s+1)*c, '*')
</code>```

The code that does not work is supposed to look like this:

```<code>####*
###**
##***
#****
*****
</code>```

答:
Well, here is my approach to print the above pattern

```<code>n = 6
for i in range(1, n):
    print("{}{}".format("#"*(n-i-1),"*"*i))

####*
###**
##***
#****
*****
</code>```

You can pass n instead of absolute number

Body:
I'm trying to create a simple python code that will create fairly simple shapes using "#'s" and "*'s" and I'm quite new to python and would like to only use for loops and the range() function. My code may be more complicated than it needs to be, but anyway, Heres my code so far:

Shapes = int(input("please enter the number size of the shape you want"))
sShapes = input("Would you like a square, triangle, Triangle 2 or Pyramid?")
s = 0
ss = Shapes + 1

##This is the code to make a square##
if sShapes == "Square":
    for i in range(0, Shapes):
        print('*'*Shapes)

##This is the code to make a triangle##
elif sShapes == "Triangle":
    for b in range(0, ss, 1):
        print('*'*(s+1)*b)

##This is the code that does not work##
elif sShapes == "T2":
    for c in range(ss,0,-1):
        print('#'*(s+1)*c, '*')

The code that does not work is supposed to look like this:

####*
###**
##***
#****
*****

Body:
Well, here is my approach to print the above pattern

n = 6
for i in range(1, n):
    print("{}{}".format("#"*(n-i-1),"*"*i))

####*
###**
##***
#****
*****

You can pass n instead of absolute number


问:
Trying to access unlisted children of root node with phpSmug
I've modified the example-oauth.php file that comes with phpSmug to list the immediate children of the root node, but only public folders (those with at least one public album) and public albums are listed. I know my authorization (Access=Full) is correct, because when I try to list all user albums, I do get them all (code not shown). When I use the live example on the SmugMug site, I do get all immediate children of the root node. So, it seems the problem is within phpSmug, not with the SmugMug API itself. Also, I am replacing a Chrome App that also works as it should. (The Chrome App does not use phpSmug, of course.)

Any idea what's wrong and how I can fix it?

Here's my modified example. Lines that I added or changed are marked with the initials MJR. Note again that I didn't write most of this program, but only added and changed a few lines.

```<code>/* Last updated with phpSmug 4.0
 *
 * This example file shows you how to authenticate using OAuth and then display
 * the first 25 images in the first public gallery found of the authenticated
 * user's account.
 *
 * You'll want to set the following variables below:
 *
 * - $APIKey with one provided by SmugMug: http://www.smugmug.com/hack/apikeys
 * - $OAuthSecret with one provided when you obtained your API key
 * - $AppName with your application name, version and URL, eg
 *
 * The $AppName is NOT required, but it's encouraged as it will allow SmugMug to
 * diagnose any issues users may have with your application if they request help
 * on the SmugMug forums. A good format to use is "APP NAME/VER (URL)".
 *
 */

$APIKey = 'YOUR_API_KEY';  // MJR -- my own data was entered
$OAuthSecret = 'YOUR_OAUTH_SECRET';  // MJR -- my own data was entered
$AppName = 'YOUR_APP_NAME/VER (URL)';
?>
<html>
<head>
    <title>phpSmug OAuth Login Example</title>
    <style type="text/css">
        body { background-color: #fff; color: #444; font-family: sans-serif }
        div { width: 750px; margin: 0 auto; text-align: center; }
        img { border: 0;}
    </style>
</head>
<body>
    <div>
        <a href="http://phpsmug.com"><img src="phpSmug-logo.svg" /></a>
        <h1>OAuth Login Example</h1>
<?php

try {
    $options = [
        'AppName' => $AppName,
        '_verbosity' => 1, # Reduce verbosity to reduce the amount of data in the response and to make using it easier.
        'OAuthSecret' => $OAuthSecret, # You need to pass your OAuthSecret in order to authenticate with OAuth.
        'verify' => false // MJR: Added because SSL certificates are not set up
    ];

    $client = new phpSmug\Client($APIKey, $options);

    // Perform the 3 step OAuth Authorisation process.
    // NOTE: This is a very simplified example that does NOT store the final token.
    // You will need to ensure your application does.
    if (!isset($_SESSION['SmugGalReqToken'])) {

        // Step 1: Get a request token using an optional callback URL back to ourselves
        $callback = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
        $request_token = $client->getRequestToken($callback);
        $_SESSION['SmugGalReqToken'] = serialize($request_token);

        // Step 2: Get the User to login to SmugMug and authorise this demo
        echo '<p>Click <a href="'.$client->getAuthorizeURL(['Access' => 'Full']).'"><strong>HERE</strong></a> to Authorize This Demo.</p>'; // MJR
        // Alternatively, automatically direct your visitor by commenting out the above line in favour of this:
        //header("Location:".$client->getAuthorizeURL());
    } else {
        $reqToken = unserialize($_SESSION['SmugGalReqToken']);
        unset($_SESSION['SmugGalReqToken']);

        // Step 3: Use the Request token obtained in step 1 to get an access token
        $client->setToken($reqToken['oauth_token'], $reqToken['oauth_token_secret']);
        $oauth_verifier = $_GET['oauth_verifier'];  // This comes back with the callback request.
        $token = $client->getAccessToken($oauth_verifier);  // The results of this call is what your application needs to store.
        // Get the username of the authenticated user
        $username = $client->get('!authuser')->User->NickName;

        // List top level folders and albums.  // MJR
        $user = $client->get('!authuser'); // MJR
        $root = $client->get($user->User->Uris->Node); // MJR
        $children = $client->get($root->Node->Uris->ChildNodes); // MJR
        foreach ($children->Node as $v) { // MJR
            echo "<br> $v->Type \"$v->Name\" $v->Uri"; // MJR
        } // MJR

    }
} catch (Exception $e) {
    echo "{$e->getMessage()} (Error Code: {$e->getCode()})";
}
?>
    </div>
</body>
</html>
</code>```

答:
Solved! I was using an API key that I got a few years ago. I created a new API key, and it works! Must be some weird state left over from before SmugMug went to API 2.

FYI: In the returned JSON, ResponseLevel is now set to Full. If this comes up for anyone else in the future, and you determine that the ResponseLevel is set to Public, that might be a clue that their problem is like mine.

Thanks for your help, lildude. You're a BIG dude in my book!

Body:
I've modified the example-oauth.php file that comes with phpSmug to list the immediate children of the root node, but only public folders (those with at least one public album) and public albums are listed. I know my authorization (Access=Full) is correct, because when I try to list all user albums, I do get them all (code not shown). When I use the live example on the SmugMug site, I do get all immediate children of the root node. So, it seems the problem is within phpSmug, not with the SmugMug API itself. Also, I am replacing a Chrome App that also works as it should. (The Chrome App does not use phpSmug, of course.)

Any idea what's wrong and how I can fix it?

Here's my modified example. Lines that I added or changed are marked with the initials MJR. Note again that I didn't write most of this program, but only added and changed a few lines.

/* Last updated with phpSmug 4.0
 *
 * This example file shows you how to authenticate using OAuth and then display
 * the first 25 images in the first public gallery found of the authenticated
 * user's account.
 *
 * You'll want to set the following variables below:
 *
 * - $APIKey with one provided by SmugMug: http://www.smugmug.com/hack/apikeys
 * - $OAuthSecret with one provided when you obtained your API key
 * - $AppName with your application name, version and URL, eg
 *
 * The $AppName is NOT required, but it's encouraged as it will allow SmugMug to
 * diagnose any issues users may have with your application if they request help
 * on the SmugMug forums. A good format to use is "APP NAME/VER (URL)".
 *
 */

$APIKey = 'YOUR_API_KEY';  // MJR -- my own data was entered
$OAuthSecret = 'YOUR_OAUTH_SECRET';  // MJR -- my own data was entered
$AppName = 'YOUR_APP_NAME/VER (URL)';
?>

    <title>phpSmug OAuth Login Example</title>

OAuth Login Example

<?php

try {
    $options = [
        'AppName' => $AppName,
        '_verbosity' => 1, # Reduce verbosity to reduce the amount of data in the response and to make using it easier.
        'OAuthSecret' => $OAuthSecret, # You need to pass your OAuthSecret in order to authenticate with OAuth.
        'verify' => false // MJR: Added because SSL certificates are not set up
    ];

    $client = new phpSmug\Client($APIKey, $options);

    // Perform the 3 step OAuth Authorisation process.
    // NOTE: This is a very simplified example that does NOT store the final token.
    // You will need to ensure your application does.
    if (!isset($_SESSION['SmugGalReqToken'])) {

        // Step 1: Get a request token using an optional callback URL back to ourselves
        $callback = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
        $request_token = $client->getRequestToken($callback);
        $_SESSION['SmugGalReqToken'] = serialize($request_token);

        // Step 2: Get the User to login to SmugMug and authorise this demo
        echo '
Click getAuthorizeURL(['Access' => 'Full']).'">HERE to Authorize This Demo.
'; // MJR
        // Alternatively, automatically direct your visitor by commenting out the above line in favour of this:
        //header("Location:".$client->getAuthorizeURL());
    } else {
        $reqToken = unserialize($_SESSION['SmugGalReqToken']);
        unset($_SESSION['SmugGalReqToken']);

        // Step 3: Use the Request token obtained in step 1 to get an access token
        $client->setToken($reqToken['oauth_token'], $reqToken['oauth_token_secret']);
        $oauth_verifier = $_GET['oauth_verifier'];  // This comes back with the callback request.
        $token = $client->getAccessToken($oauth_verifier);  // The results of this call is what your application needs to store.
        // Get the username of the authenticated user
        $username = $client->get('!authuser')->User->NickName;

        // List top level folders and albums.  // MJR
        $user = $client->get('!authuser'); // MJR
        $root = $client->get($user->User->Uris->Node); // MJR
        $children = $client->get($root->Node->Uris->ChildNodes); // MJR
        foreach ($children->Node as $v) { // MJR
            echo "
 $v->Type \"$v->Name\" $v->Uri"; // MJR
        } // MJR

    }
} catch (Exception $e) {
    echo "{$e->getMessage()} (Error Code: {$e->getCode()})";
}
?>


问:
IndexError: list index out of range when trying to program an argument
I keep getting IndexError: list index out of range when using the below snippets in a python script:

```<code>rhost = sys.argv[1] #target ip
rport = int(sys.argv[2]) #target port
</code>```

I do not really see the issue with the above code.  Any assistance would be most appreciated!

答: It was my mistake, I need to add a logic check in the script so that if there is not the appropriate amount of arguments it displays an error referencing the usage portion.</p>

Body:
I keep getting IndexError: list index out of range when using the below snippets in a python script:

rhost = sys.argv[1] #target ip
rport = int(sys.argv[2]) #target port

I do not really see the issue with the above code.  Any assistance would be most appreciated!


问:
Performance of recursion vs accumulator style
We have two functions that compute the factorial of a given number. The first one, !, uses an accumulator style. The second, fact, uses natural recursion.

```<code>(define (! n0)
  (local (;; accumulator is the product of all natural numbers in [n0, n)
      (define (!-a n accumulator)
        (cond
          [(zero? n) accumulator]
          [else (!-a (sub1 n) (* n accumulator))])))
    (!-a n0 1)))
</code>```

and

```<code>(define (fact n)
  (cond
    [(= 0 n) 1]
    [else (* n (fact (- n 1)))]))
</code>```

At the bottom of Section 31, HtDP states that the naturally recursive version is often as fast if not faster than the accumulator version, but does not state the reasons why. I did some reading on this and it seems that the answer is 'tail call optimization/elimination', but the Wikipedia article seems to be at odds with what HtDP says, at least with respect to performance. Why is this so?

At work, the recursive style is faster. At home, the accumulator style is faster. Is there no general heuristic to guide a choice as to which style is generally preferred? I understand that the accumulator-style is more memory-efficient, but if we restrict the discussion to performance alone, it is unclear, at least to me, which is the better choice.

I've thought about this a little further, and would have to side with the Wikipedia article on the superiority of the accumulator-style recursion in the general case. Not only does it reduce usage of stack/heap space, memory access is always going to be behind register access and can only be made more evident now that multicore is here. Still, HtDP proves that actual testing is required in all cases.

答:
I don't know the inners of the Racket compiler, but I'll speculate.

Tail calls are generally more expensive than normal calls (this is true in .NET, up to 7 times slower), but in some cases the tail call can be eliminated and it ends up being a while(1) { ... } C-style loop, hence there will be no extra calls to make, just a simply local jump, effectively eliminating procedure application overhead.

Body:
We have two functions that compute the factorial of a given number. The first one, !, uses an accumulator style. The second, fact, uses natural recursion.

(define (! n0)
  (local (;; accumulator is the product of all natural numbers in [n0, n)
      (define (!-a n accumulator)
        (cond
          [(zero? n) accumulator]
          [else (!-a (sub1 n) (* n accumulator))])))
    (!-a n0 1)))

and

(define (fact n)
  (cond
    [(= 0 n) 1]
    [else (* n (fact (- n 1)))]))

At the bottom of Section 31, HtDP states that the naturally recursive version is often as fast if not faster than the accumulator version, but does not state the reasons why. I did some reading on this and it seems that the answer is 'tail call optimization/elimination', but the Wikipedia article seems to be at odds with what HtDP says, at least with respect to performance. Why is this so?

At work, the recursive style is faster. At home, the accumulator style is faster. Is there no general heuristic to guide a choice as to which style is generally preferred? I understand that the accumulator-style is more memory-efficient, but if we restrict the discussion to performance alone, it is unclear, at least to me, which is the better choice.

I've thought about this a little further, and would have to side with the Wikipedia article on the superiority of the accumulator-style recursion in the general case. Not only does it reduce usage of stack/heap space, memory access is always going to be behind register access and can only be made more evident now that multicore is here. Still, HtDP proves that actual testing is required in all cases.


问:
Assembly x86-64 setting carry flag for sub instruction
I am working through Richard Detmer's Assembly Language book.

The first chapter states:

A borrow occurs in the subtraction a - b when b is larger than a as unsigned numbers. Computer hardware can detect a borrow in subtraction by looking at whether a carry occurred in the corresponding addition. If there is no carry in the addition, then there is a borrow in the subtraction. If there is a carry in the addition, then there is no borrow in the subtraction.

The carry flag is the 0th bit of the EFL register.

Suppose we want to perform 195D - 618D = -423D as a subtraction operation. There is a borrow and hence the carry flag should not be set.

The following asm code compiles and runs, yet after sub rax, 618, the carry flag is indeed set.

The corresponding addition would be 00C3h + FD96h and this does not involve a carry since the final pairwise addition is 0 + F with no carry into it and hence, there is no carry out of the final pairwise addition.

```<code> .DATA
number  QWORD   195
sum     QWORD   ?

.CODE
main    PROC
        mov     rax, number     ; 195 to RAX
        sub     rax, 618        ; subtract 618
             ;at this point, however, the carry flag is indeed set to 1. Why is this?
        mov     sum, rax        ; sum to memory

        mov     rax, 0          ; return code
        ret                     ; exit to operating system

main    ENDP

END
</code>```

I am unclear about how this could be.

Any help will be appreciated.

答:
First understand that there is unsigned integer arithmetic (where overflow is indicated by the carry flag) and signed integer arithmetic (where overflow is indicated by the overflow flag).

The same addition and subtraction instructions are used for both unsigned and signed integer arithmetic. The only difference is which flags you test afterwards and how you interpret the result (e.g. as -0x0000423D or as 0xFFFFBDC3).

A borrow is also indicated by the carry flag. This means that a borrow happens whenever an unsigned integer overflow happened. For 0x0000195D - 0x0000618D there is an unsigned integer overflow (unsigned integers can't be negative), so the carry flag will be set (but there wasn't a signed integer overflow, so the overflow flag won't be set). The result will be 0xFFFFBDC3 or -0x0000423D depending on whether the result was supposed to be signed or unsigned.

Body:
I am working through Richard Detmer's Assembly Language book.

The first chapter states:

A borrow occurs in the subtraction a - b when b is larger than a as unsigned numbers. Computer hardware can detect a borrow in subtraction by looking at whether a carry occurred in the corresponding addition. If there is no carry in the addition, then there is a borrow in the subtraction. If there is a carry in the addition, then there is no borrow in the subtraction.

The carry flag is the 0th bit of the EFL register.

Suppose we want to perform 195D - 618D = -423D as a subtraction operation. There is a borrow and hence the carry flag should not be set.

The following asm code compiles and runs, yet after sub rax, 618, the carry flag is indeed set.

The corresponding addition would be 00C3h + FD96h and this does not involve a carry since the final pairwise addition is 0 + F with no carry into it and hence, there is no carry out of the final pairwise addition.

 .DATA
number  QWORD   195
sum     QWORD   ?

.CODE
main    PROC
        mov     rax, number     ; 195 to RAX
        sub     rax, 618        ; subtract 618
             ;at this point, however, the carry flag is indeed set to 1. Why is this?
        mov     sum, rax        ; sum to memory

        mov     rax, 0          ; return code
        ret                     ; exit to operating system

main    ENDP

END

I am unclear about how this could be.

Any help will be appreciated.