问:
first and last day of the current month in swift
I'm trying to get the first and last day of the month in swift.

So far I have the following:

```<code>let dateFormatter = NSDateFormatter()
let date = NSDate()
dateFormatter.dateFormat = "yyyy-MM-dd"
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)

let month = components.month
let year = components.year

let startOfMonth = ("\(year)-\(month)-01")
</code>```

But I'm not sure how to get the last date. Is there a built in method I'm missing? Obviously it has to take into account leap years etc.

答:
With Swift 3, you can choose one of the two following patters in order to retrieve the first and last days of a month.

#1. Using Calendar dateComponents(_:from:), date(from:) and date(byAdding:to:wrappingComponents:) methods

With this pattern, you first get the date of the first day of a month then add a month and remove a day from it in order to get the date of the last day of the month. The Playground code below shows how to set it:

```<code>import Foundation

// Set calendar and date
let calendar = Calendar.current
let date = calendar.date(byAdding: DateComponents(day: -10), to: Date())!

// Get first day of month
let firstDayComponents = calendar.dateComponents([.year, .month], from: date)
let firstDay = calendar.date(from: firstDayComponents)!

// Get last day of month
let lastDayComponents = DateComponents(month: 1, day: -1)
let lastDay = calendar.date(byAdding: lastDayComponents, to: firstDay)!

// Set date formatter
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long

// Print results
print(dateFormatter.string(from: date)) // Prints: 22 March 2017 at 18:07:15 CET
print(dateFormatter.string(from: firstDay)) // Prints: 1 March 2017 at 00:00:00 CET
print(dateFormatter.string(from: lastDay)) // Prints: 31 March 2017 at 00:00:00 CEST
</code>```

#2. Using Calendar range(of:in:for:), dateComponents(_:from:) and date(from:) and  methods

With this pattern, you get a range of absolute day values in a month and then retrieve the dates of the first day and last day of the month from it. The Playground code below shows how to set it:

```<code>import Foundation

// Set calendar and date
let calendar = Calendar.current
let date = calendar.date(byAdding: DateComponents(day: -10), to: Date())!

// Get range of days in month
let range = calendar.range(of: .day, in: .month, for: date)! // Range(1..<32)

// Get first day of month
var firstDayComponents = calendar.dateComponents([.year, .month], from: date)
firstDayComponents.day = range.lowerBound
let firstDay = calendar.date(from: firstDayComponents)!

// Get last day of month
var lastDayComponents = calendar.dateComponents([.year, .month], from: date)
lastDayComponents.day = range.upperBound - 1
//lastDayComponents.day = range.count // also works
let lastDay = calendar.date(from: lastDayComponents)!

// Set date formatter
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long

// Print results
print(dateFormatter.string(from: date)) // prints: 22 March 2017 at 18:07:15 CET
print(dateFormatter.string(from: firstDay)) // prints: 1 March 2017 at 00:00:00 CET
print(dateFormatter.string(from: lastDay)) // prints: 31 March 2017 at 00:00:00 CEST
</code>```

Body:
I'm trying to get the first and last day of the month in swift.

So far I have the following:

let dateFormatter = NSDateFormatter()
let date = NSDate()
dateFormatter.dateFormat = "yyyy-MM-dd"
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)

let month = components.month
let year = components.year

let startOfMonth = ("\(year)-\(month)-01")

But I'm not sure how to get the last date. Is there a built in method I'm missing? Obviously it has to take into account leap years etc.

Body:
With Swift 3, you can choose one of the two following patters in order to retrieve the first and last days of a month.

#1. Using Calendar dateComponents(_:from:), date(from:) and date(byAdding:to:wrappingComponents:) methods

With this pattern, you first get the date of the first day of a month then add a month and remove a day from it in order to get the date of the last day of the month. The Playground code below shows how to set it:

import Foundation

// Set calendar and date
let calendar = Calendar.current
let date = calendar.date(byAdding: DateComponents(day: -10), to: Date())!

// Get first day of month
let firstDayComponents = calendar.dateComponents([.year, .month], from: date)
let firstDay = calendar.date(from: firstDayComponents)!

// Get last day of month
let lastDayComponents = DateComponents(month: 1, day: -1)
let lastDay = calendar.date(byAdding: lastDayComponents, to: firstDay)!

// Set date formatter
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long

// Print results
print(dateFormatter.string(from: date)) // Prints: 22 March 2017 at 18:07:15 CET
print(dateFormatter.string(from: firstDay)) // Prints: 1 March 2017 at 00:00:00 CET
print(dateFormatter.string(from: lastDay)) // Prints: 31 March 2017 at 00:00:00 CEST

#2. Using Calendar range(of:in:for:), dateComponents(_:from:) and date(from:) and  methods

With this pattern, you get a range of absolute day values in a month and then retrieve the dates of the first day and last day of the month from it. The Playground code below shows how to set it:

import Foundation

// Set calendar and date
let calendar = Calendar.current
let date = calendar.date(byAdding: DateComponents(day: -10), to: Date())!

// Get range of days in month
let range = calendar.range(of: .day, in: .month, for: date)! // Range(1..<32)

// Get first day of month
var firstDayComponents = calendar.dateComponents([.year, .month], from: date)
firstDayComponents.day = range.lowerBound
let firstDay = calendar.date(from: firstDayComponents)!

// Get last day of month
var lastDayComponents = calendar.dateComponents([.year, .month], from: date)
lastDayComponents.day = range.upperBound - 1
//lastDayComponents.day = range.count // also works
let lastDay = calendar.date(from: lastDayComponents)!

// Set date formatter
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long

// Print results
print(dateFormatter.string(from: date)) // prints: 22 March 2017 at 18:07:15 CET
print(dateFormatter.string(from: firstDay)) // prints: 1 March 2017 at 00:00:00 CET
print(dateFormatter.string(from: lastDay)) // prints: 31 March 2017 at 00:00:00 CEST


来源: stackexchange

问:
getLatLong always returns false
I'm trying to retrieve longitude and latitude values from geotagged images using android.media.ExifInterface library. However, getLatLong always returns false although the image is geotagged. This is my code :

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button galleryButton = (Button) findViewById(R.id.galleryButton);

    galleryButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(pickPhoto , 1);

        }

    });

}

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {

    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                Uri selectedImage = imageReturnedIntent.getData();
                ExifInterface exif = new ExInterface(selectedImage.getPath());
                float[] latlong = null;
                bool result = exif.getLatLong(latlong);

            }

            break;

    }
}
</code>```

As you can see, I'm initializing exif object with the path from returned URI and it contains path like "/external/images/media/2330". When I call getLatLong, it always returns false. I have also tried the example from this page, but still does not work. Any help would be appreciated.

Galaxy S6 Edge
Android SDK Version 25

答:
getPath() only works on a Uri with a file scheme. Yours has a content scheme. Plus, you are using the ExifInterface with the security flaws.

Add the com.android.support:exifinterface:25.3.1 library to your dependencies.

Next, replace your android.media.ExifInterface import with one for android.support.media.ExifInterface.

Then, replace:

```<code>ExifInterface exif = new ExInterface(selectedImage.getPath());
</code>```

with:

```<code>ExifInterface exif = new ExifInterface(getContentResolver().openInputStream(selectedImage));
</code>```

ContentLicense: CC BY-SA 3.0

Title: getLatLong always returns false

Body:
I'm trying to retrieve longitude and latitude values from geotagged images using android.media.ExifInterface library. However, getLatLong always returns false although the image is geotagged. This is my code :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button galleryButton = (Button) findViewById(R.id.galleryButton);

    galleryButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(pickPhoto , 1);

        }

    });

}

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {

    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                Uri selectedImage = imageReturnedIntent.getData();
                ExifInterface exif = new ExInterface(selectedImage.getPath());
                float[] latlong = null;
                bool result = exif.getLatLong(latlong);

            }

            break;

    }
}

As you can see, I'm initializing exif object with the path from returned URI and it contains path like "/external/images/media/2330". When I call getLatLong, it always returns false. I have also tried the example from this page, but still does not work. Any help would be appreciated.

Galaxy S6 Edge
Android SDK Version 25

Body:
getPath() only works on a Uri with a file scheme. Yours has a content scheme. Plus, you are using the ExifInterface with the security flaws.

Add the com.android.support:exifinterface:25.3.1 library to your dependencies.

Next, replace your android.media.ExifInterface import with one for android.support.media.ExifInterface.

Then, replace:

ExifInterface exif = new ExInterface(selectedImage.getPath());

with:

ExifInterface exif = new ExifInterface(getContentResolver().openInputStream(selectedImage));


问:
Ad-ID (IDFA) and Google Framework
I am currently developing an App for iOS for iPhone with Google AdMob intergrated within it. I implementetd other Firebase functions like Firebase Messaging, because I am planning to push notifications.

As stated by Google, Google uses the Apple IDFA and conforms to its guidelines. Therefore, I assume by submitting this App, I should select IDFA.

But in the same time, I am planning to bring the exact same app without Ads, but still with Google Framework being integrated within it, because, as I said, I am planning to push notifications.

My question is: should I remove the Google AdMob interface before submitting the Ad-Free app? If no need to do so, should I select IDFA on submission? If it has to be removed, what and from where should I exactly remove?

Thanks a lot!

答:
Here is what I have done:

In the Ad-Free version, I removed the complete framework and reinstalled it using "pod install" but this time installing only 'Firbase', 'Firebase/Core' and 'Firebase/Messaging" without AdMob.

My app got accepted without selecting IDFA upon submission.

Title: Ad-ID (IDFA) and Google Framework


问:
How to download Podspec dependencies for local development
This seems like something that should be done very easily. I don't know why I just can't seem to find a simple answer to that.

I am creating a pod library that has a pod dependency.

So in my .podspec, I have a s.dependency 'SomePod', '~> 1.0'. Since I am writing my library using SomePod, I want the source files from it in order to import it and use it. Sure one way to do it is to have a PodFile in the repo and then pod install the SomePod.

But is there some other way to download the somePod dependency so that I can use it in my library? What is the best practice around that to have a clean structure?

FYI, I am using the Cookie Cutter library in order to generate all my project structure. What's left for me to do is download those podspec dependencies and avoid using Podfile and pod install since I already have a .xcworkspace generated from Cookie Cutter, so pod install won't like that and will go crazy.

答:
Well you could handle the dependency management with other Tools (Carthage etc.) or simply on your own (git clone + project integration), but as you are already providing a podspec for your lib, why not just stick to cocoapods for third party lib integration?

This would be the typical approach for your setup, as you just need to write a simple Podfile, assure that SomePod is fetched with the same version as defined in podspec and call pod install.

Advantages:

you can still watch third party sources

you can debug into third party lib

you can compile, test & debug against the exact same version of SomePod that will be fetched from a client project of your lib (no need to keep versions manually in sync)


问:
Cluster Markers with Google Maps API, locations from database
I am creating a google map that is populated with markers based upon information from my database. I have followed the tutorial provided from Google in this first step.

The map works fine, however since some of my markers are close together, I would like to take advantage of marker clustering. I’ve followed what I can from Google's tutorial on marker clustering.

However, I cannot find a way to get it to work. My markers just show up the way they are, without any clustering. I think I have followed all of the steps, linking the JS file to my HTML, downloading and uploading the marker icons and JS file to my hosting site, etc.

How can I continue to create markers from my database, but also cluster the markers?

I have tested the exact code from the google marker clusterer tutorial, and everything works fine. (However the markers are not in the locations I need.)

A simplified version of my HTML(PHP) webpage is as follows:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>My Website</title>
    <style>
        map {
    height: 400px;
    width: 98%;
    border: 5px outset SteelBlue;
    }
    </style>
    </head>
<body>

                <!-- Google Map -->
                <div id='map'>
                </div>

<!-- Google MAPS API & Custom Maps JS-->

    <!-- This is my personal file that houses the main Javascript code -->
        <script src="findermap.js"></script>

    <!-- A link to download this file is provided by the Google tutorial -->
        <script src="markerclusterer.js"></script>

    <!-- Basic Google Maps API key link -->
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=MY-KEY-IS-USED-HERE&callback=initMap">
    </script>

</body>
</html>
</code>```

Here is basically the JavaScript file I use, "findermap.js"

```<code>            function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
              center: new google.maps.LatLng(0, 0),
              zoom: 1
            });

            var customIcons = {
                    type1: {
                      icon: 'icon_type1.png'
                    },
                    type2: {
                      icon: 'icon_type2.png'
                    },
                    type3: {
                      icon: 'icon_type3.png'
                    },
                    type4: {
                      icon: 'icon_type4.png'
                    }
            };
            var markers = [];
            var infoWindow = new google.maps.InfoWindow;

              // Change this depending on the name of your PHP or XML file
              downloadUrl('https://my-website.com/getinfo.php', function(data) {
                var xml = data.responseXML;
                var markers2 = xml.documentElement.getElementsByTagName('marker');
                Array.prototype.forEach.call(markers2, function(markerElem) {
                  var name = markerElem.getAttribute('name');

                  var address = markerElem.getAttribute('address');
                  var type = markerElem.getAttribute('type');
                  var point = new google.maps.LatLng(
                      parseFloat(markerElem.getAttribute('lat')),
                      parseFloat(markerElem.getAttribute('lng')));

                  var infowincontent = document.createElement('div');
                  var strong = document.createElement('strong');
                  strong.textContent = name
                  infowincontent.appendChild(strong);
                  infowincontent.appendChild(document.createElement('br'));

                  var text = document.createElement('text');
                  text.textContent = address
                  infowincontent.appendChild(text);
                  var icon = customIcons[type] || {};
                  var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: icon.icon,
                    label: icon.label
                  });

                  marker.addListener('click', function() {
                    infoWindow.setContent(infowincontent);
                    infoWindow.open(map, marker);
                  });

                 markers.push(marker);

                });

              });

                  var options = {
                      imagePath: '/clustericons/m'
                  };

              // Add a marker clusterer to manage the markers.
                  var markerCluster = new MarkerClusterer(map, markers, options);
            }

            function downloadUrl(url, callback) {
            var request = window.ActiveXObject ?
                new ActiveXObject('getinfo.php') :
                new XMLHttpRequest;

            request.onreadystatechange = function() {
              if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
              }
            };

            request.open('GET', url, true);
            request.send(null);
            }

            function doNothing() {}
</code>```

答:
I Found it! Here is the solution. This is the updated javascript file:</p>

```<code>    var customIcons = {
                type1: {
                  icon: 'icon_type1.png'
                },
                type2: {
                  icon: 'icon_type2.png'
                },
                type3: {
                  icon: 'icon_type3.png'
                },
                type4: {
                  icon: 'icon_type4.png'
                }
        };

        function initMap() {
          var cluster = [];
          var map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(0, 0),
            zoom: 1,
            mapTypeId: 'roadmap'
          });
    var infowindow = new google.maps.InfoWindow();

          // Change this depending on the name of your PHP file
          downloadUrl('https://my-website.com/the-sweet-sweet-xml-info.php', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < markers.length; i++) {
              var name = markers[i].getAttribute("name");
              var address = markers[i].getAttribute("address");
              var type = markers[i].getAttribute("type");
              var point = new google.maps.LatLng(
                  parseFloat(markers[i].getAttribute("lat")),
                  parseFloat(markers[i].getAttribute("lng")));

              var html= "<b>" +
              markers[i].getAttribute("name") +
              "</b> <br/>" +
              markers[i].getAttribute("address");

              var icon = customIcons[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: icon.icon,
              });
              google.maps.event.addListener(marker, 'click', (function(marker, i) {
                            return function() {
                                infowindow.setContent(
                                "<b>" +
                                markers[i].getAttribute("name") +
                                "</b> <br/>" +
                                markers[i].getAttribute("address")
                                );
                                infowindow.open(map, marker);

                                //This sends information from the clicked icon back to the serverside code
                                document.getElementById("setlatlng").innerHTML = markers[i].getAttribute("name");
                            }
                        })(marker, i));
              cluster.push(marker);
            }

            var options = {
                  imagePath: '/location-of-cluster-icons/m'
              };

            var mc = new MarkerClusterer(map,cluster,options);
          });
        }

        function bindInfoWindow(marker, map, infoWindow, html) {
          google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);

          });
        }

        function downloadUrl(url, callback) {
          var request = window.ActiveXObject ?
              new ActiveXObject('the-sweet-sweet-xml-info.php') :
              new XMLHttpRequest;

          request.onreadystatechange = function() {
            if (request.readyState == 4) {
              request.onreadystatechange = doNothing;
              callback(request, request.status);
            }
          };

          request.open('GET', url, true);
          request.send(null);
        }

        function doNothing() {}
</code>```

Body:
I am creating a google map that is populated with markers based upon information from my database. I have followed the tutorial provided from Google in this first step.

The map works fine, however since some of my markers are close together, I would like to take advantage of marker clustering. I’ve followed what I can from Google's tutorial on marker clustering.

However, I cannot find a way to get it to work. My markers just show up the way they are, without any clustering. I think I have followed all of the steps, linking the JS file to my HTML, downloading and uploading the marker icons and JS file to my hosting site, etc.

How can I continue to create markers from my database, but also cluster the markers?

I have tested the exact code from the google marker clusterer tutorial, and everything works fine. (However the markers are not in the locations I need.)

A simplified version of my HTML(PHP) webpage is as follows:

<!DOCTYPE html>

        <title>My Website</title>

Here is basically the JavaScript file I use, "findermap.js"

            function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
              center: new google.maps.LatLng(0, 0),
              zoom: 1
            });

            var customIcons = {
                    type1: {
                      icon: 'icon_type1.png'
                    },
                    type2: {
                      icon: 'icon_type2.png'
                    },
                    type3: {
                      icon: 'icon_type3.png'
                    },
                    type4: {
                      icon: 'icon_type4.png'
                    }
            };
            var markers = [];
            var infoWindow = new google.maps.InfoWindow;

              // Change this depending on the name of your PHP or XML file
              downloadUrl('https://my-website.com/getinfo.php', function(data) {
                var xml = data.responseXML;
                var markers2 = xml.documentElement.getElementsByTagName('marker');
                Array.prototype.forEach.call(markers2, function(markerElem) {
                  var name = markerElem.getAttribute('name');

                  var address = markerElem.getAttribute('address');
                  var type = markerElem.getAttribute('type');
                  var point = new google.maps.LatLng(
                      parseFloat(markerElem.getAttribute('lat')),
                      parseFloat(markerElem.getAttribute('lng')));

                  var infowincontent = document.createElement('div');
                  var strong = document.createElement('strong');
                  strong.textContent = name
                  infowincontent.appendChild(strong);
                  infowincontent.appendChild(document.createElement('br'));

                  var text = document.createElement('text');
                  text.textContent = address
                  infowincontent.appendChild(text);
                  var icon = customIcons[type] || {};
                  var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: icon.icon,
                    label: icon.label
                  });

                  marker.addListener('click', function() {
                    infoWindow.setContent(infowincontent);
                    infoWindow.open(map, marker);
                  });

                 markers.push(marker);

                });

              });

                  var options = {
                      imagePath: '/clustericons/m'
                  };

              // Add a marker clusterer to manage the markers.
                  var markerCluster = new MarkerClusterer(map, markers, options);
            }

            function downloadUrl(url, callback) {
            var request = window.ActiveXObject ?
                new ActiveXObject('getinfo.php') :
                new XMLHttpRequest;

            request.onreadystatechange = function() {
              if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
              }
            };

            request.open('GET', url, true);
            request.send(null);
            }

            function doNothing() {}

Body:
I Found it! Here is the solution. This is the updated javascript file:

    var customIcons = {
                type1: {
                  icon: 'icon_type1.png'
                },
                type2: {
                  icon: 'icon_type2.png'
                },
                type3: {
                  icon: 'icon_type3.png'
                },
                type4: {
                  icon: 'icon_type4.png'
                }
        };

        function initMap() {
          var cluster = [];
          var map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(0, 0),
            zoom: 1,
            mapTypeId: 'roadmap'
          });
    var infowindow = new google.maps.InfoWindow();

          // Change this depending on the name of your PHP file
          downloadUrl('https://my-website.com/the-sweet-sweet-xml-info.php', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < markers.length; i++) {
              var name = markers[i].getAttribute("name");
              var address = markers[i].getAttribute("address");
              var type = markers[i].getAttribute("type");
              var point = new google.maps.LatLng(
                  parseFloat(markers[i].getAttribute("lat")),
                  parseFloat(markers[i].getAttribute("lng")));

              var html= "<b>" +
              markers[i].getAttribute("name") +
              "</b> <br/>" +
              markers[i].getAttribute("address");

              var icon = customIcons[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: icon.icon,
              });
              google.maps.event.addListener(marker, 'click', (function(marker, i) {
                            return function() {
                                infowindow.setContent(
                                "<b>" +
                                markers[i].getAttribute("name") +
                                "</b> <br/>" +
                                markers[i].getAttribute("address")
                                );
                                infowindow.open(map, marker);

                                //This sends information from the clicked icon back to the serverside code
                                document.getElementById("setlatlng").innerHTML = markers[i].getAttribute("name");
                            }
                        })(marker, i));
              cluster.push(marker);
            }

            var options = {
                  imagePath: '/location-of-cluster-icons/m'
              };

            var mc = new MarkerClusterer(map,cluster,options);
          });
        }

        function bindInfoWindow(marker, map, infoWindow, html) {
          google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);

          });
        }

        function downloadUrl(url, callback) {
          var request = window.ActiveXObject ?
              new ActiveXObject('the-sweet-sweet-xml-info.php') :
              new XMLHttpRequest;

          request.onreadystatechange = function() {
            if (request.readyState == 4) {
              request.onreadystatechange = doNothing;
              callback(request, request.status);
            }
          };

          request.open('GET', url, true);
          request.send(null);
        }

        function doNothing() {}


问:
Incorrect RDD tranformation
I am unable to re-use the new RDD that has formed by doing mapPartition. The code seems to work fine only if I add reduceByKey transformation after the mapPartition (I do not want to perform reduceByKey). Since reduceByKey and mapParition are both transformations I am not sure what is causing error.

```<code>C = [x for x in xrange(2**20)]
C = sc.parallelize(C)
while True:
    C = C.repartition(1000)\
        .mapPartitions(foo)\
        .persist()

    if C.take(1) == 0 :
        break
</code>```

Error reported:

```<code>TypeError: can't pickle listiterator objects
</code>```

答:
The error is due to what you are returning from the mapPartitions is what I believe. If you return a new RDD, I do not see a reason for the code to raise an exception. Following is the code snippet which I developed by using your code.

```<code>def f(it):
    s = 0
    l = 0

    for x in it:
        s += x
        l += 1
        if l > 1:
             yield s

C = sc.parallelize([x for x in range(100)])

while True:
      C = C.repartition(10)\
          .mapPartitions(f)
      if C.isEmpty():
          break
</code>```

It's preferred to use isEmpty() over take(1) to check the whether RDD is empty or not.

Title: Incorrect RDD tranformation

Body:
I am unable to re-use the new RDD that has formed by doing mapPartition. The code seems to work fine only if I add reduceByKey transformation after the mapPartition (I do not want to perform reduceByKey). Since reduceByKey and mapParition are both transformations I am not sure what is causing error.

C = [x for x in xrange(2**20)]
C = sc.parallelize(C)
while True:
    C = C.repartition(1000)\
        .mapPartitions(foo)\
        .persist()

    if C.take(1) == 0 :
        break

Error reported:

TypeError: can't pickle listiterator objects

Body:
The error is due to what you are returning from the mapPartitions is what I believe. If you return a new RDD, I do not see a reason for the code to raise an exception. Following is the code snippet which I developed by using your code.

def f(it):
    s = 0
    l = 0

    for x in it:
        s += x
        l += 1
        if l > 1:
             yield s

C = sc.parallelize([x for x in range(100)])

while True:
      C = C.repartition(10)\
          .mapPartitions(f)
      if C.isEmpty():
          break

It's preferred to use isEmpty() over take(1) to check the whether RDD is empty or not.


问:
What happens to variable x in this for loop in C?
In this code below

```<code>int main(){
int i;
for(i = 0;i<4;i++){
int x = 1;
x++;
} // for close
}// main close
</code>```

Here the variable x is `auto  storage class, right?

So, will the variable x get created, I mean memory allocation happens when the statement is encountered and gets destroyed when it reaches the end of the loop and gets created/memory is allocated again for x?

I tried to print the address of x in the loop and it prints the same address for x every time.So,does it mean every time x is created and destroyed and it is using the same room/memory block for it ?

If it is creating and destroying like that, doesn't it effect CPU usage?
If so, is there any way to prevent it and maintain good memory health?

答:
It is implementation dependent. You see same memory address because compiler decided to do so. Memory isn't magically allocating at new address before each iteration. Automatic storage in the x86 architecture is implemented using stack, allocation is done just by subtraction of ESP/RSP (x86/x64) register, which points to the top of the stack. You can read articles about it in the internet.

Compiler just reassign memory every iteration (not allocating/deallocating)

This is assembly listing of your code (GCC 6.3, x86). Comment in the assembly language starts with ;. I added c like pseudocode to explain the meaning of instructions

```<code>main:
        push    ebp
        mov     ebp, esp ; Create new stack frame
        sub     esp, 16 ; Allocate memory for local variables
        mov     DWORD PTR [ebp-4], 0 ; i = 0;
.L3:
        cmp     DWORD PTR [ebp-4], 3  ; if(i > 3)
                                      ; {
        jg      .L2                   ;    break;
                                      ; }
        mov     DWORD PTR [ebp-8], 1 ; x = 1;
        add     DWORD PTR [ebp-8], 1 ; x += 1;
        add     DWORD PTR [ebp-4], 1 ; i += 1;
        jmp     .L3 ; Go to location .L3
.L2:
        mov     eax, 0 ; Set return value to 0
        leave ; Restore the stack pointer
        ret ; Return to the caller
</code>```

So address of ebp - 8 (or int x) will be same every time.

This is optimized code assembly listing (GCC 6.3,֊O3, x86).

```<code>main:
        xor     eax, eax ; Set return value to 0
        ret ; Return to the caller
</code>```

Body:
In this code below

int main(){
int i;
for(i = 0;i<4;i++){
int x = 1;
x++;
} // for close
}// main close

Here the variable x is `auto  storage class, right?

So, will the variable x get created, I mean memory allocation happens when the statement is encountered and gets destroyed when it reaches the end of the loop and gets created/memory is allocated again for x?

I tried to print the address of x in the loop and it prints the same address for x every time.So,does it mean every time x is created and destroyed and it is using the same room/memory block for it ?

If it is creating and destroying like that, doesn't it effect CPU usage?
If so, is there any way to prevent it and maintain good memory health?

Body:
It is implementation dependent. You see same memory address because compiler decided to do so. Memory isn't magically allocating at new address before each iteration. Automatic storage in the x86 architecture is implemented using stack, allocation is done just by subtraction of ESP/RSP (x86/x64) register, which points to the top of the stack. You can read articles about it in the internet.

Compiler just reassign memory every iteration (not allocating/deallocating)

This is assembly listing of your code (GCC 6.3, x86). Comment in the assembly language starts with ;. I added c like pseudocode to explain the meaning of instructions

main:
        push    ebp
        mov     ebp, esp ; Create new stack frame
        sub     esp, 16 ; Allocate memory for local variables
        mov     DWORD PTR [ebp-4], 0 ; i = 0;
.L3:
        cmp     DWORD PTR [ebp-4], 3  ; if(i > 3)
                                      ; {
        jg      .L2                   ;    break;
                                      ; }
        mov     DWORD PTR [ebp-8], 1 ; x = 1;
        add     DWORD PTR [ebp-8], 1 ; x += 1;
        add     DWORD PTR [ebp-4], 1 ; i += 1;
        jmp     .L3 ; Go to location .L3
.L2:
        mov     eax, 0 ; Set return value to 0
        leave ; Restore the stack pointer
        ret ; Return to the caller

So address of ebp - 8 (or int x) will be same every time.

This is optimized code assembly listing (GCC 6.3,֊O3, x86).

main:
        xor     eax, eax ; Set return value to 0
        ret ; Return to the caller


问:
How to check two instances are having same values in android?
How can I check 2 instances of same class are equal or not in android?

code is as below

```<code>class Address{
    int id;
    String name;
    String street;
    City city;
    State state;
    List<Language> languages;
}
class City{
    int cityId;
    String cityName;
}
class State{
    int stateId;
    String stateName;
}
class Language{
    int langId,
    String langName;
}

class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    .
    .
    .
    Address address1=new Address();
    .
    .
    Address address2=new Address();
    .
    .
    .

    **check address1 and address2 are having same values**
    .
    .
    .

    }

}
</code>```

Kindly let me know the best way to check address1 and address2 instances are having same values or not.

Thanks.

答:
You can compare each value one by one</p>

```<code>public bool compare(Addess a1, Address a2){

    if (a1.attribute1.equals(a2.attribute)){

       if(a1.attribute2.equals(a2.attribute)){
            // do this for all attributes
            return true;
        }

        return false;
}
</code>```

Body:
How can I check 2 instances of same class are equal or not in android?

code is as below

class Address{
    int id;
    String name;
    String street;
    City city;
    State state;
    List<Language> languages;
}
class City{
    int cityId;
    String cityName;
}
class State{
    int stateId;
    String stateName;
}
class Language{
    int langId,
    String langName;
}

class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    .
    .
    .
    Address address1=new Address();
    .
    .
    Address address2=new Address();
    .
    .
    .

    **check address1 and address2 are having same values**
    .
    .
    .

    }

}

Kindly let me know the best way to check address1 and address2 instances are having same values or not.

Thanks.

Body:
You can compare each value one by one

public bool compare(Addess a1, Address a2){

    if (a1.attribute1.equals(a2.attribute)){

       if(a1.attribute2.equals(a2.attribute)){
            // do this for all attributes
            return true;
        }

        return false;
}


问:
node.js needle post not doing its job
Why doesn't Needle do its job here?
It just seems to hang forever waiting to time out.
Eventually I will get the

Ready-o, friend-o

```<code>var express = require('express');
var router = express.Router();
var needle = require('needle');

router.get('/', function (req, resp) {
    console.log("nee.get");

    var data = { key: 'value' };
    needle.post('http://localhost/nee', data, { json: true })
        .on('done', function () {
            console.log('Ready-o, friend-o.');
            resp.sendStatus(200);
        })
});

router.post('/', function (req, resp, next) {
    console.log(req.body.key);
    res.sendStatus(200);
});

module.exports = router;
</code>```

答: if you are like me you forgot to include the :PORT# after the http://localhost</p>

Title: node.js needle post not doing its job

Body:
Why doesn't Needle do its job here?
It just seems to hang forever waiting to time out.
Eventually I will get the

Ready-o, friend-o

var express = require('express');
var router = express.Router();
var needle = require('needle');

router.get('/', function (req, resp) {
    console.log("nee.get");

    var data = { key: 'value' };
    needle.post('http://localhost/nee', data, { json: true })
        .on('done', function () {
            console.log('Ready-o, friend-o.');
            resp.sendStatus(200);
        })
});

router.post('/', function (req, resp, next) {
    console.log(req.body.key);
    res.sendStatus(200);
});

module.exports = router;


问:
Big C# source file with Windows API method signatures, structures, constants: will they all be included in the final .exe?
I want to put all the signatures of Windows API functions I'm using in programs in one class, such as WinAPI, and in a file WinAPI.cs I will include in my projects. The class will be internal static and the methods public static extern. (Something like the huge NativeMethods.cs from the .NET Framework source code).

Let's say WinAPI.cs has one hundred native methods signatures like:

```<code>[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
</code>```

If I'm only going to use a few of them in a project (even one or two), if I include the WinAPI.cs file in my project, will the final .exe be filled with the unnecessary method declarations I'm not using (the other 99 or so)?

What about native structure declarations, If I'm not using them in the current project, will they still be included in the final .exe?

```<code>    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }
</code>```

What about constants declarations or readonly members like:

```<code>public const int WH_JOURNALPLAYBACK = 1;
public static readonly int WM_GETTEXT = 0x0D;
</code>```

答:
Don't sweat the small stuff here.  These are just declarations, there is no IL for them in the final assembly.  They just take up some space in the metadata.  Odds are very high that they don't even get loaded from the assembly, especially when you keep the declarations together.  Metadata is only ever loaded into RAM when it is used, 4096 bytes at a time.

Btw, you explicitly don't want to use readonly for these constant declarations.  Now you do get them to take space, even when they are not used.  One of the few cases where a public const is a good idea.  These are manifest constants, their value never changes.  Like Math.PI.

ContentLicense: CC BY-SA 2.5

Body:
I want to put all the signatures of Windows API functions I'm using in programs in one class, such as WinAPI, and in a file WinAPI.cs I will include in my projects. The class will be internal static and the methods public static extern. (Something like the huge NativeMethods.cs from the .NET Framework source code).

Let's say WinAPI.cs has one hundred native methods signatures like:

[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

If I'm only going to use a few of them in a project (even one or two), if I include the WinAPI.cs file in my project, will the final .exe be filled with the unnecessary method declarations I'm not using (the other 99 or so)?

What about native structure declarations, If I'm not using them in the current project, will they still be included in the final .exe?

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }

What about constants declarations or readonly members like:

public const int WH_JOURNALPLAYBACK = 1;
public static readonly int WM_GETTEXT = 0x0D;


问:
Unable to Start the Name Node in hadoop
I am running the hadoop in my local system but while running ./start-all.sh command its running all functionality except Name Node while running it's getting connection refused and in log file prints below exception

```<code>java.io.ioexception : there appears to be a gap in the edit log, we expected txid 1, but got txid 291.
</code>```

Can You please help me.

答:
Start namenode with recover flag enabled. Use the following command</p>

```<code>./bin/hadoop namenode -recover
</code>```

Title: Unable to Start the Name Node in hadoop

Body:
I am running the hadoop in my local system but while running ./start-all.sh command its running all functionality except Name Node while running it's getting connection refused and in log file prints below exception

java.io.ioexception : there appears to be a gap in the edit log, we expected txid 1, but got txid 291.

Can You please help me.

Body:
Start namenode with recover flag enabled. Use the following command

./bin/hadoop namenode -recover


问:
Python Module Consisting Only of a Single String
It seems to be legal Python code to have a file consisting only of a single quote-enclosed string. The Python interpreter will not complain about the following:

```<code>#!/usr/bin/python

"somevalue"
</code>```

If I wanted to keep some one-off value (say an API key) isolated from other configuration settings, is it possible to import a file like this into another script as a module and use the string?

The default string representation of the imported module will be something like <module x from y-path>. Can the string value contained within that module be somehow accessed?

(To preemptively cut off tangents, I understand I could just read the file as text or assign the value to variable and from module import variable in another script. There are more conventional ways to accomplish related goals. I am asking out of a desire to better understand the language's design and capabilities.)

答:
That string actually ends up being the docstring for the module.
So it is accessed by the __doc__ attribute of the module.
Python picks up the first loose string it finds in a module, class, or function to determine its docstring.

https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring

Body:
It seems to be legal Python code to have a file consisting only of a single quote-enclosed string. The Python interpreter will not complain about the following:

#!/usr/bin/python

"somevalue"

If I wanted to keep some one-off value (say an API key) isolated from other configuration settings, is it possible to import a file like this into another script as a module and use the string?

The default string representation of the imported module will be something like <module x from y-path>. Can the string value contained within that module be somehow accessed?

(To preemptively cut off tangents, I understand I could just read the file as text or assign the value to variable and from module import variable in another script. There are more conventional ways to accomplish related goals. I am asking out of a desire to better understand the language's design and capabilities.)


问:
How can I create customizer with postman

When I tried createsuperuser at terminal, I could make it.
Also I could see created custom user password is hashed.
But when I tried to create custom user. I could make it.
But password is not hashed, and I could not log in.

答:
I don't know whether you are using rest-framework or pure django but either way you need to call:

```<code>user.set_password(validated_data['password'])
</code>```

If you are using built in Django models and views for auth(register, login, ..) it is already done. But if you use custom user model you need to use set_password(). The best way is in create/save method of model form.
Example for rest-framework

Body:
I don't know whether you are using rest-framework or pure django but either way you need to call:

user.set_password(validated_data['password'])

If you are using built in Django models and views for auth(register, login, ..) it is already done. But if you use custom user model you need to use set_password(). The best way is in create/save method of model form.
Example for rest-framework


问:
Why do I get ORA-00979 here?
```<code>SELECT e1.nombreEquipo, p1.idTemporada, COUNT (*)
FROM equipo e1 INNER JOIN partido p1
ON e1.nombreEquipo = p1.nombreLocal OR
    e1.nombreEquipo = p1.nombreVisitante
WHERE p1.golesLocal = p1.golesVisitante
GROUP BY e1.nombreEquipo, p1.idTemporada
HAVING COUNT(*) >=
(
    SELECT COUNT (*)
    FROM partido p2
    WHERE (e1.nombreEquipo = p2.nombreLocal OR e1.nombreEquipo = p2.nombreVisitante) AND (p1.golesLocal = p2.golesLocal) AND
          (p1.idTemporada = p2.idTemporada)
)
</code>```

I'm trying to use this code for an SQL query, but I get the ORA-00936 error when I try to run the script. I have read on several pages that this error is caused by not putting all the select columns in the group by line, but I think I haven´t missed any of them.

It's the first time I use SQL and don't know very much about it.

答:
The problem is in the HAVING clause:

```<code>HAVING COUNT(*) >= (
    SELECT COUNT (*)
    FROM partido p2
    WHERE (e1.nombreEquipo = p2.nombreLocal OR
           e1.nombreEquipo = p2.nombreVisitante
          ) AND (p1.golesLocal = p2.golesLocal) AND
-----------------^
          (p1.idTemporada = p2.idTemporada)
)
</code>```

The column p1.golesLocal is not in the GROUP BY, so it cannot be used after the aggregation, unless it is the argument to an aggregation function.

I can't suggest a fix because I don't know the intention of the query.

Title: Why do I get ORA-00979 here?

Body:
SELECT e1.nombreEquipo, p1.idTemporada, COUNT (*)
FROM equipo e1 INNER JOIN partido p1
ON e1.nombreEquipo = p1.nombreLocal OR
    e1.nombreEquipo = p1.nombreVisitante
WHERE p1.golesLocal = p1.golesVisitante
GROUP BY e1.nombreEquipo, p1.idTemporada
HAVING COUNT(*) >=
(
    SELECT COUNT (*)
    FROM partido p2
    WHERE (e1.nombreEquipo = p2.nombreLocal OR e1.nombreEquipo = p2.nombreVisitante) AND (p1.golesLocal = p2.golesLocal) AND
          (p1.idTemporada = p2.idTemporada)
)

I'm trying to use this code for an SQL query, but I get the ORA-00936 error when I try to run the script. I have read on several pages that this error is caused by not putting all the select columns in the group by line, but I think I haven´t missed any of them.

It's the first time I use SQL and don't know very much about it.

Body:
The problem is in the HAVING clause:

HAVING COUNT(*) >= (
    SELECT COUNT (*)
    FROM partido p2
    WHERE (e1.nombreEquipo = p2.nombreLocal OR
           e1.nombreEquipo = p2.nombreVisitante
          ) AND (p1.golesLocal = p2.golesLocal) AND
-----------------^
          (p1.idTemporada = p2.idTemporada)
)

The column p1.golesLocal is not in the GROUP BY, so it cannot be used after the aggregation, unless it is the argument to an aggregation function.

I can't suggest a fix because I don't know the intention of the query.


问:
Object reference not set to an instance of an object. but the Properties are accessable
I am passing a IList into another class which looks as follows:

```<code>public class KundenViewModel
{
    public IList<Kunde> _kunden;

    /// <summary>
    /// Add a list of Kunde to the View
    /// </summary>
    /// <param name="kunden">A list of Kunde objects</param>
    public KundenViewModel(IList<Kunde> kunden)
    {
        foreach (var k in kunden)
        {
            var test = k._Name;
            _kunden.Add(k);
        }
        //_kunden.AddRange(kunden);
    }

    /// <summary>
    /// Add one Object of Kunde to the View
    /// </summary>
    /// <param name="kunde">A Kunde Object</param>
    public KundenViewModel(Kunde kunde)
    {
        _kunden.Add(kunde);
    }
}
</code>```

But at runtime I receive at the Line 14 (_kunden.Add(k);) the error "Object reference not set to an instance of an object." Well I would say the object has never been initialized, but It has been and I also can access the properties for example the line before, there is no error.

Thanks in Advance

答: Looks like _kunden is null. Where is it initialized?</p>

Body:
I am passing a IList into another class which looks as follows:

public class KundenViewModel
{
    public IList<Kunde> _kunden;

    ///
    /// Add a list of Kunde to the View
    ///
    /// <param name="kunden">A list of Kunde objects</param>
    public KundenViewModel(IList<Kunde> kunden)
    {
        foreach (var k in kunden)
        {
            var test = k._Name;
            _kunden.Add(k);
        }
        //_kunden.AddRange(kunden);
    }

    ///
    /// Add one Object of Kunde to the View
    ///
    /// <param name="kunde">A Kunde Object</param>
    public KundenViewModel(Kunde kunde)
    {
        _kunden.Add(kunde);
    }
}

But at runtime I receive at the Line 14 (_kunden.Add(k);) the error "Object reference not set to an instance of an object." Well I would say the object has never been initialized, but It has been and I also can access the properties for example the line before, there is no error.

Thanks in Advance


问:
Accessing command line (cmd) from RStudio with system() command
I want to use the system() command to access the command line (cmd) from RStudio. But when I place my command in an R script, an error is displayed and indicates that R does not accept the syntax. The command is:

```<code>system("C:\Program Files\ANSYS Inc\v150\ANSYS\bin\winx64\ansys150.exe" -p ane3fl -dir "C:\Users\hamdani\Documents" -j "hamid" -s read -l en-us -b -i "C:\Users\hamdani\Documents\Plane Stress Bracket.txt" -o "C:\Users\hamdani\Documents\fichier.out")
</code>```

The error is:

```<code>Error: '\P' is an unrecognized escape in character string starting "'"C:\P"
</code>```

When I place the command directly in the System Command, it works very well:

```<code>"C:\Users\hamdani\Documents" -j "hamid" -s read -l en-us -b -i "C:\Users\hamdani\Documents\Plane Stress Bracket.txt" -o "C:\Users\hamdani\Documents\fichier.out"
</code>```

答:
The problem is the way that you must enter strings for R.  Your command includes the path to the executable and files, so part of the command is:

```<code>system("C:\Program Files\ANSYS Inc\v150\ANSYS\bin\winx64\ansys150.exe" ...
</code>```

But R uses backslash \ to signal an escape sequence, specialized use of characters such as \n to represent a newline character. Since \ signals an escape sequence is about to start, if you want a backslash character, you must escape the escape, i.e. the way to get a single backslash character in your string is to type \\. You command includes many backslashes.  You need to double all of them to get by this type of error.

OwnerDisplayName: Hamid Hamdani

Body:
I want to use the system() command to access the command line (cmd) from RStudio. But when I place my command in an R script, an error is displayed and indicates that R does not accept the syntax. The command is:

system("C:\Program Files\ANSYS Inc\v150\ANSYS\bin\winx64\ansys150.exe" -p ane3fl -dir "C:\Users\hamdani\Documents" -j "hamid" -s read -l en-us -b -i "C:\Users\hamdani\Documents\Plane Stress Bracket.txt" -o "C:\Users\hamdani\Documents\fichier.out")

The error is:

Error: '\P' is an unrecognized escape in character string starting "'"C:\P"

When I place the command directly in the System Command, it works very well:

"C:\Users\hamdani\Documents" -j "hamid" -s read -l en-us -b -i "C:\Users\hamdani\Documents\Plane Stress Bracket.txt" -o "C:\Users\hamdani\Documents\fichier.out"

Body:
The problem is the way that you must enter strings for R.  Your command includes the path to the executable and files, so part of the command is:

system("C:\Program Files\ANSYS Inc\v150\ANSYS\bin\winx64\ansys150.exe" ...

But R uses backslash \ to signal an escape sequence, specialized use of characters such as \n to represent a newline character. Since \ signals an escape sequence is about to start, if you want a backslash character, you must escape the escape, i.e. the way to get a single backslash character in your string is to type \\. You command includes many backslashes.  You need to double all of them to get by this type of error.


问:
Matrix of random permutations
I want to create a matrix of x columns of random permutations from 1 to 10, say. The command randperm(10) works great, yet I would like to create x of those.

Is there a way to do it without a loop?
Thanks,

答:
Without for loop

The below code works but is not spatially optimal because all n! permutations before sampling from them.

O(perms) time constraint

O(n!) space constraint

```<code>mat = datasample(perms(1:n),k,'Replace',false);
</code>```

With for loop

If you use a loop you could do something like the following. The downside here is that you'll have to check your output matrix every loop (if you need to ensure unique permutations).

O(n!) time constraints

O(k) space constraints

```<code>mat = zeros(x,n)
count = 1;
while count < x+1
   temp = randperm(n);

   if ismember(temp,mat,'rows')
       mat(count,:) = temp;
       count = count + 1;
   end
end
</code>```

Summary

If you have a large n you'll run into issues with n! space constraints before n!time in MATLAB so I'd recommend the second solution.

If you have large k/n! the first solution will be significantly faster and similar space constraints

If you have low k and n the first solution ensures you do not need to check for unique permutations so I'd go with that for that reason.

Title: Matrix of random permutations

Body:
Without for loop

The below code works but is not spatially optimal because all n! permutations before sampling from them.

O(perms) time constraint

O(n!) space constraint

mat = datasample(perms(1:n),k,'Replace',false);

With for loop

If you use a loop you could do something like the following. The downside here is that you'll have to check your output matrix every loop (if you need to ensure unique permutations).

O(n!) time constraints

O(k) space constraints

mat = zeros(x,n)
count = 1;
while count < x+1
   temp = randperm(n);

   if ismember(temp,mat,'rows')
       mat(count,:) = temp;
       count = count + 1;
   end
end

Summary

If you have a large n you'll run into issues with n! space constraints before n!time in MATLAB so I'd recommend the second solution.

If you have large k/n! the first solution will be significantly faster and similar space constraints

If you have low k and n the first solution ensures you do not need to check for unique permutations so I'd go with that for that reason.


问:
Xcode8 - Program is not executing correctly
While using Xcode8 says that it is running but there is no output.

Output:

10

Please enter the rectangle's length:

10

Please enter the rectangle's width:

The length for the rectangle is 10.00

The width for the rectangel is 10.00

The area for a rectangle is 100.00

The radius for a circle is 10.00

The area for a circle is 314.16

Program ended with exit code: 0

Wanted Output:

Please enter the rectangle's length: 10

Please enter the rectangle's width: 10

The length for the rectangle is 10.00

The width for the rectangel is 10.00

The area for a rectangle is 100.00

The radius for a circle is 10.00

The area for a circle is 314.16

Program ended with exit code: 0

```<code>#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

// Function prototypes
double getLength(); // Function that receives the length
double getWidth(); // Function that receives the width
double getArea(double); //Function calculates area for circle
double getArea(double,double); // Function calculates area for rectangle
void displayData(double,double,double,double, double);
// displayData function is used to display values

int main() {

    // Declares variables
    double length, width, circleArea, rectangleArea;

    length = getLength(); // Stores length
    width = getWidth(); // Stores width
    circleArea = getArea(width); // Stores area of circle
    rectangleArea = getArea(width, length); // Stores are of rectangle

    // Displays the length, width, area of circle, and rectangle area
    displayData(length, width, rectangleArea, width, circleArea);

    return 0;
}

/* This function asks the user to enter the rectangle's length and
 then returns that values as a double */

double getLength() {
    double length;
    cout << "Please enter the rectangle's length: ";
    cin >> length; // User input is stored in variable length
    cout << "\n";
    /* While loop doesn't let user input a
    negative value or a value of zero for
    the length of the rectangle. */

    while (length <= 0) {

        if (length < 0) { //if statement used when a negative value is entered for length
            cout << "INVALID INPUT!" << endl; // Error message
            cout << "Please enter a positive value for the Length of the Rectangle: ";
            // Asks the user to enter the length again

            cin >> length; // Stores value of length

            if (length > 0) {
                cout << "\n";
            }
        }
        if (length == 0) { // If statement used when a value of zero is entered for length
            cout << "INVALID INPUT!" << endl;//error message
            cout << "Please enter a positive value for the Length of the Rectangle: ";
            // Asks the user to enter the length again

            cin >> length;// Stores the value of length

            if (length > 0) {
                cout << "\n";
            }
        }
    }

    return length;
}

/* This function asks the user to enter the rectangle's width and
 then returns that values as a double */

double getWidth() {
    double width;
    cout << "Please enter the rectangle's width: ";
    cin >> width; // User input is stored in variable width
    cout << "\n";

    /* While loop doesn't let user input a
     negative value or a value of zero for the
     width of the rectangle. */

    while (width <= 0) {
        if (width < 0) { // If statement used when a negative value is entered for width

            cout << "INVALID INPUT!" << endl; // Error message
            cout << "Please enter a positive value for the Width of the Rectangle: ";
            // Asks the user to enter the width again
            cin >> width; //Stores the value of width in the variable, width
            if (width > 0) {
                cout << "\n";
            }
        }
        if (width == 0) { // If statement used when a value of zero is entered for width
            cout << "INVALID INPUT!" << endl; // Error message
            cout << "Please enter a positive value for the Width of the Rectangle: ";
            // Asks the user to enter the width again
            cin >> width; // Stores the value of width in the variable, width
            if (width > 0)
            {
                cout << "\n";
            }
        }
    }

    return width;
}

double getArea(double radius) {
    const double PI = 3.14159;
    double circleArea;

    circleArea = PI * pow(radius, 2); // Formula for the area of a circle
    return circleArea;

}

/* This function accepts the rectangle's length and width as arguments and returns
 the rectangle's area. The area is calculated by multiplying the length by the
 width. */

double getArea(double length, double width) {
    double rectangleArea;

    rectangleArea = length * width; // Formula for the area of a rectangle
    return rectangleArea;
}

/* This function accepts the rectangle's length, width, and area as arguments
 and displays them in an appropriate message on the screen */

void displayData(double l, double w, double ra, double r, double ca) {

    cout << setprecision(2) << fixed;
    cout << "The length for the rectangle is " << l << endl;
    cout << "The width for the rectangle is " << w << endl;
    cout << "The area for a rectangle is " << ra << endl << endl;
    cout << "The radius for the circle is " << r << endl;
    cout << "The area for the circle is " << ca << endl;

}
</code>```

答:
When you use << with cout, it doesn't immediately push to the screen. A common way to send the output, as you've shown, is endl. If you don't want a line return, use flush.

```<code>cout << "Please enter the rectangle's length: " << flush;
</code>```

EDIT: Xcode 8.3 seems to have new rules about cin and cout on the same line.

Body:
While using Xcode8 says that it is running but there is no output.

Output:

10

Please enter the rectangle's length:

10

Please enter the rectangle's width:

The length for the rectangle is 10.00

The width for the rectangel is 10.00

The area for a rectangle is 100.00

The radius for a circle is 10.00

The area for a circle is 314.16

Program ended with exit code: 0

Wanted Output:

Please enter the rectangle's length: 10

Please enter the rectangle's width: 10

The length for the rectangle is 10.00

The width for the rectangel is 10.00

The area for a rectangle is 100.00

The radius for a circle is 10.00

The area for a circle is 314.16

Program ended with exit code: 0

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

// Function prototypes
double getLength(); // Function that receives the length
double getWidth(); // Function that receives the width
double getArea(double); //Function calculates area for circle
double getArea(double,double); // Function calculates area for rectangle
void displayData(double,double,double,double, double);
// displayData function is used to display values

int main() {

    // Declares variables
    double length, width, circleArea, rectangleArea;

    length = getLength(); // Stores length
    width = getWidth(); // Stores width
    circleArea = getArea(width); // Stores area of circle
    rectangleArea = getArea(width, length); // Stores are of rectangle

    // Displays the length, width, area of circle, and rectangle area
    displayData(length, width, rectangleArea, width, circleArea);

    return 0;
}

/* This function asks the user to enter the rectangle's length and
 then returns that values as a double */

double getLength() {
    double length;
    cout << "Please enter the rectangle's length: ";
    cin >> length; // User input is stored in variable length
    cout << "\n";
    /* While loop doesn't let user input a
    negative value or a value of zero for
    the length of the rectangle. */

    while (length <= 0) {

        if (length < 0) { //if statement used when a negative value is entered for length
            cout << "INVALID INPUT!" << endl; // Error message
            cout << "Please enter a positive value for the Length of the Rectangle: ";
            // Asks the user to enter the length again

            cin >> length; // Stores value of length

            if (length > 0) {
                cout << "\n";
            }
        }
        if (length == 0) { // If statement used when a value of zero is entered for length
            cout << "INVALID INPUT!" << endl;//error message
            cout << "Please enter a positive value for the Length of the Rectangle: ";
            // Asks the user to enter the length again

            cin >> length;// Stores the value of length

            if (length > 0) {
                cout << "\n";
            }
        }
    }

    return length;
}

/* This function asks the user to enter the rectangle's width and
 then returns that values as a double */

double getWidth() {
    double width;
    cout << "Please enter the rectangle's width: ";
    cin >> width; // User input is stored in variable width
    cout << "\n";

    /* While loop doesn't let user input a
     negative value or a value of zero for the
     width of the rectangle. */

    while (width <= 0) {
        if (width < 0) { // If statement used when a negative value is entered for width

            cout << "INVALID INPUT!" << endl; // Error message
            cout << "Please enter a positive value for the Width of the Rectangle: ";
            // Asks the user to enter the width again
            cin >> width; //Stores the value of width in the variable, width
            if (width > 0) {
                cout << "\n";
            }
        }
        if (width == 0) { // If statement used when a value of zero is entered for width
            cout << "INVALID INPUT!" << endl; // Error message
            cout << "Please enter a positive value for the Width of the Rectangle: ";
            // Asks the user to enter the width again
            cin >> width; // Stores the value of width in the variable, width
            if (width > 0)
            {
                cout << "\n";
            }
        }
    }

    return width;
}

double getArea(double radius) {
    const double PI = 3.14159;
    double circleArea;

    circleArea = PI * pow(radius, 2); // Formula for the area of a circle
    return circleArea;

}

/* This function accepts the rectangle's length and width as arguments and returns
 the rectangle's area. The area is calculated by multiplying the length by the
 width. */

double getArea(double length, double width) {
    double rectangleArea;

    rectangleArea = length * width; // Formula for the area of a rectangle
    return rectangleArea;
}

/* This function accepts the rectangle's length, width, and area as arguments
 and displays them in an appropriate message on the screen */

void displayData(double l, double w, double ra, double r, double ca) {

    cout << setprecision(2) << fixed;
    cout << "The length for the rectangle is " << l << endl;
    cout << "The width for the rectangle is " << w << endl;
    cout << "The area for a rectangle is " << ra << endl << endl;
    cout << "The radius for the circle is " << r << endl;
    cout << "The area for the circle is " << ca << endl;

}

Body:
When you use << with cout, it doesn't immediately push to the screen. A common way to send the output, as you've shown, is endl. If you don't want a line return, use flush.

cout << "Please enter the rectangle's length: " << flush;

EDIT: Xcode 8.3 seems to have new rules about cin and cout on the same line.


问:
Macro loop through and update some cells
I have a sheet (Master) which should be updated periodically based on information in another sheet (NewData). In column A there is an unique id in both sheets. In the NewData sheet there might be some new id's which should be transferred to the Master sheet, and if the NewData sheet failes to have an id which is registered in the Master sheet, this id (entire row) should be removed from Master sheet. In other words: The NewData sheet gives the blueprint of which id's to be in the Master sheet.

The NewData sheet contains updated data to some of the columns in the Master sheet. I can't blindly copy the information between the two sheets because the user might have put a hyperlink in the cell - and that hyperlink should not be deleted.

Example:

The Master sheet looks like this before update

The NewData sheet looks like this

I am not allowed to post more than two links, so I have to verbally describe how the updated Master sheet shoukd look like after running the macro:

Rowid 2001 (Kjell) should be unchanged

Rowid 2345 (Vegard) should be removed (as it is not in the NewData
sheet)

Rowid 1002 (Fenja) should be almost as in original Master, but
with a new description and a new date, and now a date without the
hyperlink.

Rowid 1234 () should be as a new row (without data in Name cell)

I guess this can be solved by rather simple vba-programming, but I don't even have basic knowledge, and after trying a lot of copy/paste, trying vlookup and index-match and... I took the step to bother this community... Very glad if any could help me!

答:
I assume each of the row ids are unique in both worksheets.  If so you can use a dictionary object and populate it with all the values in the Master worksheet.  Once that's done you can iterate through the NewData worksheet and if an encountered id exists in the dictionary, then update the Master record (ie that record is in both Master and NewData);  note, that you delete the dictionary key/value pair once that's done.   If it doesn't exist then you append it to the end of the Master worksheet (ie that record is in NewData but not in Master).

After that loop completes the only entries in the dictionary are keys that exist in Master but not in NewData and can be deleted - which is what's done in the last loop:

```<code>Option Explicit

Sub updateMaster()
  Dim dict As Object
  Set dict = CreateObject("Scripting.Dictionary")

  Dim wrkM As Worksheet: Set wrkM = Worksheets("Master")
  Dim wrkD As Worksheet: Set wrkD = Worksheets("NewData")

  Dim r As Integer, r1 As Integer, lr As Integer
  Dim rng As Range
  Dim val As String
  With wrkM:
    lr = .Range("A" & .Rows.Count).End(xlUp).row
    For r = 2 To lr:
      Set rng = .Range("A" & r).EntireRow
      val = Trim(.Cells(r, "A").Value)
      Set dict(val) = rng
    Next
  End With
  lr = lr + 1

  Dim str As Variant
  With wrkD:
    For r = 2 To .Range("A" & .Rows.Count).End(xlUp).row:
      str = Trim(.Cells(r, "A").Value)
      If dict.Exists(str) Then
        Set rng = dict(str)
        r1 = rng.row
        wrkM.Cells(r1, "B").Value = .Cells(r, "B").Value
        wrkM.Cells(r1, "E").Value = .Cells(r, "C").Value
        wrkM.Cells(r1, "D").Value = .Cells(r, "D").Value
        dict.Remove str
      Else
        wrkM.Cells(lr, "A").Value = .Cells(r, "A").Value
        wrkM.Cells(lr, "B").Value = .Cells(r, "B").Value
        wrkM.Cells(lr, "D").Value = .Cells(r, "D").Value
        wrkM.Cells(lr, "E").Value = .Cells(r, "C").Value
        lr = lr + 1
      End If
    Next
  End With

  For Each str In dict.keys():
     Set rng = dict(str)
     rng.Delete
  Next

End Sub
</code>```

If you have a contiguous range you can replace the 1st 2 rows in the else condition with the following:

```<code>.Range("A" & r, "B" & r).Copy Destination:=wrkM.Range("A" & lr, "B" & lr)
</code>```

but for just 2 rows it isn't as efficient.

Body:
I assume each of the row ids are unique in both worksheets.  If so you can use a dictionary object and populate it with all the values in the Master worksheet.  Once that's done you can iterate through the NewData worksheet and if an encountered id exists in the dictionary, then update the Master record (ie that record is in both Master and NewData);  note, that you delete the dictionary key/value pair once that's done.   If it doesn't exist then you append it to the end of the Master worksheet (ie that record is in NewData but not in Master).

After that loop completes the only entries in the dictionary are keys that exist in Master but not in NewData and can be deleted - which is what's done in the last loop:

Option Explicit

Sub updateMaster()
  Dim dict As Object
  Set dict = CreateObject("Scripting.Dictionary")

  Dim wrkM As Worksheet: Set wrkM = Worksheets("Master")
  Dim wrkD As Worksheet: Set wrkD = Worksheets("NewData")

  Dim r As Integer, r1 As Integer, lr As Integer
  Dim rng As Range
  Dim val As String
  With wrkM:
    lr = .Range("A" & .Rows.Count).End(xlUp).row
    For r = 2 To lr:
      Set rng = .Range("A" & r).EntireRow
      val = Trim(.Cells(r, "A").Value)
      Set dict(val) = rng
    Next
  End With
  lr = lr + 1

  Dim str As Variant
  With wrkD:
    For r = 2 To .Range("A" & .Rows.Count).End(xlUp).row:
      str = Trim(.Cells(r, "A").Value)
      If dict.Exists(str) Then
        Set rng = dict(str)
        r1 = rng.row
        wrkM.Cells(r1, "B").Value = .Cells(r, "B").Value
        wrkM.Cells(r1, "E").Value = .Cells(r, "C").Value
        wrkM.Cells(r1, "D").Value = .Cells(r, "D").Value
        dict.Remove str
      Else
        wrkM.Cells(lr, "A").Value = .Cells(r, "A").Value
        wrkM.Cells(lr, "B").Value = .Cells(r, "B").Value
        wrkM.Cells(lr, "D").Value = .Cells(r, "D").Value
        wrkM.Cells(lr, "E").Value = .Cells(r, "C").Value
        lr = lr + 1
      End If
    Next
  End With

  For Each str In dict.keys():
     Set rng = dict(str)
     rng.Delete
  Next

End Sub

If you have a contiguous range you can replace the 1st 2 rows in the else condition with the following:

.Range("A" & r, "B" & r).Copy Destination:=wrkM.Range("A" & lr, "B" & lr)

but for just 2 rows it isn't as efficient.


问:
Why my carousel disappear when click on menu?
can anybody tell me why my bootstrap carousel disappear when i click on nav menu btn..

I want to smooth scroll to div on same page...
Can any body sole this weird problem.

here is a fiddle---------------
https://jsfiddle.net/vo1npqdx/502/

$(document).ready(function() {
  // Add smooth scrolling to all links
  $("#siteoverview_btn").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior

    $(".active").removeClass("active");

    // Prevent default anchor click behavior
    event.preventDefault();

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $("#siteoverview_content").offset().top
    }, 800, function() {

      // Add hash (#) to URL when done scrolling (default click behavior)
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <!-- nav here -->
  <nav class="navbar navbar-default roboto normal menu" role="navigation">
    <div class="container">
      <div class="navbar-header">
      </div>
      <ul class="nav navbar-nav nav_bar_block">
        <li class="border_right">SITE OVERVIEW</li>
      </ul>
    </div>
  </nav>

  <!-- nav here -->

  <div class="banner">
    <div class="notification_bar">
      <div class="container">
        <div class="content">
        </div>
      </div>
    </div>

    <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
      </ol>

      <!-- Wrapper for slides -->
      <div class="carousel-inner" role="listbox">
        <div class="item active">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
        <div class="item">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
        <div class="item">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
      </div>

      <!-- Controls -->

        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>

        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>

    </div>
  </div>

  <div class="main_body">
    <div class="container">
      <div class="body_content">
        <h3 class="body_head">AUCTION CENTRE</h3>
        <div class="row">
          <div class="col-sm-8">

            <p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of
              Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.
              It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic
              words etc.</p>

            <br>
            <div class="row content_points">
              <div class="col-sm-6">
                <h4>LATEST NEWS</h4>
                <hr class="underline">
                <ul>
                  <li><b>LAST UPDATED ON: MARCH 17, 2017</b></li>
                  <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
                  <li>Many desktop publishing packages and web page editors</li>
                  <li>All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary</li>
                  <li>The standard chunk of Lorem Ipsum used since the 1500s is reproduced below</li>
                  <li>Many desktop publishing packages and web page editors</li>
                </ul>
              </div>
              <div id="siteoverview_content" class="col-sm-6">
                <h4>SITE OVERVIEW</h4>
                <hr class="underline">
                <ul>
                  <li>AWR Upload</li>
                  <li>AWR Report</li>
                  <li>Statistical Info</li>
                  <li>Gatepass Entry</li>
                  <li>Customised Reports</li>
                  <li>Other Info</li>
                  <li>Other Info 1</li>
                  <li>Other Info 2</li>
                </ul>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>

  </div>

  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body></code>```

答:
Just remove $(".active").removeClass("active"); inside $("#siteoverview_btn").on('click', function(event) {...}). this remove the active class of bootstrap carousel and error comes

$(document).ready(function() {
  // Add smooth scrolling to all links
  $("#siteoverview_btn").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior

    //$(".active").removeClass("active");

    // Prevent default anchor click behavior
    event.preventDefault();

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $("#siteoverview_content").offset().top
    }, 800, function() {

      // Add hash (#) to URL when done scrolling (default click behavior)
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <!-- nav here -->
  <nav class="navbar navbar-default roboto normal menu" role="navigation">
    <div class="container">
      <div class="navbar-header">
      </div>
      <ul class="nav navbar-nav nav_bar_block">
        <li class="border_right">SITE OVERVIEW</li>
      </ul>
    </div>
  </nav>

  <!-- nav here -->

  <div class="banner">
    <div class="notification_bar">
      <div class="container">
        <div class="content">
        </div>
      </div>
    </div>

    <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
      </ol>

      <!-- Wrapper for slides -->
      <div class="carousel-inner" role="listbox">
        <div class="item active">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
        <div class="item">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
        <div class="item">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
      </div>

      <!-- Controls -->

        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>

        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>

    </div>
  </div>

  <div class="main_body">
    <div class="container">
      <div class="body_content">
        <h3 class="body_head">AUCTION CENTRE</h3>
        <div class="row">
          <div class="col-sm-8">

            <p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of
              Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.
              It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic
              words etc.</p>

            <br>
            <div class="row content_points">
              <div class="col-sm-6">
                <h4>LATEST NEWS</h4>
                <hr class="underline">
                <ul>
                  <li><b>LAST UPDATED ON: MARCH 17, 2017</b></li>
                  <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
                  <li>Many desktop publishing packages and web page editors</li>
                  <li>All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary</li>
                  <li>The standard chunk of Lorem Ipsum used since the 1500s is reproduced below</li>
                  <li>Many desktop publishing packages and web page editors</li>
                </ul>
              </div>
              <div id="siteoverview_content" class="col-sm-6">
                <h4>SITE OVERVIEW</h4>
                <hr class="underline">
                <ul>
                  <li>AWR Upload</li>
                  <li>AWR Report</li>
                  <li>Statistical Info</li>
                  <li>Gatepass Entry</li>
                  <li>Customised Reports</li>
                  <li>Other Info</li>
                  <li>Other Info 1</li>
                  <li>Other Info 2</li>
                </ul>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>

  </div>

  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body></code>```

Body:
can anybody tell me why my bootstrap carousel disappear when i click on nav menu btn..

I want to smooth scroll to div on same page...
Can any body sole this weird problem.

here is a fiddle---------------
https://jsfiddle.net/vo1npqdx/502/

$(document).ready(function() {
  // Add smooth scrolling to all links
  $("#siteoverview_btn").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior

    $(".active").removeClass("active");

    // Prevent default anchor click behavior
    event.preventDefault();

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $("#siteoverview_content").offset().top
    }, 800, function() {

      // Add hash (#) to URL when done scrolling (default click behavior)
    });
  });
});

  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

SITE OVERVIEW

            ...

            ...

            ...

        Previous

        Next

AUCTION CENTRE

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of
              Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.
              It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic
              words etc.

LATEST NEWS

LAST UPDATED ON: MARCH 17, 2017

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Many desktop publishing packages and web page editors

All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below

Many desktop publishing packages and web page editors

SITE OVERVIEW

AWR Upload

AWR Report

Statistical Info

Gatepass Entry

Customised Reports

Other Info

Other Info 1

Other Info 2

Body:
Just remove $(".active").removeClass("active"); inside $("#siteoverview_btn").on('click', function(event) {...}). this remove the active class of bootstrap carousel and error comes

$(document).ready(function() {
  // Add smooth scrolling to all links
  $("#siteoverview_btn").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior

    //$(".active").removeClass("active");

    // Prevent default anchor click behavior
    event.preventDefault();

    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $('html, body').animate({
      scrollTop: $("#siteoverview_content").offset().top
    }, 800, function() {

      // Add hash (#) to URL when done scrolling (default click behavior)
    });
  });
});

<body>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <!-- nav here -->
  <nav class="navbar navbar-default roboto normal menu" role="navigation">
    <div class="container">
      <div class="navbar-header">
      </div>
      <ul class="nav navbar-nav nav_bar_block">
        <li class="border_right"><a id="siteoverview_btn">SITE OVERVIEW</a></li>
      </ul>
    </div>
  </nav>

  <!-- nav here -->

  <div class="banner">
    <div class="notification_bar">
      <div class="container">
        <div class="content">
        </div>
      </div>
    </div>

    <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
      </ol>

      <!-- Wrapper for slides -->
      <div class="carousel-inner" role="listbox">
        <div class="item active">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
        <div class="item">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
        <div class="item">
          <img src="http://www.777a7.com/img65/vxxrimfdyqtwewgfynzp.jpg" alt="...">
          <div class="carousel-caption">
            ...
          </div>
        </div>
      </div>

      <!-- Controls -->
      <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
      </a>
      <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
      </a>
    </div>
  </div>

  <div class="main_body">
    <div class="container">
      <div class="body_content">
        <h3 class="body_head">AUCTION CENTRE</h3>
        <div class="row">
          <div class="col-sm-8">

            <p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of
              Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.
              It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic
              words etc.</p>

            <br>
            <div class="row content_points">
              <div class="col-sm-6">
                <h4>LATEST NEWS</h4>
                <hr class="underline">
                <ul>
                  <li><b>LAST UPDATED ON: MARCH 17, 2017</b></li>
                  <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
                  <li>Many desktop publishing packages and web page editors</li>
                  <li>All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary</li>
                  <li>The standard chunk of Lorem Ipsum used since the 1500s is reproduced below</li>
                  <li>Many desktop publishing packages and web page editors</li>
                </ul>
              </div>
              <div id="siteoverview_content" class="col-sm-6">
                <h4>SITE OVERVIEW</h4>
                <hr class="underline">
                <ul>
                  <li>AWR Upload</li>
                  <li>AWR Report</li>
                  <li>Statistical Info</li>
                  <li>Gatepass Entry</li>
                  <li>Customised Reports</li>
                  <li>Other Info</li>
                  <li>Other Info 1</li>
                  <li>Other Info 2</li>
                </ul>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>

  </div>

  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>