问:
Get current location on Google Map - AngularJS
I'm trying to get the current location using Google Map with AngularJS.
This is my code:-

angular.module('indexAngularApp', ['uiGmapgoogle-maps'])
  .controller('mapsController', function($scope, $http) {
    //this is default coordinates for the map when it loads for first time

    var options = {
      enableHighAccuracy: true
    };

    navigator.geolocation.getCurrentPosition(function(pos) {
        $scope.map = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
        $scope.map.center.latitude = new google.maps.LatLng(pos.coords.latitude);
        $scope.map.center.longitude = new google.maps.LatLng(pos.coords.longitude);
        $scope.map.center.zoom = 15;

        //$scope.position.latitude = 28.699955;
        //$scope.position.longitude = 77.098159;

        //var a = $scope.position.latitude;
        //var b = $scope.position.longitude;

        //console.log(JSON.stringify($scope.map));

        //$scope.map.center.latitude = $scope.position.latitude;
        //$scope.map.center.longitude = data.data.Long;

        //   $scope.map =
        //{
        //    center:
        //    {
        //        latitude: a,
        //        longitude: b
        //    },

        //    zoom: 15
        //}

      },
      function(error) {
        alert('Unable to get location: ' + error.message);
      }, options);

    $scope.markers = [];
    $scope.locations = [];
    //to get all the locations from the server
    $http.get('http://localhost:4582/Api/NewCompWebAPI').then(function(data) {
      $scope.locations = data.data;
    }, function() {
      alert('Error');
    });
    //service that gets makers info from server
    $scope.ShowLocation = function(locationID) {
      $http.get('/home/GetMarkerData', {
        params: {
          locationID: locationID
        }
      }).then(function(data) {
        $scope.markers = [];
        $scope.markers.push({
          id: data.data.LocationID,
          coords: {
            latitude: data.data.Lat,
            longitude: data.data.Long
          },
          title: data.data.title, //title of the makers
          address: data.data.Address, //Address of the makers
          image: data.data.ImagePath //image --optional
        });
        //set map focus to center
        $scope.map.center.latitude = data.data.Lat;
        $scope.map.center.longitude = data.data.Long;
      }, function() {
        alert('Error'); //shows error if connection lost or error occurs
      });
    }
    //Show or Hide marker on map using options passes here
    $scope.windowOptions = {
      show: true
    };

  })

//mapsController Ends Here```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>input {
  padding: 5px;
  border: 1px solid #A5A5A5;
}

input.ng-dirty.ng-invalid {
  border: 1px solid red;
  background-color: rgb(255, 244, 244);
}

.error {
  color: red;
}

.angular-google-map-container {
  height: 300px;
  box-shadow: 2px 2px 3px 3px lightgrey;
}

.angular-google-map {
  width: 80%;
  height: 100%;
  margin: auto 0px;
}

</style></code>```

{{map.center}}

        <ui-gmap-google-map style="box-shadow:2px 2px 2px 2px lightgrey; width:100%" center="map.center" zoom="map.zoom">
          <ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
            <ui-gmap-window options="windowOptions" show="windowOptions.show">

{{marker.title}}

{{marker.address}}

                    No of Customers:

            </ui-gmap-window>
          </ui-gmap-marker>
        </ui-gmap-google-map>

{{l.UniqueName}}

```

Now the problem is I'm not able to get the current latitude and longitude of the device. Can anyone help me with this?

答:
Finally I just changed the IndesAngular.js file :-

angular.module('indexAngularApp', ['uiGmapgoogle-maps'])
        .controller('mapsController', function ($scope, $http) {
            //this is default coordinates for the map when it loads for first time
            var options = {
                enableHighAccuracy: true
            };

            navigator.geolocation.getCurrentPosition(function (pos) {
                $scope.position = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
                $scope.map = {
                    center:
                  {
                      latitude: pos.coords.latitude,
                      longitude: pos.coords.longitude
                  },
                  zoom:17
                };

                //console.log(JSON.stringify($scope.map));
            },
                        function (error) {
                            alert('Unable to get location: ' + error.message);
                        }, options);

            //$scope.map =
            //  {
            //      center:
            //      {
            //          latitude: 28.6315,
            //          longitude: 77.6315
            //      },
            //      zoom: 16
            //  }
            $scope.markers = [];
            $scope.locations = [];
            //to get all the locations from the server
            $http.get('http://localhost:4582/Api/NewCompWebAPI').then(function (data) {
                $scope.locations = data.data;
            }, function () {
                alert('Error');
            });
            //service that gets makers info from server
            //$scope.ShowLocation = function (locationID) {
            //    $http.get('/home/GetMarkerData',
            //    {
            //        params:
            //        {
            //            locationID: locationID
            //        }
            //    }).then(function (data) {
            //        $scope.markers = [];
            //        $scope.markers.push
            //        ({
            //            id: data.data.LocationID,
            //            coords:
            //            {
            //                latitude: data.data.Lat,
            //                longitude: data.data.Long
            //            },
            //            title: data.data.title, //title of the makers
            //            address: data.data.Address, //Address of the makers
            //            image: data.data.ImagePath //image --optional
            //        });
            //        //set map focus to center
            //        $scope.map.center.latitude = data.data.Lat;
            //        $scope.map.center.longitude = data.data.Long;
            //    }, function () {
            //        alert('Error'); //shows error if connection lost or error occurs
            //    });
            //}
            //Show or Hide marker on map using options passes here
            $scope.windowOptions =
              {
                  show: true
              };
        })
//mapsController Ends Here```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script></code>```

Body:
I'm trying to get the current location using Google Map with AngularJS.
This is my code:-

angular.module('indexAngularApp', ['uiGmapgoogle-maps'])
  .controller('mapsController', function($scope, $http) {
    //this is default coordinates for the map when it loads for first time

    var options = {
      enableHighAccuracy: true
    };

    navigator.geolocation.getCurrentPosition(function(pos) {
        $scope.map = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
        $scope.map.center.latitude = new google.maps.LatLng(pos.coords.latitude);
        $scope.map.center.longitude = new google.maps.LatLng(pos.coords.longitude);
        $scope.map.center.zoom = 15;

        //$scope.position.latitude = 28.699955;
        //$scope.position.longitude = 77.098159;

        //var a = $scope.position.latitude;
        //var b = $scope.position.longitude;

        //console.log(JSON.stringify($scope.map));

        //$scope.map.center.latitude = $scope.position.latitude;
        //$scope.map.center.longitude = data.data.Long;

        //   $scope.map =
        //{
        //    center:
        //    {
        //        latitude: a,
        //        longitude: b
        //    },

        //    zoom: 15
        //}

      },
      function(error) {
        alert('Unable to get location: ' + error.message);
      }, options);

    $scope.markers = [];
    $scope.locations = [];
    //to get all the locations from the server
    $http.get('http://localhost:4582/Api/NewCompWebAPI').then(function(data) {
      $scope.locations = data.data;
    }, function() {
      alert('Error');
    });
    //service that gets makers info from server
    $scope.ShowLocation = function(locationID) {
      $http.get('/home/GetMarkerData', {
        params: {
          locationID: locationID
        }
      }).then(function(data) {
        $scope.markers = [];
        $scope.markers.push({
          id: data.data.LocationID,
          coords: {
            latitude: data.data.Lat,
            longitude: data.data.Long
          },
          title: data.data.title, //title of the makers
          address: data.data.Address, //Address of the makers
          image: data.data.ImagePath //image --optional
        });
        //set map focus to center
        $scope.map.center.latitude = data.data.Lat;
        $scope.map.center.longitude = data.data.Long;
      }, function() {
        alert('Error'); //shows error if connection lost or error occurs
      });
    }
    //Show or Hide marker on map using options passes here
    $scope.windowOptions = {
      show: true
    };

  })

//mapsController Ends Here

{{map.center}}

        <ui-gmap-google-map style="box-shadow:2px 2px 2px 2px lightgrey; width:100%" center="map.center" zoom="map.zoom">
          <ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
            <ui-gmap-window options="windowOptions" show="windowOptions.show">

{{marker.title}}

{{marker.address}}

                    No of Customers:

            </ui-gmap-window>
          </ui-gmap-marker>
        </ui-gmap-google-map>

{{l.UniqueName}}

Now the problem is I'm not able to get the current latitude and longitude of the device. Can anyone help me with this?

Body:
Finally I just changed the IndesAngular.js file :-

angular.module('indexAngularApp', ['uiGmapgoogle-maps'])
        .controller('mapsController', function ($scope, $http) {
            //this is default coordinates for the map when it loads for first time
            var options = {
                enableHighAccuracy: true
            };

            navigator.geolocation.getCurrentPosition(function (pos) {
                $scope.position = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
                $scope.map = {
                    center:
                  {
                      latitude: pos.coords.latitude,
                      longitude: pos.coords.longitude
                  },
                  zoom:17
                };

                //console.log(JSON.stringify($scope.map));
            },
                        function (error) {
                            alert('Unable to get location: ' + error.message);
                        }, options);

            //$scope.map =
            //  {
            //      center:
            //      {
            //          latitude: 28.6315,
            //          longitude: 77.6315
            //      },
            //      zoom: 16
            //  }
            $scope.markers = [];
            $scope.locations = [];
            //to get all the locations from the server
            $http.get('http://localhost:4582/Api/NewCompWebAPI').then(function (data) {
                $scope.locations = data.data;
            }, function () {
                alert('Error');
            });
            //service that gets makers info from server
            //$scope.ShowLocation = function (locationID) {
            //    $http.get('/home/GetMarkerData',
            //    {
            //        params:
            //        {
            //            locationID: locationID
            //        }
            //    }).then(function (data) {
            //        $scope.markers = [];
            //        $scope.markers.push
            //        ({
            //            id: data.data.LocationID,
            //            coords:
            //            {
            //                latitude: data.data.Lat,
            //                longitude: data.data.Long
            //            },
            //            title: data.data.title, //title of the makers
            //            address: data.data.Address, //Address of the makers
            //            image: data.data.ImagePath //image --optional
            //        });
            //        //set map focus to center
            //        $scope.map.center.latitude = data.data.Lat;
            //        $scope.map.center.longitude = data.data.Long;
            //    }, function () {
            //        alert('Error'); //shows error if connection lost or error occurs
            //    });
            //}
            //Show or Hide marker on map using options passes here
            $scope.windowOptions =
              {
                  show: true
              };
        })
//mapsController Ends Here

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


来源: stackexchange

问:
Documenting a method that just returns something
I'm writing some javadocs (actually they are jsdocs but it doesn't make a difference for this question) and found this repeating pattern:

Imagine a method that just returns a value, maybe product of some calculation. For example, let say it is the time in milliseconds since the unix epoch.

```<code>public long getTimeSinceTheEpoch(){

  //calculate time

  return time;
}
</code>```

So far, so good. Now when the time comes to add javadocs (or jsdocs, or rdocs, whatever), I've been writing something like this:

```<code>/**
* Gets the time in milliseconds since the unix epoch
*
* @returns the time in milliseconds since the unix epoch
*/
public long getTimeSinceTheEpoch(){
</code>```

Here, the problem is obvious.

My question is, what do you put in the body of the comment, and what do you choose for the @returns attribute of the comment?

IMPORTANT

I'm not a fan of these kind of comments, if it depended on me I would rename the method to something like getTimeInMillisecondsSinceTheEpoch and avoid the comments at all.

I cannot do that (avoid the comments), so I'm striving to make them as useful as possible.

答:
The Sun (now Oracle) style guide "How to Write Doc Comments for the Javadoc Tool" recommends this:

The @return tag is required for every
  method that returns something other
  than void, even if it is redundant
  with the method description. (Whenever
  possible, find something non-redundant
  (ideally, more specific) to use for
  the tag comment.)

I'm not fond of the redundancy, and it goes against the DRY principle. Personally, I either make one a summary and the other a detail (as suggested above), or provide only an @return. As you point out, the name of a simple getter may suffice as the summary.

ContentLicense: CC BY-SA 2.5

Body:
I'm writing some javadocs (actually they are jsdocs but it doesn't make a difference for this question) and found this repeating pattern:

Imagine a method that just returns a value, maybe product of some calculation. For example, let say it is the time in milliseconds since the unix epoch.

public long getTimeSinceTheEpoch(){

  //calculate time

  return time;
}

So far, so good. Now when the time comes to add javadocs (or jsdocs, or rdocs, whatever), I've been writing something like this:

/**
* Gets the time in milliseconds since the unix epoch
*
* @returns the time in milliseconds since the unix epoch
*/
public long getTimeSinceTheEpoch(){

Here, the problem is obvious.

My question is, what do you put in the body of the comment, and what do you choose for the @returns attribute of the comment?

IMPORTANT

I'm not a fan of these kind of comments, if it depended on me I would rename the method to something like getTimeInMillisecondsSinceTheEpoch and avoid the comments at all.

I cannot do that (avoid the comments), so I'm striving to make them as useful as possible.


问:
Why does PyCharm give unresolved reference errors on some Numpy imports?
The following line in PyCharm is flagged by on-the-fly inspection with unresolved reference errors for each import. (They are underlined red.)

```<code>from numpy import tan, arcsin, arccos, arctan
</code>```

However the following imports do not cause any error/warning:

```<code>from numpy import sin, cos, arctan2, sqrt, cross, pi
</code>```

The code in which I use these imports runs fine without any errors or warnings.  I generally rely on PyCharm's red errors as a warning that my code is broken and will not run, but in this case PyCharm is wrong.

Why are some of numpy's functions recognized by PyCharm's introspection and others aren't?

Current Versions:

Windows 7 64-bit

Python 2.7.5

PyCharm 3.1.2

Numpy 1.8

Thanks!

答:
The Python configuration is specified in (at least) two places:  Run | Edit Configurations | Python | Python Interpreter, and File | Settings | Project | Project Interpreter.  My mistake was I did not set the correct Python installation in the File | Settings ....  Hence, it was referring to a Python configuration that did not have the import installed (e.g. NumPy).

After I set these two locations to point to the same, correct Python installation, I did a File | Invalidate Caches / Restart, then it was fine.

A third place to check is File | Default Settings... | Project Interpreter and make sure it matches the other settings.

ContentLicense: CC BY-SA 3.0

Body:
The following line in PyCharm is flagged by on-the-fly inspection with unresolved reference errors for each import. (They are underlined red.)

from numpy import tan, arcsin, arccos, arctan

However the following imports do not cause any error/warning:

from numpy import sin, cos, arctan2, sqrt, cross, pi

The code in which I use these imports runs fine without any errors or warnings.  I generally rely on PyCharm's red errors as a warning that my code is broken and will not run, but in this case PyCharm is wrong.

Why are some of numpy's functions recognized by PyCharm's introspection and others aren't?

Current Versions:

Windows 7 64-bit

Python 2.7.5

PyCharm 3.1.2

Numpy 1.8

Thanks!


问:
How to clean up a string excluding certain characters
I want to clean up the below string but only get rid of the \n, \r and extra spaces but not the apostrophe(') and other characters like dash(-) and colon(:).

Right now I am using this code but it gets rid of all special characters.

```<code>string = "\n\n\r\n            Scott Hibb's Amazing Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
rx = re.compile('\W+')
string = rx.sub(' ', string).strip()
print(string)
</code>```

How can i do this?

答:
You can use filter() and strip() to remove \n, \t, \r and extra whitespaces while preserving rest of the characters, something like this :

```<code>string = "\n\n\r\n       Scott Hibb's       Amazing    Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
print(' '.join(filter(None, string.strip().split())))
</code>```

This will result in :

```<code>Scott Hibb's Amazing Whisky Grilled Baby Back Ribs
</code>```

Body:
I want to clean up the below string but only get rid of the \n, \r and extra spaces but not the apostrophe(') and other characters like dash(-) and colon(:).

Right now I am using this code but it gets rid of all special characters.

string = "\n\n\r\n            Scott Hibb's Amazing Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
rx = re.compile('\W+')
string = rx.sub(' ', string).strip()
print(string)

How can i do this?

Body:
You can use filter() and strip() to remove \n, \t, \r and extra whitespaces while preserving rest of the characters, something like this :

string = "\n\n\r\n       Scott Hibb's       Amazing    Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
print(' '.join(filter(None, string.strip().split())))

This will result in :

Scott Hibb's Amazing Whisky Grilled Baby Back Ribs


问:
WARNING c3p0: Another error has occurred: Connection is Closed
We are using c3p0 as the connection pool in our application with Microsoft SQL Database. The connections are tested on checkout with validation query so that application doesn't work with stale connections.

Recently, we have started seeing following warning in the application logs (a lot of these messages are present in sequence). Anyone have seen this sort of exception and what does it mean?

```<code>2017-03-29 09:34:24 [WARNING] [c3p0] A PooledConnection that has already signalled a Connection error is still in use!
2017-03-29 09:34:24 [WARNING] [c3p0] Another error has occurred [ com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed. ] which will not be reported to listeners!
2017-03-29 09:34:24 com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.
2017-03-29 09:34:24     at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
2017-03-29 09:34:24     at com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(SQLServerConnection.java:388)
2017-03-29 09:34:24     at com.microsoft.sqlserver.jdbc.SQLServerConnection.prepareStatement(SQLServerConnection.java:2166)
2017-03-29 09:34:24     at com.microsoft.sqlserver.jdbc.SQLServerConnection.prepareStatement(SQLServerConnection.java:1853)
2017-03-29 09:34:24     at com.mchange.v2.c3p0.impl.NewProxyConnection.prepareStatement(NewProxyConnection.java:1076)
</code>```

My concerns are:

Does this warning (or exception message) mean that the query had actually failed to execute and the code will throw the exception?

Is it just a warning message that is logged by c3p0 because we test connection on checkout and since the connection is closed, it will now acquire a new connection from the database and the application will run without any issue?

Any help will be appreciated. Thanks!

答:
So, there's not enough information here to say what the initial cause of the problem was. Anything could have happened, a network outage, whatever. Testing a Connection on checkout ensures that the Connection worked at the time of checkout, but once in client-land, nothing prevents a break. It should be very, unless you are keeping Connections checked out for long periods of time. (Don't do that! With a Connection pool, adopt a just-in-time, quick checkout, immediate check-in strategy.)

Anyway, some attempt by the application to use the Connection threw an Exception. c3p0 internally checked the Connection then, decided the Connection was broken, and emitted an event (specified by the JDBC spec, but of interest only to internal listeners) indicating a Connection error. c3p0 responds to this by marking the Connection for destruction rather than check-in when the application is done.

The application, despite having seen the first Exception, continued to use the Connection. A second Exception occurred (yes, this Connection really is broken). That's what c3p0 is logging here. It's ignoring the second Exception, not signaling a Connection error, because a Connection error has already been signalled for this Connection. But it's a bit surprised and annoyed to find that the Connection is still in use ;)

All exceptions are relayed to the application. Silently swallowing up problems is the very opposite of c3p0's philosophy. But whatever your application was doing with this Connection triggered an Exception, and your application kept doing other things that triggered more.

That doesn't necessarily mean that anything is wrong. An application may tentatively interpret an Exception as something other than a Connection failure. Perhaps an Exception occurred because of a constraint violation, and if so, there is a workaround? If it were something like that, here the application would find further evidence that, yes, the Connection is broken, because this next use of the Connection, after a previous Exception had been handled, will continue to fail.

If I were you, I'd review the application code that triggers this stack trace, and look particularly for Exception handling in prior steps that might be too forgiving, that might catch an Exception and continue when it should instead abort. Again, that's not necessarily the case -- it could be that your application is doing exactly what it should, it's appropriately retrying or attempting to continue after a potentially recoverable error, and it's robust to the possibility that the retry will fail too, in which case you'll just harmlessly see these stack traces in your logs, hopefully very rarely, when already-checked-out Connections fail. But I'd definitely review your Exception handling logic in this code path, during the step that triggered the stack trace, and importantly during prior steps which would have triggered the first Exception. Usually one Exception aborts a database codepath (except for an eventual rollback() and close()), here you are barreling on to a second, which may well be awesome, but make sure it is what you want to do.

If you are seeing this a lot, make sure Connection testing on checkout really is configured properly, then try to minimize the period during which the Connection is checked out, then try to understand why your network or something at the server side might be failing occasionally.

Body:
We are using c3p0 as the connection pool in our application with Microsoft SQL Database. The connections are tested on checkout with validation query so that application doesn't work with stale connections.

Recently, we have started seeing following warning in the application logs (a lot of these messages are present in sequence). Anyone have seen this sort of exception and what does it mean?

2017-03-29 09:34:24 [WARNING] [c3p0] A PooledConnection that has already signalled a Connection error is still in use!
2017-03-29 09:34:24 [WARNING] [c3p0] Another error has occurred [ com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed. ] which will not be reported to listeners!
2017-03-29 09:34:24 com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.
2017-03-29 09:34:24     at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
2017-03-29 09:34:24     at com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(SQLServerConnection.java:388)
2017-03-29 09:34:24     at com.microsoft.sqlserver.jdbc.SQLServerConnection.prepareStatement(SQLServerConnection.java:2166)
2017-03-29 09:34:24     at com.microsoft.sqlserver.jdbc.SQLServerConnection.prepareStatement(SQLServerConnection.java:1853)
2017-03-29 09:34:24     at com.mchange.v2.c3p0.impl.NewProxyConnection.prepareStatement(NewProxyConnection.java:1076)

My concerns are:

Does this warning (or exception message) mean that the query had actually failed to execute and the code will throw the exception?

Is it just a warning message that is logged by c3p0 because we test connection on checkout and since the connection is closed, it will now acquire a new connection from the database and the application will run without any issue?

Any help will be appreciated. Thanks!


问:
How to convert 'QVideoFrame' with YUV data to 'QVideoframe' with RGBA32 data in Qt?
I receive QVideoFrames from webcam, and they contain image data in YUV format (QVideoFrame::Format_YUV420P). How can I convert one such frame to one with QVideoFrame::Format_ARGB32 or QVideoFrame::Format_RGBA32?

Can I do it without going low level, using just existing functionality in Qt5?

Example:

```<code>QVideoFrame convertFormat(const QVideoFrame &inputframe, QVideoFrame::PixelFormat outputFormat)
{
    // What comes here?
}

//Usage
QVideoFrame converted = convertFormat(mySourceFrame, QVideoFrame::Format_RGB32);
</code>```

答:
https://doc.qt.io/qt-5/qvideoframe.html#map</p>

```<code>if (inputframe.map(QAbstractVideoBuffer::ReadOnly))
{
    int height = inputframe.height();
    int width = inputframe.width();
    uchar* bits = inputframe.bits();
    // figure out the inputFormat and outputFormat, they should be QImage::Format
    QImage image(bits, width, height, inputFormat);
    // do your conversion
    QImage outImage = image.convertToForma(outFormat); // blah convert
    return QVideoFrame(outImage);
}
</code>```

Body:
I receive QVideoFrames from webcam, and they contain image data in YUV format (QVideoFrame::Format_YUV420P). How can I convert one such frame to one with QVideoFrame::Format_ARGB32 or QVideoFrame::Format_RGBA32?

Can I do it without going low level, using just existing functionality in Qt5?

Example:

QVideoFrame convertFormat(const QVideoFrame &inputframe, QVideoFrame::PixelFormat outputFormat)
{
    // What comes here?
}

//Usage
QVideoFrame converted = convertFormat(mySourceFrame, QVideoFrame::Format_RGB32);

Body:
https://doc.qt.io/qt-5/qvideoframe.html#map

if (inputframe.map(QAbstractVideoBuffer::ReadOnly))
{
    int height = inputframe.height();
    int width = inputframe.width();
    uchar* bits = inputframe.bits();
    // figure out the inputFormat and outputFormat, they should be QImage::Format
    QImage image(bits, width, height, inputFormat);
    // do your conversion
    QImage outImage = image.convertToForma(outFormat); // blah convert
    return QVideoFrame(outImage);
}


问:
Determining register values when using objdump
So I'm trying to use the objdump utility to build a Control Flow Graph from assembly, and I'm running into a problem. Basically, whenever a branch occurs and the target address is relative I'm not sure how to know where the next basic block starts. I'm not sure if I'm being clear, so I'll add an example. Say my program is going through the objdump output, and has recorded the starting address for the first basic block. It then hits a jump command that uses relative addressing to point to the proper address to jump to. I know that the end of my first basic block occurs right there, but how do I go about getting the right address for the beginning of the next basic block? Any guidance anyone can provide would be greatly appreciated, I'm an x86 novice at best and I've been banging my head against this for the past week.</p>

答:
Assuming I understand the question, maybe this will get you started.  Relative jumps are pc based.

```
d: eb 04 jmp 13
```

0xEB is the opcode for a relative jump based on an 8 bit immediate.  The address of the instruction is in the objdump output, in this case d or 0xD.  it is a two byte instruction (x86 is variable length).  it tells you in the output what the destination address is, in this case jmp 13.  So looking for the line in the objdump output that starts with 13 and a colon is the beginning of that next chunk of code.

To understand how that address is computed.  The pc is at 0xD when it starts to fetch the instruction, it takes two bytes, so the pc is at 0xD+2 = 0xF when it is ready to execute this instruction.  The offset is 0x4 so 0xF+0x4 = 0x13 the destination address.

```
20: 75 ed jne f
```

Same goes for backwards.  pc plus number of bytes = 0x20+2 = 0x22.  0xED is a signed number and is negative so sign extend 0xED to 0xFFFFFFF...FFFFED, however big your address register is. Add 0x22+0xFFFFFF...FFFED and you get 0x0F the destination address.  You can also take 0xED, invert and add 1 to negate it.  ~0xED = 0x12, 0x12+1 = 0x13.  So 0xED means subtract 0x13.  0x22-0x13=0x0F.

Here are some more, in each case it gives you the target address which you can just look for in the objdump output.

To understand how it computes that value.  Same story, start with opcode at 0x400A81, it takes 6 bytes in this case for the variable length instruction.  So by the time you are ready to execute the pc is at 0x400A81+6 = 0x400A87.  The offset is 0x107 so if the condition is met the destination address is 0x400A87 + 0x107 = 0x400B8E.

Note these are grepped from a larger program, not sequential code, just a collection of isolated examples.

```
  400a81:   0f 8f 07 01 00 00       jg     400b8e
  400a8f:   0f 8f e6 00 00 00       jg     400b7b
  400a9d:   0f 8f c5 00 00 00       jg     400b68
  400aab:   0f 8f a4 00 00 00       jg     400b55
  400ab9:   0f 8f 83 00 00 00       jg     400b42
  401d76:   0f 8f 31 01 00 00       jg     401ead
```

Body:
Assuming I understand the question, maybe this will get you started.  Relative jumps are pc based.

d: eb 04 jmp 13

0xEB is the opcode for a relative jump based on an 8 bit immediate.  The address of the instruction is in the objdump output, in this case d or 0xD.  it is a two byte instruction (x86 is variable length).  it tells you in the output what the destination address is, in this case jmp 13.  So looking for the line in the objdump output that starts with 13 and a colon is the beginning of that next chunk of code.

To understand how that address is computed.  The pc is at 0xD when it starts to fetch the instruction, it takes two bytes, so the pc is at 0xD+2 = 0xF when it is ready to execute this instruction.  The offset is 0x4 so 0xF+0x4 = 0x13 the destination address.

20: 75 ed jne f

Same goes for backwards.  pc plus number of bytes = 0x20+2 = 0x22.  0xED is a signed number and is negative so sign extend 0xED to 0xFFFFFFF...FFFFED, however big your address register is. Add 0x22+0xFFFFFF...FFFED and you get 0x0F the destination address.  You can also take 0xED, invert and add 1 to negate it.  ~0xED = 0x12, 0x12+1 = 0x13.  So 0xED means subtract 0x13.  0x22-0x13=0x0F.

Here are some more, in each case it gives you the target address which you can just look for in the objdump output.

To understand how it computes that value.  Same story, start with opcode at 0x400A81, it takes 6 bytes in this case for the variable length instruction.  So by the time you are ready to execute the pc is at 0x400A81+6 = 0x400A87.  The offset is 0x107 so if the condition is met the destination address is 0x400A87 + 0x107 = 0x400B8E.

Note these are grepped from a larger program, not sequential code, just a collection of isolated examples.

  400a81:   0f 8f 07 01 00 00       jg     400b8e
  400a8f:   0f 8f e6 00 00 00       jg     400b7b
  400a9d:   0f 8f c5 00 00 00       jg     400b68
  400aab:   0f 8f a4 00 00 00       jg     400b55
  400ab9:   0f 8f 83 00 00 00       jg     400b42
  401d76:   0f 8f 31 01 00 00       jg     401ead


问:
Autoscroll to TOP with ui-router and Angularjs
I've read so many different problems with this and none of the solution given seem to fit my use case.  I started by simply putting target="_top" on all my links, but that actually forces my app to reload which wont work.  I've also seen people say they use autoscroll="true" but that only seems to work if its within my ui-view.

The issue with this is that in my index.html file I have fixed nav and other static elements that are above my first ui-view.  This means when I go to other pages I lose the navigation as the page loads past those elements.  I've also tried putting this on the body with:

```<code><body autoscroll="true">
</body>
</code>```

This doesn't seem to do anything either.  So the question is, how can I make sure that new pages (new route changes from ui-router) result in starting at the top of the page? THANKS!

答:
There is an Angular service for this.
https://docs.angularjs.org/api/ng/service/$anchorScroll

Sample Code:

```<code>.run(function ($rootScope, $state, $stateParams, $anchorScroll) {

    $rootScope.$on('$stateChangeStart', function () {
        $anchorScroll();
    });

});
</code>```

If you want to scroll to a specific element

```<code>.run(function ($rootScope, $state, $stateParams, $anchorScroll) {

    $rootScope.$on('$stateChangeStart', function () {
       // set the location.hash to the id of
       // the element you wish to scroll to.
        $location.hash('bottom');

       // call $anchorScroll()
        $anchorScroll();
    });

});
</code>```

Body:
I've read so many different problems with this and none of the solution given seem to fit my use case.  I started by simply putting target="_top" on all my links, but that actually forces my app to reload which wont work.  I've also seen people say they use autoscroll="true" but that only seems to work if its within my ui-view.

The issue with this is that in my index.html file I have fixed nav and other static elements that are above my first ui-view.  This means when I go to other pages I lose the navigation as the page loads past those elements.  I've also tried putting this on the body with:

This doesn't seem to do anything either.  So the question is, how can I make sure that new pages (new route changes from ui-router) result in starting at the top of the page? THANKS!

Body:
There is an Angular service for this.
https://docs.angularjs.org/api/ng/service/$anchorScroll

Sample Code:

.run(function ($rootScope, $state, $stateParams, $anchorScroll) {

    $rootScope.$on('$stateChangeStart', function () {
        $anchorScroll();
    });

});

If you want to scroll to a specific element

.run(function ($rootScope, $state, $stateParams, $anchorScroll) {

    $rootScope.$on('$stateChangeStart', function () {
       // set the location.hash to the id of
       // the element you wish to scroll to.
        $location.hash('bottom');

       // call $anchorScroll()
        $anchorScroll();
    });

});


问:
Vue with Browserify on Runtime only build
I've been trying to figure this one out but I always get

[Vue warn]: You are using the runtime-only build of Vue where the
  template compiler is not available. Either pre-compile the templates
  into render functions, or use the compiler-included build.  (found in
  )

I'm using laravel 5.2 with browserify with elixir and vue 2.2.2

I'm trying to display a simple view

this is my app.js

import Vue from 'vue';

  import Test from './components/Test.vue';

new Vue({     el : '.container',  render: h => h(Test) })

Test.vue

```<code><template>
    <div class="view">
        <h1>{{msg}} </h1>
    </div>
</template>

<script type="text/javascript">
export default {
    data (){
        return {
            msg : 'This is Vue'
        }
    }
}
</script>

<style>
    div.view{
        padding:2em;
        position: relative;
    }

</style>
</code>```

答:
Are you using laravel-elixir-vueify? Try using laravel-elixir-vue-2 instead..you can also try to set the vue.common.js inside "browser" of package.json (i'm using npm with gulp and browserify)..like:</p>

```<code>"browse": { "vue": "vue/dist/vue.common.js" }
</code>```

Body:
I've been trying to figure this one out but I always get

[Vue warn]: You are using the runtime-only build of Vue where the
  template compiler is not available. Either pre-compile the templates
  into render functions, or use the compiler-included build.  (found in
  )

I'm using laravel 5.2 with browserify with elixir and vue 2.2.2

I'm trying to display a simple view

this is my app.js

import Vue from 'vue';

  import Test from './components/Test.vue';

new Vue({     el : '.container',  render: h => h(Test) })

Test.vue

<template>

{{msg}}

</template>

Body:
Are you using laravel-elixir-vueify? Try using laravel-elixir-vue-2 instead..you can also try to set the vue.common.js inside "browser" of package.json (i'm using npm with gulp and browserify)..like:

"browse": { "vue": "vue/dist/vue.common.js" }


问:
watson special character, repeat posts, and url handling
in using watson personality insights API, i've already note some odd trends, including many scored at a mean value across dimensions (e.g. agreeableness with many around .27), making me thing it's imputing to something.

Upon review I've note a language misalign issue (i.e. if it thinks it's english, you could get weird results if it's, say spanish), which has lead me to ask, but not find answer to:

how does watson handle:
1) urls in the message (e.g. many twitter posts have urls)
2) repeat posts (many channels repeat post things many times)
3) special characters (many posts have a ton of random special characters)

My goal is to determine how much pre-processing I need to do to make watson most effective.

答:
You are correct that if the language is mis-aligned then you will get incorrect results.

The Pi API determines the language first from the content-language header. If that is missing then if the content-type is json, then it looks at the language in the json content, selecting the language that has the highest number of occurrences, and finally, if that is missing it will default to the default language, namely English.

So in short, the recommendation (which will become required in a future update), is to always send in the content-language header.

Secondly, to your question on the content:
- URLs: the service will attempt to remove these. I won't guarantee that it removes every possible option as the url spec has some very esoteric options but we will remove the common formats.
- Repeat Posts: if you send in the same post twice, then it will be counted twice. We do no de-duplication in the text that is sent into the service.
- Special Characters; I'm assuming you are referring to emojis here. These are included in our processing as the underlying models were trained on data that included them as well, and thus they are one of the many signals the service uses.


问:
Bitwise operation with difference in order of comparison - (0 to 1) vs (1 to 0)
I have a problem in which there are two sets of bits being compared. The first is the initial state, and the second is the new state.

```<code>Initial State 1010
New State     1100
</code>```

I want to bitwise compare these bitsets and generate a third bitset which represents all bits that went high (0->1) but NOT those that went low (1->0)

```<code>Desired Result 0100
</code>```

Bits are high which were initially 0 and went to 1. Bits that were high and went low are ignored, so OR and XOR don't seem quite right.

Is there an elegant way to accomplish this with bitwise operators?

答:
In other words, you are looking for the bits that are not set in the initial state and are set in the new state. So:

```<code>LOW2HIGH = ~INITIAL & NEW
</code>```

Body:
I have a problem in which there are two sets of bits being compared. The first is the initial state, and the second is the new state.

Initial State 1010
New State     1100

I want to bitwise compare these bitsets and generate a third bitset which represents all bits that went high (0->1) but NOT those that went low (1->0)

Desired Result 0100

Bits are high which were initially 0 and went to 1. Bits that were high and went low are ignored, so OR and XOR don't seem quite right.

Is there an elegant way to accomplish this with bitwise operators?

Body:
In other words, you are looking for the bits that are not set in the initial state and are set in the new state. So:

LOW2HIGH = ~INITIAL & NEW


问:
How to return a bool to the outside function when you have nested functions in Swift?
So I have a function I have that has an inner function that connects to a Firebase database. the function returns a bool but I need the to return true or false based on whats inside the Firebase database. So basically I need to return true or false inside of the Firebase function the problem is it thinks that I am trying to return to the Firebase function when I am actually trying to return to the outside function a simple example is this

```<code>func someOtherFunc(name: String, lastname: String){

}
func someFunc(name: String, lastname: String) -> bool {
    someOtherFunc(name: name, lastname: lastname) {
        if name == "George" {
        return true

        } else {
        return false // will not work because some other func does not return a value
        }

    }
}
</code>```

here is the code that I need fixed which is a little more complicated than the above function because the inner Firebase function runs asynchronously(in the background) and so all the code inside the function needs to run synchronously to return the correct value

Here is my function

```<code>func takeAwayMoney(_ howMuch: String) -> Bool{
        if let notMuch = Int(howMuch) {

            let userID = FIRAuth.auth()?.currentUser?.uid
            datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                let money = value?["money"] as? String ?? ""

                //convert money to int
                if let conMoney = Int(money) {
                    var conMoreMoney = conMoney
                    if conMoreMoney < notMuch {
                        print(" sorry you don't have enough money")
                        return false
                    } else {
                        conMoreMoney -= notMuch
                        let values = ["money": String(conMoreMoney)]

                        //update the users money
                        self.datRef.child("User").child(userID!).updateChildValues(values)
                        return true //doesn't work because of example above
                    }

                }

                // ...
            }) { (error) in
                print(error.localizedDescription)
            }
        }
    }
</code>```

This code does not compile because there is no return values to the main function.

I know the really hard way to fix this would be to initialize values at the top of the function that would be the money of the user then check it after dispatching it for  a couple of seconds then you could return the values, but I know there must be another way because this way would cause a lot of problems.

答:
The root cause is that takeAwayMoney is synchronous, but it uses observeSingleEvent, which is asynchronous.

The "right" way to solve this is to make takeAwayMoney return Void, but take a completion function that will give you the bool asynchronously, like this:

```<code>func takeAwayMoney(_ howMuch: String, completion: @escaping (Bool)->()) -> Void {

/// When you want to "return" the bool, call the completion. e.g.:
// ...
                if conMoreMoney < notMuch {
                    print(" sorry you don't have enough money")
                    completion(false)
                    return // if you want to stop processing
                }
// ...

}
</code>```

If you cannot do this, then takeMoney needs to wait for the completion to finish and you use semaphores to have them communicate with each other.  You do not just wait a couple of seconds.  See this for an example:

Semaphores to run asynchronous method synchronously

Body:
So I have a function I have that has an inner function that connects to a Firebase database. the function returns a bool but I need the to return true or false based on whats inside the Firebase database. So basically I need to return true or false inside of the Firebase function the problem is it thinks that I am trying to return to the Firebase function when I am actually trying to return to the outside function a simple example is this

func someOtherFunc(name: String, lastname: String){

}
func someFunc(name: String, lastname: String) -> bool {
    someOtherFunc(name: name, lastname: lastname) {
        if name == "George" {
        return true

        } else {
        return false // will not work because some other func does not return a value
        }

    }
}

here is the code that I need fixed which is a little more complicated than the above function because the inner Firebase function runs asynchronously(in the background) and so all the code inside the function needs to run synchronously to return the correct value

Here is my function

func takeAwayMoney(_ howMuch: String) -> Bool{
        if let notMuch = Int(howMuch) {

            let userID = FIRAuth.auth()?.currentUser?.uid
            datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                let money = value?["money"] as? String ?? ""

                //convert money to int
                if let conMoney = Int(money) {
                    var conMoreMoney = conMoney
                    if conMoreMoney < notMuch {
                        print(" sorry you don't have enough money")
                        return false
                    } else {
                        conMoreMoney -= notMuch
                        let values = ["money": String(conMoreMoney)]

                        //update the users money
                        self.datRef.child("User").child(userID!).updateChildValues(values)
                        return true //doesn't work because of example above
                    }

                }

                // ...
            }) { (error) in
                print(error.localizedDescription)
            }
        }
    }

This code does not compile because there is no return values to the main function.

I know the really hard way to fix this would be to initialize values at the top of the function that would be the money of the user then check it after dispatching it for  a couple of seconds then you could return the values, but I know there must be another way because this way would cause a lot of problems.

Body:
The root cause is that takeAwayMoney is synchronous, but it uses observeSingleEvent, which is asynchronous.

The "right" way to solve this is to make takeAwayMoney return Void, but take a completion function that will give you the bool asynchronously, like this:

func takeAwayMoney(_ howMuch: String, completion: @escaping (Bool)->()) -> Void {

/// When you want to "return" the bool, call the completion. e.g.:
// ...
                if conMoreMoney < notMuch {
                    print(" sorry you don't have enough money")
                    completion(false)
                    return // if you want to stop processing
                }
// ...

}

If you cannot do this, then takeMoney needs to wait for the completion to finish and you use semaphores to have them communicate with each other.  You do not just wait a couple of seconds.  See this for an example:

Semaphores to run asynchronous method synchronously


问:
Confused on how to use arrays with an object with the calculation on another class.
I am making a program that finds the area of square. The calculation is done on another class. I have to use an array with values 1-10. I have to find the squares of those numbers in the array using the property from the other class. I am confused on how to do that. This is what I have done so far.

```<code>using System;
using Square;

namespace DemoSquares
{
    public class DemoSquares
    {
        static void Main()
    {
        int[] numbers = new int[10];

        Squares asquare = new Squares();

        asquare.Length = numbers[0];

        foreach (int i in numbers)
        {
            Console.WriteLine("{0}", i, asquare.Area);

        }
    }
}
</code>```

}
This is the class.
    using System;

```<code>namespace Square
{
    class Squares
    {

    private int length;
    private int area;
    public int Length
    {
        get
        {
            return length;
        }
        set
        {
            length = value;
            CalcArea();
        }
    }
    public int Area
    {
        get
        {
            return area;
        }
    }
    private void CalcArea()
    {
        area = Length * Length;
    }
}
</code>```

}

答:
I'am not shure if I understand you but this may work:</p>

```<code>foreach (int i in numbers)
{
    asquare.Length = i;
    asquare.CalcArea();
    Console.WriteLine("Area for {0}: {1}", i, asquare.Area);
}
</code>```

Body:
I am making a program that finds the area of square. The calculation is done on another class. I have to use an array with values 1-10. I have to find the squares of those numbers in the array using the property from the other class. I am confused on how to do that. This is what I have done so far.

using System;
using Square;

namespace DemoSquares
{
    public class DemoSquares
    {
        static void Main()
    {
        int[] numbers = new int[10];

        Squares asquare = new Squares();

        asquare.Length = numbers[0];

        foreach (int i in numbers)
        {
            Console.WriteLine("{0}", i, asquare.Area);

        }
    }
}

}
This is the class.
    using System;

namespace Square
{
    class Squares
    {

    private int length;
    private int area;
    public int Length
    {
        get
        {
            return length;
        }
        set
        {
            length = value;
            CalcArea();
        }
    }
    public int Area
    {
        get
        {
            return area;
        }
    }
    private void CalcArea()
    {
        area = Length * Length;
    }
}

}

Body:
I'am not shure if I understand you but this may work:

foreach (int i in numbers)
{
    asquare.Length = i;
    asquare.CalcArea();
    Console.WriteLine("Area for {0}: {1}", i, asquare.Area);
}


问:
Apache (xamp) and IIS cannot work together
I have XAMP 1.6.8 and IIS 5.0 installed on my PC(Windows XP SP3).

I'm unable to run them simultaneously. If IIS service is running, Apache throws the following error:

(OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down Unable to open logs Note the errors or messages above, and press the key to exit. 24...

Windows could not start the Apache2 on Local Computer. For more information, review the System Event Log. If this is a non-Microsoft service, contact the service vendor, and refer to service-specific error code 1.

Edit:

Apache runs on a different port 3128. And IIS (asp.net) usually runs on a different port.

答:
"could not bind to address 0.0.0.0:80" means that, when it starts up, it tries to bind to port 80 on all available network interfaces. As IIS already has hogged one (or more) IPs to bind to, apache cannot get any and so will fail.

(I'm not sure if it will bind to any available IPs if you've configured it to bind to all, but one is already taken.)

So, configure Apache to bind to a different port (if you only have 1 IP address), or to bind to a different IP or range of IPs.

You do this by changing the binding. First find the Listen directive in the configuration file (httpd.conf) and change it. Currently it will say "Listen 80" (meaning all IPs), change it to say "Listen 192.168.0.2:80" to make it bind to that specified IP address.

You may have to edit the IIS configuration too to tell it to only bind to a single IP address too.

LastEditorDisplayName: Peter Hilton

OwnerDisplayName: gbjbaanb


问:
How can I implement a makefile-style algorithm in python
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.

The input to this feature extraction system will be a graph detailing the links between the feature extraction blocks, and I'd like to work out which functions to run when based upon the graph.

An example of such a system might be the following:

```<code>            ,-> [B] -> [D] ----+
input --> [A]           ^      v
            `-> [C] ----+---> [E] --> output
</code>```

and the function calls (assuming each block X is a function of the form output = X(inputs) might be something like:

```<code>a = A(input)
b = B(a)
c = C(a)
d = D(b,c)  # can't call D until both b and c are ready
output = E(d,c)   # can't call E until both c and d are ready
</code>```

I already have the function graph loaded in the form of a dictionary with each dictionary entry of the form (inputs, function) like so:

```<code>blocks = {'A' : (('input'), A),
          'B' : (('A'), B),
          'C' : (('A'), C),
          'D' : (('B','C'), D),
          'output' : (('D','C'), E)}
</code>```

I'm just currently drawing a blank on what the makefile algorithm does exactly, and how to go about implementing it. My google-fu appears to be not-very-helpful here too. If someone at least can give me a pointer to a good discussion of the makefile algorithm that would probably be a good start.

答: blocks is basically an adjacency list representation of the (acyclic) dependency graph. Hence, to get the correct order to process the blocks, you can perform a topological sort.

Body:
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.

The input to this feature extraction system will be a graph detailing the links between the feature extraction blocks, and I'd like to work out which functions to run when based upon the graph.

An example of such a system might be the following:

            ,-> [B] -> [D] ----+
input --> [A]           ^      v
            `-> [C] ----+---> [E] --> output

and the function calls (assuming each block X is a function of the form output = X(inputs) might be something like:

a = A(input)
b = B(a)
c = C(a)
d = D(b,c)  # can't call D until both b and c are ready
output = E(d,c)   # can't call E until both c and d are ready

I already have the function graph loaded in the form of a dictionary with each dictionary entry of the form (inputs, function) like so:

blocks = {'A' : (('input'), A),
          'B' : (('A'), B),
          'C' : (('A'), C),
          'D' : (('B','C'), D),
          'output' : (('D','C'), E)}

I'm just currently drawing a blank on what the makefile algorithm does exactly, and how to go about implementing it. My google-fu appears to be not-very-helpful here too. If someone at least can give me a pointer to a good discussion of the makefile algorithm that would probably be a good start.


问:
Disable swiperefreshlayout and scrollview when interacting with a map fragment
I currently have the following layout high level layout

```<code><android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/swipeRefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="81dp">

            ...

            <FrameLayout
                android:id="@+id/location_container"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView3"
                app:layout_constraintVertical_bias="0.0">

                <fragment
                    android:id="@+id/fragment_location"
                    android:name="com.nissanshare.vehicleinfo.VehicleLocationFragment"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="8dp"
                    android:tag="fragment_vehicleInfo"
                    tools:layout="@layout/fragment_vehicle_info_location" />

                <View
                    android:id="@+id/transparent_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@android:color/transparent" />
            </FrameLayout>

            ...

        </android.support.constraint.ConstraintLayout>
    </ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

And in my code I have the following method

mTouchInterceptor is the transparent_view in the layout

```<code>private void setupTouchInterceptor() {
        mTouchInterceptor.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        Log.d(TAG, ".onTouch:DOWN");
                        // Disallow ScrollView to intercept touch events.
                        mScrollView.requestDisallowInterceptTouchEvent(true);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(true);

                        return false;

                    case MotionEvent.ACTION_UP:
                        Log.d(TAG, ".onTouch:UP");
                        // Allow ScrollView to intercept touch events.

                        mScrollView.requestDisallowInterceptTouchEvent(false);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(false);

                        return true;

                    case MotionEvent.ACTION_MOVE:
                        Log.d(TAG, ".onTouch:MOVE");
                        mScrollView.requestDisallowInterceptTouchEvent(true);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(true);

                        return false;

                    default:
                        return true;
                }
            }
        });
    }
</code>```

This is the same code I use when just using scrollview without the SwipeRefreshLayout and it works flawlessly. However when adding the SwipeRefreshLayout, it seems that it doesn't respect the call to requestDisallowInterceptTouchEvent. How do I prevent the SwipeRefreshLayout from refreshing when interacting with the map.

答: Simply had to change ScrollView to android.support.v4.widget.NestedScrollView.

Body:
I currently have the following layout high level layout

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/swipeRefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="81dp">

            ...

            <FrameLayout
                android:id="@+id/location_container"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView3"
                app:layout_constraintVertical_bias="0.0">

                <fragment
                    android:id="@+id/fragment_location"
                    android:name="com.nissanshare.vehicleinfo.VehicleLocationFragment"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="8dp"
                    android:tag="fragment_vehicleInfo"
                    tools:layout="@layout/fragment_vehicle_info_location" />

                <View
                    android:id="@+id/transparent_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@android:color/transparent" />
            </FrameLayout>

            ...

        </android.support.constraint.ConstraintLayout>
    </ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>

And in my code I have the following method

mTouchInterceptor is the transparent_view in the layout

private void setupTouchInterceptor() {
        mTouchInterceptor.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        Log.d(TAG, ".onTouch:DOWN");
                        // Disallow ScrollView to intercept touch events.
                        mScrollView.requestDisallowInterceptTouchEvent(true);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(true);

                        return false;

                    case MotionEvent.ACTION_UP:
                        Log.d(TAG, ".onTouch:UP");
                        // Allow ScrollView to intercept touch events.

                        mScrollView.requestDisallowInterceptTouchEvent(false);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(false);

                        return true;

                    case MotionEvent.ACTION_MOVE:
                        Log.d(TAG, ".onTouch:MOVE");
                        mScrollView.requestDisallowInterceptTouchEvent(true);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(true);

                        return false;

                    default:
                        return true;
                }
            }
        });
    }

This is the same code I use when just using scrollview without the SwipeRefreshLayout and it works flawlessly. However when adding the SwipeRefreshLayout, it seems that it doesn't respect the call to requestDisallowInterceptTouchEvent. How do I prevent the SwipeRefreshLayout from refreshing when interacting with the map.


问:
Amp Form issue with XHR request using PHP logic (2 versions with caveats)
Am I going about this the wrong way?

Added 2 code examples!

Probably simple to someone else on here, I'm new to Amp html and mustache and I'm having a frustrating problem creating AMP pages with forms, It's almost there though!

I must of rewrote this a few times and its always the same outcome! I'm trying to always return the correct value submitted via form and then pulled from the database, it only works the second time around if the page is refreshed ie* pressing f5 and trying again, otherwise it displays the same content.

It basically loads the div with what is returned from the database, if it exists or not.

The issue I think is with the session, I had to create a success and error variable to show different content depending on whether the data exists in the database or not exists as a XHR response will always be successful unless something is broke.

No matter where I place a session unset value it either does nothing or makes the request not work.

Session based Example:

```<code><?php
session_start();
header("Access-Control-Allow-Credentials: true");
header("AMP-Same-Origin : true");
header("Access-Control-Allow-Origin: *.ampproject.org");
header("AMP-Access-Control-Allow-Source-Origin: http://www.example.com");
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");

include_once('../includes/dbcon.php');
if(isset($_POST['value'])){
$value = isset($_POST['value']) ? $_POST['value'] : '';
//json
header("Content-Type: application/json");
//remove out any spaces from $_post value
$value = str_replace(" ", "", $_POST['value']);
//make session the same as $_post value
$_SESSION["value"] = $value;
$value = $_SESSION["value"];
//check the db
$query = $db->prepare("SELECT * FROM posts WHERE value = '" . $value . "'");
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
if( $query->rowCount() > 0){
    foreach($rows as $row) {
         // value exists
              $_SESSION['msg'] = 'success';
                $output = $_SESSION['msg'];
                  echo json_encode($output);
            }
} else {
          // value does not exist
              $_SESSION['msg'] = 'error';
                 $output = $_SESSION['msg'];
                    echo json_encode($output);
       }
} else { //show page
include_once('includes/header.php');  //includes the amped form and mustache.js files etc
?>
  <h1>Check value.</h1>

    <form method="POST" action-xhr="//www.example.com/test" target="_blank">
      <fieldset>
        <label>
          <span>Check VALUE</span>
            <input type="text" name="value" required>
        </label>
            <input type="submit" value="Check">
      </fieldset>
<div submit-success>
<template type="amp-mustache">
<?php
          $response = $_SESSION['msg'];
        //echo $response .' ( '.$_SESSION['value'] .' ) ';  //test the session value returned
          if($response==='success') {
              echo 'Value already exists! do something here';
            } else if($response==='error') {
              echo 'Value does not exist! do something here';
          }
?>
</template>
</div>
<div submit-error>
<template type="amp-mustache">
  Something has gone wrong! (todo) If there is no response from xhr request then this error is displayed.
 </template>
 </div>
</form>
<?php include_once('includes/footer.php');
 }
 ?>
</code>```

Original version below using amp-mustache, working (kind of) fine but impossible and useless as I cannot render the html to the browser from the error or success message or manipulate or compare the mustache tag with PHP logic.

It has to be possible...
For instance returning back the json array which reads:

```<code>"Success! Value found click here: <a href="#">link</a>"
</code>```

is not html so impossible to add a button etc.

That's all I need to accomplish after checking the value.

Version using the mustache tag

```<code><?php
    header("Access-Control-Allow-Credentials: true");
    header("AMP-Same-Origin : true");
    header("Access-Control-Allow-Origin: *.ampproject.org");
    header("AMP-Access-Control-Allow-Source-Origin: http://www.example.com");
    header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
    header("Cache-Control:private");
    include_once('../includes/dbcon.php');

if(isset($_POST['value'])){
$value = isset($_POST['value']) ? $_POST['value'] : '';
//json
header("Content-Type: application/json");
//take out any spaces from the value first
$value = str_replace(" ", "", $_POST['value']);
//check db
$query = $db->prepare("SELECT * FROM posts WHERE value = '" . $value . "'");
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
if( $query->rowCount() > 0){
    foreach($rows as $row) {
         // value exists
        echo json_encode(array('value'=>'My success message.'));
            }
} else {
          // value does not exist
        echo json_encode(array('value'=>'error.<a href="#">test</a>')); //does not display as html
       }
} else { //show page

 include_once('includes/header.php');  //includes the amped form and mustache.js files etc
?>
  <h1>Check value.</h1>
    <form method="POST" action-xhr="//www.example.com/test" target="_blank">
      <fieldset>
        <label>
          <span>Check Value</span>
            <input type="text" name="value" required>
        </label>
            <input type="submit" value="Check">
      </fieldset>
<div submit-success>
<template type="amp-mustache">
  {{value}}
</template>
</div>
    <div submit-error>
      <template type="amp-mustache">
          Something has gone wrong! (todo) If no response from xhr request then this error is displayed.
      </template>
    </div>
  </form>
<?php include_once('includes/footer.php');
  }
?>
</code>```

答:
I'm an idiot, I figured it out the mustache way (Method 2), I can't believe I didn't try it - a long day I guess at a day job which doesn't involve programming!

Simply change both checks to:

```<code> //success part
 $url="http://example.com/success-page";
 $title="my success title tag text";
 echo json_encode(array(
'value'=>'My <strong>success</strong> message',
'url'=> $url,
'title' => $title
)); // add more variables to build up the JSON array and display them as mustache tags

 //error part
 $url="http://example.com/error-page";
 $title="my error title tag text";
 echo json_encode(array(
'value'=>'My error message',
'url'=> $url,
'title' => $title
)); // add more variables to build up the JSON array and display them as mustache tags
</code>```

and finally change the mustache tag part to:

```<code>{{{value}}} <a href="{{url}}" title="{{title}}">Click me</a>
</code>```

3 curly brackets un-escape simple HTML tags.

Body:
Am I going about this the wrong way?

Added 2 code examples!

Probably simple to someone else on here, I'm new to Amp html and mustache and I'm having a frustrating problem creating AMP pages with forms, It's almost there though!

I must of rewrote this a few times and its always the same outcome! I'm trying to always return the correct value submitted via form and then pulled from the database, it only works the second time around if the page is refreshed ie* pressing f5 and trying again, otherwise it displays the same content.

It basically loads the div with what is returned from the database, if it exists or not.

The issue I think is with the session, I had to create a success and error variable to show different content depending on whether the data exists in the database or not exists as a XHR response will always be successful unless something is broke.

No matter where I place a session unset value it either does nothing or makes the request not work.

Session based Example:

<?php
session_start();
header("Access-Control-Allow-Credentials: true");
header("AMP-Same-Origin : true");
header("Access-Control-Allow-Origin: *.ampproject.org");
header("AMP-Access-Control-Allow-Source-Origin: http://www.example.com");
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");

include_once('../includes/dbcon.php');
if(isset($_POST['value'])){
$value = isset($_POST['value']) ? $_POST['value'] : '';
//json
header("Content-Type: application/json");
//remove out any spaces from $_post value
$value = str_replace(" ", "", $_POST['value']);
//make session the same as $_post value
$_SESSION["value"] = $value;
$value = $_SESSION["value"];
//check the db
$query = $db->prepare("SELECT * FROM posts WHERE value = '" . $value . "'");
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
if( $query->rowCount() > 0){
    foreach($rows as $row) {
         // value exists
              $_SESSION['msg'] = 'success';
                $output = $_SESSION['msg'];
                  echo json_encode($output);
            }
} else {
          // value does not exist
              $_SESSION['msg'] = 'error';
                 $output = $_SESSION['msg'];
                    echo json_encode($output);
       }
} else { //show page
include_once('includes/header.php');  //includes the amped form and mustache.js files etc
?>

Check value.

    <form method="POST" action-xhr="//www.example.com/test" target="_blank">
      <fieldset>

          Check VALUE
            <input type="text" name="value" required>

            <input type="submit" value="Check">
      </fieldset>

<template type="amp-mustache">
<?php
          $response = $_SESSION['msg'];
        //echo $response .' ( '.$_SESSION['value'] .' ) ';  //test the session value returned
          if($response==='success') {
              echo 'Value already exists! do something here';
            } else if($response==='error') {
              echo 'Value does not exist! do something here';
          }
?>
</template>

<template type="amp-mustache">
  Something has gone wrong! (todo) If there is no response from xhr request then this error is displayed.
 </template>

</form>
<?php include_once('includes/footer.php');
 }
 ?>

Original version below using amp-mustache, working (kind of) fine but impossible and useless as I cannot render the html to the browser from the error or success message or manipulate or compare the mustache tag with PHP logic.

It has to be possible...
For instance returning back the json array which reads:

"Success! Value found click here: link"

is not html so impossible to add a button etc.

That's all I need to accomplish after checking the value.

Version using the mustache tag

<?php
    header("Access-Control-Allow-Credentials: true");
    header("AMP-Same-Origin : true");
    header("Access-Control-Allow-Origin: *.ampproject.org");
    header("AMP-Access-Control-Allow-Source-Origin: http://www.example.com");
    header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
    header("Cache-Control:private");
    include_once('../includes/dbcon.php');

if(isset($_POST['value'])){
$value = isset($_POST['value']) ? $_POST['value'] : '';
//json
header("Content-Type: application/json");
//take out any spaces from the value first
$value = str_replace(" ", "", $_POST['value']);
//check db
$query = $db->prepare("SELECT * FROM posts WHERE value = '" . $value . "'");
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
if( $query->rowCount() > 0){
    foreach($rows as $row) {
         // value exists
        echo json_encode(array('value'=>'My success message.'));
            }
} else {
          // value does not exist
        echo json_encode(array('value'=>'error.test')); //does not display as html
       }
} else { //show page

 include_once('includes/header.php');  //includes the amped form and mustache.js files etc
?>

Check value.

    <form method="POST" action-xhr="//www.example.com/test" target="_blank">
      <fieldset>

          Check Value
            <input type="text" name="value" required>

            <input type="submit" value="Check">
      </fieldset>

<template type="amp-mustache">
  {{value}}
</template>

      <template type="amp-mustache">
          Something has gone wrong! (todo) If no response from xhr request then this error is displayed.
      </template>

  </form>
<?php include_once('includes/footer.php');
  }
?>

Body:
I'm an idiot, I figured it out the mustache way (Method 2), I can't believe I didn't try it - a long day I guess at a day job which doesn't involve programming!

Simply change both checks to:

 //success part
 $url="http://example.com/success-page";
 $title="my success title tag text";
 echo json_encode(array(
'value'=>'My <strong>success</strong> message',
'url'=> $url,
'title' => $title
)); // add more variables to build up the JSON array and display them as mustache tags

 //error part
 $url="http://example.com/error-page";
 $title="my error title tag text";
 echo json_encode(array(
'value'=>'My error message',
'url'=> $url,
'title' => $title
)); // add more variables to build up the JSON array and display them as mustache tags

and finally change the mustache tag part to:

{{{value}}} <a href="{{url}}" title="{{title}}">Click me</a>

3 curly brackets un-escape simple HTML tags.


问:
Jasmine report error: ENOENT: no such file or directory, open 'xmlresults.xml'
I'm trying to implement jasmine report to my framework that work with Protractor so in the conf.js i put this code

```<code>onComplete: function(){
var browserName;
var capsPromise = browser.getCapabilities();

capsPromise.then(function (caps) {
  browserName = caps.get('firefox');

  var HTMLReport = require('protractor-html-reporter');

  testConfig = {
    reportTitle: 'Test Execution Report',
    outPath: '/test/e2e/reports',
    testBrowser: browserName,
    modifiedSuiteName: false
  };
  new HTMLReport().from('xmlresults.xml', testConfig);
});
},
</code>```

I already install jasmine reporter with this command

```<code>npm install --save-dev jasmine-reporters@^2.0.0
</code>```

When I execute my script is not failing but when the execution try to generate the report in the terminal is displaying this:

```<code>E/launcher - ENOENT: no such file or directory, open 'xmlresults.xml'
E/launcher - Error: ENOENT: no such file or directory, open 'xmlresults.xml'
</code>```

Is anybody has an idea what is happen with this error?

Hope you can help me.

答:
Yes, the file cannot be opened at the path you specified because relative to whatever working directory you are in it isn't there.

Change the path to match the relative target location of your XML results file.

Body:
I'm trying to implement jasmine report to my framework that work with Protractor so in the conf.js i put this code

onComplete: function(){
var browserName;
var capsPromise = browser.getCapabilities();

capsPromise.then(function (caps) {
  browserName = caps.get('firefox');

  var HTMLReport = require('protractor-html-reporter');

  testConfig = {
    reportTitle: 'Test Execution Report',
    outPath: '/test/e2e/reports',
    testBrowser: browserName,
    modifiedSuiteName: false
  };
  new HTMLReport().from('xmlresults.xml', testConfig);
});
},

I already install jasmine reporter with this command

npm install --save-dev jasmine-reporters@^2.0.0

When I execute my script is not failing but when the execution try to generate the report in the terminal is displaying this:

E/launcher - ENOENT: no such file or directory, open 'xmlresults.xml'
E/launcher - Error: ENOENT: no such file or directory, open 'xmlresults.xml'

Is anybody has an idea what is happen with this error?

Hope you can help me.


问:
StringBuilder Vs StringWriter/StringReader
I recently read that in StringWriter and StringReader are used for writing and reading from StringBuilder.

Well when I use StringBuilder Object, it looks to be a self sufficient class.

We have every way of reading and writing the StringBuilder, using
StringBuilder.Append(), Insert(), Replace(), Remove() etc...

What is the possible use of StringWriter and StringReader, which cannot be done by StringBuilder itself?

What is the practical use of them?

What could be the possible reason they are not taking up Stream as the input (Because any other writer and reader are taking the stream as the Constructor parameter to operate on) but the StringBuilder?

答:
Others have said already, but it is because they derive from TextReader/TextWriter and can be used in place of them.  For one thing it just makes more sense to use the same method for outputting lines that you use for a file if you only want the content as a string.  If you want output that will span multiple lines in memory, why bother remembering to put "\r\n" at the end of every line with a StringBuilder?  What if you want the code to run on or format data for a system that only uses "\n" for line breaks?

```<code>StringBuilder sb = new StringBuilder();
// will be invalid on systems that only use \n
sb.AppendFormat("{0:yyyy-MM-dd HH:mm:ss} - Start\r\n", DateTime.Now);
// still have to add an extra parameter
sb.AppendFormat("The current time is {0:yyyy-MM-dd HH:mm:ss}{1}", DateTime.Now,
    Environment.NewLine);

StringWriter sw = new StringWriter();
// Don't have to worry about it, method name tells you there's a line break
sw.WriteLine("{0:yyyy-MM-dd HH:mm:ss} - Start", DateTime.Now);
// no extra parameters
sw.WriteLine("The current time is {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
</code>```

Say you want to process a file line by line, you would probably use a StreamReader instead of loading the whole file into a StringBuilder and splitting it by newline characters into an array, right?  With StringReader you can use the exact same method (as long as it takes a generic TextReader) by creating the StringReader from a string from a TextBox or web form.

Linq2Sql DataContexts have a Log property you can set to a TextWriter to have your queries output before they are executed to see exactly what is being run.  You can set this to a TextWriter attached to a file, but you could attach a StringWriter to it and output the contents at the bottom of your web page when testing...

Body:
Others have said already, but it is because they derive from TextReader/TextWriter and can be used in place of them.  For one thing it just makes more sense to use the same method for outputting lines that you use for a file if you only want the content as a string.  If you want output that will span multiple lines in memory, why bother remembering to put "\r\n" at the end of every line with a StringBuilder?  What if you want the code to run on or format data for a system that only uses "\n" for line breaks?

StringBuilder sb = new StringBuilder();
// will be invalid on systems that only use \n
sb.AppendFormat("{0:yyyy-MM-dd HH:mm:ss} - Start\r\n", DateTime.Now);
// still have to add an extra parameter
sb.AppendFormat("The current time is {0:yyyy-MM-dd HH:mm:ss}{1}", DateTime.Now,
    Environment.NewLine);

StringWriter sw = new StringWriter();
// Don't have to worry about it, method name tells you there's a line break
sw.WriteLine("{0:yyyy-MM-dd HH:mm:ss} - Start", DateTime.Now);
// no extra parameters
sw.WriteLine("The current time is {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);

Say you want to process a file line by line, you would probably use a StreamReader instead of loading the whole file into a StringBuilder and splitting it by newline characters into an array, right?  With StringReader you can use the exact same method (as long as it takes a generic TextReader) by creating the StringReader from a string from a TextBox or web form.

Linq2Sql DataContexts have a Log property you can set to a TextWriter to have your queries output before they are executed to see exactly what is being run.  You can set this to a TextWriter attached to a file, but you could attach a StringWriter to it and output the contents at the bottom of your web page when testing...


问:
Change hash without reload in jQuery
I have the following code:

```<code>$('ul.questions li a').click(function(event) {
    $('.tab').hide();
    $($(this).attr('href')).fadeIn('slow');
    event.preventDefault();
    window.location.hash = $(this).attr('href');
});
</code>```

This simply fades a div in based on when you click but I want the page URL hash tag to change when you click so people can copy and bookmark it.  At the moment this effectively reloads the page when the hash tag is change.

Is it possible to change the hash tag and not reload the page to prevent the jumping effect?

答:
The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

```<code>// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});
</code>```

Title: Change hash without reload in jQuery

Body:
I have the following code:

$('ul.questions li a').click(function(event) {
    $('.tab').hide();
    $($(this).attr('href')).fadeIn('slow');
    event.preventDefault();
    window.location.hash = $(this).attr('href');
});

This simply fades a div in based on when you click but I want the page URL hash tag to change when you click so people can copy and bookmark it.  At the moment this effectively reloads the page when the hash tag is change.

Is it possible to change the hash tag and not reload the page to prevent the jumping effect?

Body:
The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});


问:
IOS: Allow SwipeToDelete But Don't Show Editing Button in Tableview
For a tableview, I want to allow SwipeToDelete and I also want to allow people to edit the tableview in the sense of being able to move rows up and down.  However, when moving rows up and down, I want to suppress the delete button as it is a bit distracting.

Is there a way to allow swipe to delete while suppressing the delete button in edit mode?

I am trying the following delegate but it is not doing the job:

```<code>    - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView  editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // Detemine if it's in editing mode
        if (self.editing)
        {
NSLog(@"thinks it is editing");
            return UITableViewCellEditingStyleDelete; //enable when editing mode is on
        }
        else {
NSLog(@"thinks editing mode is off");
          //  return UITableViewCellEditingStyleDelete;
           return UITableViewCellEditingStyleNone;
        }
    }
</code>```

When I set the else to delete, it allows swipe to delete but also shows delete button.

When I set the else to None, it does not allow swipe to delete but does suppress delete button.

Some how self.editing is not doing the job.

答:
You should return UITableViewCellEditingStyleNone for editingStyle... (to avoid showing the green + or red - buttons at the left of the cell when in edit mode.  Then you can return YES from canEdit... to indicate that the cell can still be edited (ie, deleted) by swiping:

```<code>- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
</code>```

Optionally, you can also use the following to prevent the extra space appearing at the left of the cell during edit mode (where the - or + button would have otherwise been):

```<code>- (BOOL)tableView:(UITableView *)tableview shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}
</code>```

Body:
For a tableview, I want to allow SwipeToDelete and I also want to allow people to edit the tableview in the sense of being able to move rows up and down.  However, when moving rows up and down, I want to suppress the delete button as it is a bit distracting.

Is there a way to allow swipe to delete while suppressing the delete button in edit mode?

I am trying the following delegate but it is not doing the job:

    - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView  editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // Detemine if it's in editing mode
        if (self.editing)
        {
NSLog(@"thinks it is editing");
            return UITableViewCellEditingStyleDelete; //enable when editing mode is on
        }
        else {
NSLog(@"thinks editing mode is off");
          //  return UITableViewCellEditingStyleDelete;
           return UITableViewCellEditingStyleNone;
        }
    }

When I set the else to delete, it allows swipe to delete but also shows delete button.

When I set the else to None, it does not allow swipe to delete but does suppress delete button.

Some how self.editing is not doing the job.

Body:
You should return UITableViewCellEditingStyleNone for editingStyle... (to avoid showing the green + or red - buttons at the left of the cell when in edit mode.  Then you can return YES from canEdit... to indicate that the cell can still be edited (ie, deleted) by swiping:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

Optionally, you can also use the following to prevent the extra space appearing at the left of the cell during edit mode (where the - or + button would have otherwise been):

- (BOOL)tableView:(UITableView *)tableview shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}