问:
serialization of class into XML C#
I'm Having Below Class i.e ReconciliationRequest.cs

```<code>using System;
using System.Collections.Generic;
using System.Xml.Serialization;

[XmlRoot("ReconciliationRequest")]
[Serializable]
public class ReconciliationRequest
{

    public List<Patient> PatientDetails;
}
[Serializable]

public class Patient
{
    [XmlElement("NHSNumber")]
    public string NHSNumber { get; set; }

    [XmlElement("PDSChangeSerialNumber")]
    public string PDSChangeSerialNumber { get; set; }

}
</code>```

I want to serialize it into XML In Below Format

```<code><ReconciliationRequest xmlns="http://schemas.capita.co.uk/pcse/crm">
        <Patient>
            <NHSNumber>1234567890</NHSNumber>
            <PDSChangeSerialNumber>1234</PDSChangeSerialNumber>
        </Patient>

</ReconciliationRequest>
</code>```

But I'm Getting It into below format,i dont want PatientDetails tag in xml,
iwant it in above mentioned result.

```<code> <ReconciliationRequest>
      <PatientDetails>
        <Patient>
          <NHSNumber>9411992455</NHSNumber>
          <PDSChangeSerialNumber>5</PDSChangeSerialNumber>
        </Patient>
        <Patient>
          <NHSNumber>9801153512</NHSNumber>
          <PDSChangeSerialNumber>20</PDSChangeSerialNumber>
        </Patient>

      </PatientDetails>
    </ReconciliationRequest>
</code>```

I don't want PatientDetails Node .
Below is the code i used to serialize this class object into XML

```<code>ReconciliationRequest obj = new ReconciliationRequest();
                Patient obj1;
                List<Patient> PatientDetails = new List<Patient>();
                if (results.Entities.Count > 0)
                {
                    var PatientData = results.Entities[0].ToEntity<Contact>();

                    foreach (var item in results.Entities)
                    {
                        obj1 = new Patient();
                        if (item.Attributes.Keys.Contains("scr_nhs_number") && item.Attributes.Keys.Contains("csr_pdsserialchangenumber"))
                        {
                            if (!string.IsNullOrEmpty(item.Attributes["scr_nhs_number"].ToString()))
                            {
                                obj1.NHSNumber = item.Attributes["scr_nhs_number"].ToString();
                            }
                            if (!string.IsNullOrEmpty(item.Attributes["csr_pdsserialchangenumber"].ToString()))
                            {
                                obj1.PDSChangeSerialNumber = item.Attributes["csr_pdsserialchangenumber"].ToString();
                            }

                            PatientDetails.Add(obj1);
                        }
                    }
                    obj.PatientDetails = PatientDetails;

                    XmlSerializer serializer =
       new XmlSerializer(typeof(ReconciliationRequest));
                    TextWriter writer = new StreamWriter("D:\\CS\\data3.xml");
                    XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
                    nameSpace.Add(string.Empty, "http://schemas.capita.co.uk/pcse/crm");

                    serializer.Serialize(writer, obj, nameSpace);
                    writer.Close();
                }

            }
</code>```

Please guide me how can resolve this.

答:
```<code>[XmlRoot("ReconciliationRequest", Namespace = "http://schemas.capita.co.uk/pcse/crm")]
public class ReconciliationRequest
{
    [XmlElement("Patient")]
    public List<Patient> PatientDetails;
}
</code>```

although personally I'd use:

```<code>[XmlElement("Patient")]
public List<Patient> PatientDetails { get; } = new List<Patient>();
</code>```

Title: serialization of class into XML C#

Body:
I'm Having Below Class i.e ReconciliationRequest.cs

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

[XmlRoot("ReconciliationRequest")]
[Serializable]
public class ReconciliationRequest
{

    public List<Patient> PatientDetails;
}
[Serializable]

public class Patient
{
    [XmlElement("NHSNumber")]
    public string NHSNumber { get; set; }

    [XmlElement("PDSChangeSerialNumber")]
    public string PDSChangeSerialNumber { get; set; }

}

I want to serialize it into XML In Below Format

<ReconciliationRequest xmlns="http://schemas.capita.co.uk/pcse/crm">
        <Patient>
            <NHSNumber>1234567890</NHSNumber>
            <PDSChangeSerialNumber>1234</PDSChangeSerialNumber>
        </Patient>

</ReconciliationRequest>

But I'm Getting It into below format,i dont want PatientDetails tag in xml,
iwant it in above mentioned result.

 <ReconciliationRequest>
      <PatientDetails>
        <Patient>
          <NHSNumber>9411992455</NHSNumber>
          <PDSChangeSerialNumber>5</PDSChangeSerialNumber>
        </Patient>
        <Patient>
          <NHSNumber>9801153512</NHSNumber>
          <PDSChangeSerialNumber>20</PDSChangeSerialNumber>
        </Patient>

      </PatientDetails>
    </ReconciliationRequest>

I don't want PatientDetails Node .
Below is the code i used to serialize this class object into XML

ReconciliationRequest obj = new ReconciliationRequest();
                Patient obj1;
                List<Patient> PatientDetails = new List<Patient>();
                if (results.Entities.Count > 0)
                {
                    var PatientData = results.Entities[0].ToEntity<Contact>();

                    foreach (var item in results.Entities)
                    {
                        obj1 = new Patient();
                        if (item.Attributes.Keys.Contains("scr_nhs_number") && item.Attributes.Keys.Contains("csr_pdsserialchangenumber"))
                        {
                            if (!string.IsNullOrEmpty(item.Attributes["scr_nhs_number"].ToString()))
                            {
                                obj1.NHSNumber = item.Attributes["scr_nhs_number"].ToString();
                            }
                            if (!string.IsNullOrEmpty(item.Attributes["csr_pdsserialchangenumber"].ToString()))
                            {
                                obj1.PDSChangeSerialNumber = item.Attributes["csr_pdsserialchangenumber"].ToString();
                            }

                            PatientDetails.Add(obj1);
                        }
                    }
                    obj.PatientDetails = PatientDetails;

                    XmlSerializer serializer =
       new XmlSerializer(typeof(ReconciliationRequest));
                    TextWriter writer = new StreamWriter("D:\\CS\\data3.xml");
                    XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
                    nameSpace.Add(string.Empty, "http://schemas.capita.co.uk/pcse/crm");

                    serializer.Serialize(writer, obj, nameSpace);
                    writer.Close();
                }

            }

Please guide me how can resolve this.

Body:
[XmlRoot("ReconciliationRequest", Namespace = "http://schemas.capita.co.uk/pcse/crm")]
public class ReconciliationRequest
{
    [XmlElement("Patient")]
    public List<Patient> PatientDetails;
}

although personally I'd use:

[XmlElement("Patient")]
public List<Patient> PatientDetails { get; } = new List<Patient>();


来源: stackexchange

问:
Multi-threading in Android
I'm new to Android and Java. I'm trying to download 1000 plus images. I don't want to do that serially in a UI thread as that will be slow. Hence, I implemented multi-threading using thread and runnable in the below manner.

The for-loop will be called 1000 plus times. So is it an efficient way of achieving it? Will the OS manage the thread pool by its own?

```<code>private void syncS3Data() {
    tStart = System.currentTimeMillis();
    try {
        for (final AWSSyncFile f : awsSyncData.getFiles()) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    beginDownload(f);
                }

            }).start();
        }
    } catch (Exception ex) {
        progressDialog.dismiss();
        showMessage("Error:" + ex.getStackTrace().toString());
    }
}
</code>```

答:
I had developed an e-commerce app before and have encountered a similar problem in which I had to download some 200+ images for each category.The way I did it was using a loop within an AsyncTask and after each download was completed the image was displayed at the relevant place using the onProgessUpdate() function.I can't share the actual code,so i will give a skeleton example.</p>

```<code>public class DownloadImages extends AsyncTask<String,String,String>
{
  File image;
  protected String doInBackground(String... params)
    {
      //download the image here and lets say its stored in the variable file
      //call publishProgress() to run onProgressUpdate()

    }
  protected void onProgressUpdate(String... values)
  {
     //use the image in variable file to update the UI
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Multi-threading in Android

Body:
I'm new to Android and Java. I'm trying to download 1000 plus images. I don't want to do that serially in a UI thread as that will be slow. Hence, I implemented multi-threading using thread and runnable in the below manner.

The for-loop will be called 1000 plus times. So is it an efficient way of achieving it? Will the OS manage the thread pool by its own?

private void syncS3Data() {
    tStart = System.currentTimeMillis();
    try {
        for (final AWSSyncFile f : awsSyncData.getFiles()) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    beginDownload(f);
                }

            }).start();
        }
    } catch (Exception ex) {
        progressDialog.dismiss();
        showMessage("Error:" + ex.getStackTrace().toString());
    }
}

Body:
I had developed an e-commerce app before and have encountered a similar problem in which I had to download some 200+ images for each category.The way I did it was using a loop within an AsyncTask and after each download was completed the image was displayed at the relevant place using the onProgessUpdate() function.I can't share the actual code,so i will give a skeleton example.

public class DownloadImages extends AsyncTask<String,String,String>
{
  File image;
  protected String doInBackground(String... params)
    {
      //download the image here and lets say its stored in the variable file
      //call publishProgress() to run onProgressUpdate()

    }
  protected void onProgressUpdate(String... values)
  {
     //use the image in variable file to update the UI
  }
}


问:
Apache Camel deleting AWS S3 bucket's folder
I am testing a route which accesses a file from an AWS S3 bucket's sales folder. The problem I am facing is the moment all files are read from the folder, Camel deletes the folder. I understand that there is no notion of folder in S3. The file names' are prefixed with folder name.

How can I prevent the folder in S3 from getting deleted when all files are read and deleted.

Here is my route

from("aws-s3://departments?amazonS3Client=#s3Client&region=eu-west-1&prefix=sales")    .to("file:C:\temp?fileName=${header.CamelAwsS3Key}");

答:
Know your Camel version would really help, by the way to avoid the deletion of the file you're consuming you can use the deleteAfterRead option and set it to false.

https://github.com/apache/camel/blob/master/components/camel-aws/src/main/docs/aws-s3-component.adoc

In this way you should be able to avoid the deletion and at the same time, each time the consumer will poll you'll get the same set of file. Be aware of this last behavior.


问:
PyQT force update textEdit before calling other function
My question concerns PyQT5.
I try to have a dialog window with a button that when clicked

updates some text of a QTextEdit field

calls a function (which needs much time to terminate)

Something like this:

```<code>class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    run_lengthy_function(self)
</code>```

However, when I run my GUI I notice that the text is updated only after the lengthy function has terminated, although the QTextEdit.append is called before the lengthy function. How can I enforce that the text is updated in advance?

What I tried so far (but didn't work) was to let Python wait some time before triggering the lengthy function call, i.e.

```<code>from time import sleep

class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    sleep(5)
    run_lengthy_function(self)
</code>```

答:
The solution for the case that the text is displayed in the QTextEdit is to call qApp.processEvents(), this force to the GUI update:

```<code>def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    QtWidgets.qApp.processEvents()
    [...]
</code>```

On the other hand if the task is heavy it may be blocking the GUI, so maybe one solution is to run it on another thread, I can not give a proper recommendation since I do not know your function

Body:
My question concerns PyQT5.
I try to have a dialog window with a button that when clicked

updates some text of a QTextEdit field

calls a function (which needs much time to terminate)

Something like this:

class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    run_lengthy_function(self)

However, when I run my GUI I notice that the text is updated only after the lengthy function has terminated, although the QTextEdit.append is called before the lengthy function. How can I enforce that the text is updated in advance?

What I tried so far (but didn't work) was to let Python wait some time before triggering the lengthy function call, i.e.

from time import sleep

class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    sleep(5)
    run_lengthy_function(self)

Body:
The solution for the case that the text is displayed in the QTextEdit is to call qApp.processEvents(), this force to the GUI update:

def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    QtWidgets.qApp.processEvents()
    [...]

On the other hand if the task is heavy it may be blocking the GUI, so maybe one solution is to run it on another thread, I can not give a proper recommendation since I do not know your function


问:
How to append an array to an existing array in javascript
I need to make a query against different lists in Sharepoint and each one can get some results.

However I dont know how to append one result to the next, to the next, see trimmed data variable.

```<code>function GetData(billCycleId, clientCode, jobCodes, engagementCode) {
                    var enhanceFunctions = [
                        function(searchResultRow) {
                            return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
                        },
                        function(searchResultRow) {
                            return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
                        },
                        function(searchResultRow) {
                            return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
                        },
                        function(searchResultRow) {
                            return spService.AddImageMapping(searchResultRow, config.ImageFields);
                        },
                        function(searchResultRow) {
                            return spService.FormatNumberFields(searchResultRow, config.NumberFields);
                        }
                    ];

                    var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields);
                    var extendedSelectProperties = selectProperties.slice(); // copy array
                    var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
                    extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);

                    spService.GetAllListsFromWeb()
                        .then(function(lists){
                            var listEnumerator = lists.getEnumerator();
                            while (listEnumerator.moveNext()) {
                                var oList = listEnumerator.get_current();
                                var title = oList.get_title();
                                var id = oList.get_id();
                                if(title.indexOf("Bill Cycles")){
                                    // Get data from SP
                                    GetRelatedBillCyclesFromList(listid, extendedSelectProperties, billCycleId, clientCode, jobCodes, engagementCode, enhanceFunctions)
                                    .then(function (data) {
                                        var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectProperties);
                                        // Add data to dataTable

                                    })
                                    .catch (function (message) {
                                        vm.Name = "Error";
                                        vm.ValidDataLoaded = true;
                                    });
                                }
                                //Do something with oList.
                            }

                            var dataTable = $(tableSelector).DataTable();
                            dataTable.clear().rows.add(trimmedData).columns.adjust().draw(); // Resize columns based on new data sizes
                            vm.ValidDataLoaded = true;

                        })

                }

function getAllListsFromWeb(){
                        var deferred = $q.defer();
                        var context = SP.ClientContext.get_current();
                        var web = context.get_web();
                        var lists = web.get_lists();
                        context.load(lists);
                        context.executeQueryAsync(
                           function() {
                                $log.info("Successfully retrieved list item result");
                                deferred.resolve(lists);
                           },
                           function(error, errorInfo) {
                                $log.warn("Retrieving list item result failed");

                                deferred.reject(errorInfo);
                           }
                        );
                        return deferred.promise;
                    }
</code>```

Update 1:

I get the following error:
Cannot read property 'push' of undefined

Updated relevant code:

```<code>spService.GetAllListsFromWeb()
                        .then(function(lists){
                            var listEnumerator = lists.getEnumerator();
                            var result;
                            while (listEnumerator.moveNext()) {
                                var oList = listEnumerator.get_current();
                                var title = oList.get_title();
                                var id = oList.get_id();
                                if(title.indexOf("Bill Cycles") !== -1){
                                    // Get data from SP
                                    GetRelatedBillCyclesFromList(id, extendedSelectProperties, billCycleId, clientCode, jobCodes, engagementCode, enhanceFunctions)
                                    .then(function (data) {
                                        var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectProperties);
                                        // Add data to dataTable

                                        trimmedData.forEach(function(item){ // loop over source array
                                            result.push(item); //append to result array
                                        });
                                    })
                                    .catch (function (message) {
                                        vm.Name = "Error";
                                        vm.ValidDataLoaded = true;
                                    });
                                }
                                //Do something with oList.
                            }

                            var dataTable = $(tableSelector).DataTable();
                            dataTable.clear().rows.add(result).columns.adjust().draw(); // Resize columns based on new data sizes
                            vm.ValidDataLoaded = true;

                        })
</code>```

答:
You can just loop over your array and add each item to the array you want to append to.</p>

```<code>let result = [];
...

trimmedData.forEach(function(item){ // loop over source array
  result.push(item); //append to result array
});
...
</code>```

Body:
I need to make a query against different lists in Sharepoint and each one can get some results.

However I dont know how to append one result to the next, to the next, see trimmed data variable.

function GetData(billCycleId, clientCode, jobCodes, engagementCode) {
                    var enhanceFunctions = [
                        function(searchResultRow) {
                            return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
                        },
                        function(searchResultRow) {
                            return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
                        },
                        function(searchResultRow) {
                            return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
                        },
                        function(searchResultRow) {
                            return spService.AddImageMapping(searchResultRow, config.ImageFields);
                        },
                        function(searchResultRow) {
                            return spService.FormatNumberFields(searchResultRow, config.NumberFields);
                        }
                    ];

                    var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields);
                    var extendedSelectProperties = selectProperties.slice(); // copy array
                    var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
                    extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);

                    spService.GetAllListsFromWeb()
                        .then(function(lists){
                            var listEnumerator = lists.getEnumerator();
                            while (listEnumerator.moveNext()) {
                                var oList = listEnumerator.get_current();
                                var title = oList.get_title();
                                var id = oList.get_id();
                                if(title.indexOf("Bill Cycles")){
                                    // Get data from SP
                                    GetRelatedBillCyclesFromList(listid, extendedSelectProperties, billCycleId, clientCode, jobCodes, engagementCode, enhanceFunctions)
                                    .then(function (data) {
                                        var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectProperties);
                                        // Add data to dataTable

                                    })
                                    .catch (function (message) {
                                        vm.Name = "Error";
                                        vm.ValidDataLoaded = true;
                                    });
                                }
                                //Do something with oList.
                            }

                            var dataTable = $(tableSelector).DataTable();
                            dataTable.clear().rows.add(trimmedData).columns.adjust().draw(); // Resize columns based on new data sizes
                            vm.ValidDataLoaded = true;

                        })

                }

function getAllListsFromWeb(){
                        var deferred = $q.defer();
                        var context = SP.ClientContext.get_current();
                        var web = context.get_web();
                        var lists = web.get_lists();
                        context.load(lists);
                        context.executeQueryAsync(
                           function() {
                                $log.info("Successfully retrieved list item result");
                                deferred.resolve(lists);
                           },
                           function(error, errorInfo) {
                                $log.warn("Retrieving list item result failed");

                                deferred.reject(errorInfo);
                           }
                        );
                        return deferred.promise;
                    }

Update 1:

I get the following error:
Cannot read property 'push' of undefined

Updated relevant code:

spService.GetAllListsFromWeb()
                        .then(function(lists){
                            var listEnumerator = lists.getEnumerator();
                            var result;
                            while (listEnumerator.moveNext()) {
                                var oList = listEnumerator.get_current();
                                var title = oList.get_title();
                                var id = oList.get_id();
                                if(title.indexOf("Bill Cycles") !== -1){
                                    // Get data from SP
                                    GetRelatedBillCyclesFromList(id, extendedSelectProperties, billCycleId, clientCode, jobCodes, engagementCode, enhanceFunctions)
                                    .then(function (data) {
                                        var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectProperties);
                                        // Add data to dataTable

                                        trimmedData.forEach(function(item){ // loop over source array
                                            result.push(item); //append to result array
                                        });
                                    })
                                    .catch (function (message) {
                                        vm.Name = "Error";
                                        vm.ValidDataLoaded = true;
                                    });
                                }
                                //Do something with oList.
                            }

                            var dataTable = $(tableSelector).DataTable();
                            dataTable.clear().rows.add(result).columns.adjust().draw(); // Resize columns based on new data sizes
                            vm.ValidDataLoaded = true;

                        })

Body:
You can just loop over your array and add each item to the array you want to append to.

let result = [];
...

trimmedData.forEach(function(item){ // loop over source array
  result.push(item); //append to result array
});
...


问:
Memory leak in C++ seems to get worse after adding delete statements
Edit: Can someone explain why adding the delete operators do not change the Valgrind output? Please do not ask me to read C++ books, I have browsed through a couple and have not found the answers there.

I am new to C++, having come from the java world, I seem to have trouble understanding how to use new and delete operators.

I have a method (myMethod()) which initiates a class, MyClass. In MyClass there are a few arrays and few other objects being created using the new and new[] operators. Initially I did not have a destructor written for this class (I assumed that when the control returns to main from my method, these the MyClass object and everything related to it would be automatically "freed").

When I ran my program with Valgrind, this is the leak summary I got:

```<code>==9446== LEAK SUMMARY:
==9446==    definitely lost: 1,957,019 bytes in 38 blocks.
==9446==    indirectly lost: 4,171,184 bytes in 3,040 blocks.
==9446==      possibly lost: 0 bytes in 0 blocks.
==9446==    still reachable: 91,984 bytes in 991 blocks.
==9446==         suppressed: 0 bytes in 0 blocks.
==9446== Reachable blocks (those to which a pointer was found) are not shown.
==9446== To see them, rerun with: --show-reachable=yes
</code>```

So I added a destructor which deletes all the arrays and sets the objects to null. I do not explicitly call delete on the MyClass object. Now when I run my program using Valgrind, this is the leak summary I get.

```<code>LEAK SUMMARY:
==9223==    definitely lost: 1,957,019 bytes in 38 blocks.
==9223==    indirectly lost: 4,171,184 bytes in 3,040 blocks.
==9223==      possibly lost: 0 bytes in 0 blocks.
==9223==    still reachable: 91,984 bytes in 991 blocks.
==9223==         suppressed: 0 bytes in 0 blocks.
==9223== Reachable blocks (those to which a pointer was found) are not shown.
==9223== To see them, rerun with: --show-reachable=yes
</code>```

When I explicitly delete the MyClass object, the nubmer of bytes lost is more!

```<code>==9268== LEAK SUMMARY:
==9268==    definitely lost: 3,353,187 bytes in 1,253 blocks.
==9268==    indirectly lost: 28,376 bytes in 343 blocks.
==9268==      possibly lost: 0 bytes in 0 blocks.
==9268==    still reachable: 91,984 bytes in 991 blocks.
==9268==         suppressed: 0 bytes in 0 blocks.
==9268== Reachable blocks (those to which a pointer was found) are not shown.
==9268== To see them, rerun with: --show-reachable=yes
</code>```

I tried renaming the destructor to a method freeMemory() and then called freeMemory() before exitting from myMethod() and this is the leak summary. This is higher than either of them.

```<code>== LEAK SUMMARY:
==8998==    definitely lost: 5,271,299 bytes in 1,205 blocks.
==8998==    indirectly lost: 67,264 bytes in 410 blocks.
==8998==      possibly lost: 0 bytes in 0 blocks.
==8998==    still reachable: 91,984 bytes in 991 blocks.
==8998==         suppressed: 0 bytes in 0 blocks.
==8998== Reachable blocks (those to which a pointer was found) are not shown.
==8998== To see them, rerun with: --show-reachable=yes
</code>```

I guess my question is what is going on? Valgrind seems to indicate that the leak is in the constructor for MyClass and in a method in MyClass. Can someone explain to me how the new and delete operators work? I am not able to find a clear resource online, so if anyone can point me to such resource, that would be great too!

答:
Without seeing the code it is not possible to tell you exactly what to do to fix your leaks.

Note, though, that when you added destructors you reduced the amount of memory leaked it's just that much of that memory has moved from "indirectly lost" to "definitely lost" which means that your destructors are not cleaning up everything.

In most application code, though, you should rarely have to use new and almost never new[], delete or delete[]. Typically containers (such as std::vector) and smart pointers (such as shared_ptr) can be used to remove all error prone manual memory management from an application.

Body:
Edit: Can someone explain why adding the delete operators do not change the Valgrind output? Please do not ask me to read C++ books, I have browsed through a couple and have not found the answers there.

I am new to C++, having come from the java world, I seem to have trouble understanding how to use new and delete operators.

I have a method (myMethod()) which initiates a class, MyClass. In MyClass there are a few arrays and few other objects being created using the new and new[] operators. Initially I did not have a destructor written for this class (I assumed that when the control returns to main from my method, these the MyClass object and everything related to it would be automatically "freed").

When I ran my program with Valgrind, this is the leak summary I got:

==9446== LEAK SUMMARY:
==9446==    definitely lost: 1,957,019 bytes in 38 blocks.
==9446==    indirectly lost: 4,171,184 bytes in 3,040 blocks.
==9446==      possibly lost: 0 bytes in 0 blocks.
==9446==    still reachable: 91,984 bytes in 991 blocks.
==9446==         suppressed: 0 bytes in 0 blocks.
==9446== Reachable blocks (those to which a pointer was found) are not shown.
==9446== To see them, rerun with: --show-reachable=yes

So I added a destructor which deletes all the arrays and sets the objects to null. I do not explicitly call delete on the MyClass object. Now when I run my program using Valgrind, this is the leak summary I get.

LEAK SUMMARY:
==9223==    definitely lost: 1,957,019 bytes in 38 blocks.
==9223==    indirectly lost: 4,171,184 bytes in 3,040 blocks.
==9223==      possibly lost: 0 bytes in 0 blocks.
==9223==    still reachable: 91,984 bytes in 991 blocks.
==9223==         suppressed: 0 bytes in 0 blocks.
==9223== Reachable blocks (those to which a pointer was found) are not shown.
==9223== To see them, rerun with: --show-reachable=yes

When I explicitly delete the MyClass object, the nubmer of bytes lost is more!

==9268== LEAK SUMMARY:
==9268==    definitely lost: 3,353,187 bytes in 1,253 blocks.
==9268==    indirectly lost: 28,376 bytes in 343 blocks.
==9268==      possibly lost: 0 bytes in 0 blocks.
==9268==    still reachable: 91,984 bytes in 991 blocks.
==9268==         suppressed: 0 bytes in 0 blocks.
==9268== Reachable blocks (those to which a pointer was found) are not shown.
==9268== To see them, rerun with: --show-reachable=yes

I tried renaming the destructor to a method freeMemory() and then called freeMemory() before exitting from myMethod() and this is the leak summary. This is higher than either of them.

== LEAK SUMMARY:
==8998==    definitely lost: 5,271,299 bytes in 1,205 blocks.
==8998==    indirectly lost: 67,264 bytes in 410 blocks.
==8998==      possibly lost: 0 bytes in 0 blocks.
==8998==    still reachable: 91,984 bytes in 991 blocks.
==8998==         suppressed: 0 bytes in 0 blocks.
==8998== Reachable blocks (those to which a pointer was found) are not shown.
==8998== To see them, rerun with: --show-reachable=yes

I guess my question is what is going on? Valgrind seems to indicate that the leak is in the constructor for MyClass and in a method in MyClass. Can someone explain to me how the new and delete operators work? I am not able to find a clear resource online, so if anyone can point me to such resource, that would be great too!

ContentLicense: CC BY-SA 2.5


问:
Listen to promise as a stream
I have been reading about Observables. One thing I read about, is its ability to listen like a stream. I tried this using the following code.

```<code>const Rx = require('rxjs/Rx');
Promise = require('bluebird');

let i = 0;

function calculate() {
    return new Promise((resolve, reject) => {
        setInterval(() => {
            console.log(++i);
            resolve(i);
        }, 5000);
    })
}

let source = Rx.Observable.fromPromise(calculate());

source.subscribe(
    next => {
        console.log(next, ' next ');
    },
    err => {
        console.error(err)
    },
    () => {
        console.log('done!');
    }
)
</code>```

But it didn't work like a stream. So the output looks something like:

```<code>1
1 ' next '
done!
2
3
</code>```

How do I continue listening to the promise? Is this one of the problem Observable really solve?

答:
You can use switchMap and interval:

```<code>let i = 0;

function calculate() {
    return Promise.resolve(++i)
}
//I reduce to the strictly necessary for the answer, the promise's resolve.
//It's possible to have more things

let source = Rx.Observable
    .interval(1000)
    .switchMap(() => calculate())

source.subscribe(
    next => {
        console.log(next, ' next ');
    },
    err => {
        console.error(err)
    },
    () => {
        console.log('done!');
    }
)
</code>```

You can see the documentation of switchMap and interval here:

https://www.learnrxjs.io/operators/creation/interval.html

https://www.learnrxjs.io/operators/transformation/switchmap.html

And the demo: https://jsbin.com/nutukiyagi/1/edit?js,console

In this case, you never complete the stream, the console.log('done!') never appears in the console

Title: Listen to promise as a stream

Body:
I have been reading about Observables. One thing I read about, is its ability to listen like a stream. I tried this using the following code.

const Rx = require('rxjs/Rx');
Promise = require('bluebird');

let i = 0;

function calculate() {
    return new Promise((resolve, reject) => {
        setInterval(() => {
            console.log(++i);
            resolve(i);
        }, 5000);
    })
}

let source = Rx.Observable.fromPromise(calculate());

source.subscribe(
    next => {
        console.log(next, ' next ');
    },
    err => {
        console.error(err)
    },
    () => {
        console.log('done!');
    }
)

But it didn't work like a stream. So the output looks something like:

1
1 ' next '
done!
2
3

How do I continue listening to the promise? Is this one of the problem Observable really solve?

Body:
You can use switchMap and interval:

let i = 0;

function calculate() {
    return Promise.resolve(++i)
}
//I reduce to the strictly necessary for the answer, the promise's resolve.
//It's possible to have more things

let source = Rx.Observable
    .interval(1000)
    .switchMap(() => calculate())

source.subscribe(
    next => {
        console.log(next, ' next ');
    },
    err => {
        console.error(err)
    },
    () => {
        console.log('done!');
    }
)

You can see the documentation of switchMap and interval here:

https://www.learnrxjs.io/operators/creation/interval.html

https://www.learnrxjs.io/operators/transformation/switchmap.html

And the demo: https://jsbin.com/nutukiyagi/1/edit?js,console

In this case, you never complete the stream, the console.log('done!') never appears in the console


问:
How Arrays.toString() works for Object Arrays
```<code>// Java program to demonstrate working of Arrays.toString()
// for user defined objects.
import java.lang.*;
import java.util.*;

// Driver class
class Main
{
    public static void main (String[] args)
    {
        Student [] arr = {new Student(111, "bbbb", "london"),
                          new Student(131, "aaaa", "nyc"),
                          new Student(121, "cccc", "jaipur")};

        System.out.println(Arrays.toString(arr));
    }
}

// A class to represent a student.
class Student
{
    int rollno;
    String name, address;

    // Constructor
    public Student(int rollno, String name,
                               String address)
    {
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }

    // Used to print student details in main()
    public String toString()
    {
        return this.rollno + " " + this.name +
                           " " + this.address;
    }
}
</code>```

Output of the above code is:
[111 bbbb london, 131 aaaa nyc, 121 cccc jaipur]

My question is what actually happens in the line:
System.out.println(Arrays.toString(arr));?

Does Arrays.toString(arr) call toString method of each Student Object or something like that?

答:
Does Arrays.toString(arr) call toString method of each Student Object or something like that?

Yes, you are right. Every object inherits from the Object which has toString() method and Arrays.toString() calls it for each of the object. However in most of cases it returns the object reference string by default. See the documentation:

If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object

The idea is to @Override this method and customize the output.

Body:
// Java program to demonstrate working of Arrays.toString()
// for user defined objects.
import java.lang.*;
import java.util.*;

// Driver class
class Main
{
    public static void main (String[] args)
    {
        Student [] arr = {new Student(111, "bbbb", "london"),
                          new Student(131, "aaaa", "nyc"),
                          new Student(121, "cccc", "jaipur")};

        System.out.println(Arrays.toString(arr));
    }
}

// A class to represent a student.
class Student
{
    int rollno;
    String name, address;

    // Constructor
    public Student(int rollno, String name,
                               String address)
    {
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }

    // Used to print student details in main()
    public String toString()
    {
        return this.rollno + " " + this.name +
                           " " + this.address;
    }
}

Output of the above code is:
[111 bbbb london, 131 aaaa nyc, 121 cccc jaipur]

My question is what actually happens in the line:
System.out.println(Arrays.toString(arr));?

Does Arrays.toString(arr) call toString method of each Student Object or something like that?


问:
Delphi Streaming Problem
I'm using a blob field in a kbmMemTable to store a custom component that I've developed from TComponent and I use the read and write component stream methods of the TReader to read and write the component to the blob field. The data in the kbmMemTable is eventually stored inside a structured storage file created by GpStructuredStorage.

This has worked flawlessly, until I moved my component (along with the kbmMemtable) to a new application and tried to have the new application read the blob field. At first I was getting a component naming error (component name already exists), but later I started getting an Access Violation when the TReader tries to read a TPersistent property of my component.

As far as I know, I did not change anything with regards to the way I retrive the kbmMemTable data from the gpStructuredStorage file and the way I read the component back from the blob field using TReader. I've made no changes to the component and, I don't seem to have any problem with other components that I'm storing in other blob fields in the same table (at least I'm not getting any errors when they are read back).

I'm miffed at what could be the problem. Any help / suggestion would be greatly appreciated. I am using Delphi 2007.

答: I finally figured out what caused the streaming problem - although I am not sure why so perhaps someone can throw a light on this issue. I decided to check if the problem could be caused by some of the new 3rd party components I was using and lo and behold, when I disabled a skinning component (which was going to be an improvement in my new app!), everything worked as it should have. By disabling I mean I did not remove it from the program, I just made it so that the compressed skins were no longer used to paint the windows and the controls. </p>

Title: Delphi Streaming Problem


问:
How to delete particular data from core data attribute (column) in swift 3
I am doing core data in Swift 3. I am able to store data and able to fetch, working fine. But, while trying to delete particular data suppose string data, its not able to do.

Following is my code

```<code>        //Delete if existing data there
        let context = DatabaseController.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UserData")
        fetchRequest.predicate = NSPredicate.init(format: "userFocusData==\(node.label.text!)")

        let result = try? context.fetch(fetchRequest)
        let resultData = result as! [UserData]

        for object in resultData {
            context.delete(object)
        }

        do {
            try context.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
            self.showAlert(message: "Data not able to save, please try again later.", title: kText_AppName)
        } catch {

        }
</code>```

And its getting crash at following line

```<code>        let result = try? context.fetch(fetchRequest)
</code>```

And crash report is

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath Sharepoint not found in entity <NSSQLEntity UserData id=6>'
</code>```

But, I am passing some string, that string I want to delete from database.
Can anyone suggest me, how to fix this, I have not used core data well.

答:
In Swift 3

In this Code i am delete data based on id

```<code>func deleteTrip(Id:String)
    {
        managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"your entity")
        fetchRequest.predicate = NSPredicate(format: "id = %@", "\(Id)")
        do
        {
            let fetchedResults =  try managedContext!.fetch(fetchRequest) as? [NSManagedObject]

            for entity in fetchedResults! {

                managedContext?.delete(entity)
                do
                {
                    try managedContext.save()

                }

                catch let error as Error!
                {
                    print(error.localizedDescription)
                }

            }
        }
        catch _ {
            print("Could not delete")

        }
    }
</code>```

Body:
I am doing core data in Swift 3. I am able to store data and able to fetch, working fine. But, while trying to delete particular data suppose string data, its not able to do.

Following is my code

        //Delete if existing data there
        let context = DatabaseController.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UserData")
        fetchRequest.predicate = NSPredicate.init(format: "userFocusData==\(node.label.text!)")

        let result = try? context.fetch(fetchRequest)
        let resultData = result as! [UserData]

        for object in resultData {
            context.delete(object)
        }

        do {
            try context.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
            self.showAlert(message: "Data not able to save, please try again later.", title: kText_AppName)
        } catch {

        }

And its getting crash at following line

        let result = try? context.fetch(fetchRequest)

And crash report is

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath Sharepoint not found in entity <NSSQLEntity UserData id=6>'

But, I am passing some string, that string I want to delete from database.
Can anyone suggest me, how to fix this, I have not used core data well.

Body:
In Swift 3

In this Code i am delete data based on id

func deleteTrip(Id:String)
    {
        managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"your entity")
        fetchRequest.predicate = NSPredicate(format: "id = %@", "\(Id)")
        do
        {
            let fetchedResults =  try managedContext!.fetch(fetchRequest) as? [NSManagedObject]

            for entity in fetchedResults! {

                managedContext?.delete(entity)
                do
                {
                    try managedContext.save()

                }

                catch let error as Error!
                {
                    print(error.localizedDescription)
                }

            }
        }
        catch _ {
            print("Could not delete")

        }
    }


问:
How do make new website using MEAN stack application in Windows 10 home?
Some more days ago I installed MEAN stack application on my system, but I haven't any idea for MEAN stack application. How do make a new website using this MEAN stack application in Windows 10?</p>

答: First thing I would do is watch some tutorial videos on how to make an AngularJS website on youtube and follow along with what they do. This will give you a basic understanding of how a AngularJS website works. Then I would probably suggest googling for an open source meanJS site. I would probably use something like https://github.com/cornflourblue/mean-stack-registration-login-example set it up on my own server and play around with it. Learn what everything does and how it does it. Then as you deconstruct the site and learn, start to work on your own.</p>


问:
header not being set in storage promise
I am trying to add a header to my api call however, i need to get auth token and set that to the header. But when i try and run the bellow code it doesn't set it, only sets the Content-Type.

```<code>import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
  providers: [HttpClient]
})
export class DataProvider {
  public token:string;

constructor(public http: HttpClient, public storage: Storage) {}

getsomething(){

 let headers = new HttpHeaders();
 headers = headers.set('Content-Type', 'application/json');
 this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
   headers = headers.set('AuthToken', this.token);
 });

 console.log(headers);

 return this.http.get('http://localhost:54951/getfarms', {
   headers: headers
 });
</code>```

}

答:
You can't use the value you set in this.storage.get('token').then right after the call to then. The promise will not execute the handler immediately, since it is an async operation.

```<code>getsomething() {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    return this.storage.get('token').then((val) => {
        this.token = val;
        console.log(this.token);
        headers = headers.set('AuthToken', this.token);

        console.log(headers);

        return this.http.get('http://localhost:54951/getfarms', {
            headers: headers
        });
    });
}
</code>```

Or using async/await

```<code>async getsomethingAsync() {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    let val = await this.storage.get('token')
    this.token = val;
    console.log(this.token);
    headers = headers.set('AuthToken', this.token);

    console.log(headers);

    return this.http.get('http://localhost:54951/getfarms', {
        headers: headers
    });
}
</code>```

Title: header not being set in storage promise

Body:
I am trying to add a header to my api call however, i need to get auth token and set that to the header. But when i try and run the bellow code it doesn't set it, only sets the Content-Type.

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
  providers: [HttpClient]
})
export class DataProvider {
  public token:string;

constructor(public http: HttpClient, public storage: Storage) {}

getsomething(){

 let headers = new HttpHeaders();
 headers = headers.set('Content-Type', 'application/json');
 this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
   headers = headers.set('AuthToken', this.token);
 });

 console.log(headers);

 return this.http.get('http://localhost:54951/getfarms', {
   headers: headers
 });

}

Body:
You can't use the value you set in this.storage.get('token').then right after the call to then. The promise will not execute the handler immediately, since it is an async operation.

getsomething() {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    return this.storage.get('token').then((val) => {
        this.token = val;
        console.log(this.token);
        headers = headers.set('AuthToken', this.token);

        console.log(headers);

        return this.http.get('http://localhost:54951/getfarms', {
            headers: headers
        });
    });
}

Or using async/await

async getsomethingAsync() {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    let val = await this.storage.get('token')
    this.token = val;
    console.log(this.token);
    headers = headers.set('AuthToken', this.token);

    console.log(headers);

    return this.http.get('http://localhost:54951/getfarms', {
        headers: headers
    });
}


问:
Could not load file or assembly System.Reflection.TypeExtensions
I got below exception while running xunit test projects which works under VS 2017 15.3

[2017/12/4 23:08:40 Error] [xUnit.net 00:00:00.0033291] xxx.Test: Catastrophic failure: System.TypeInitializationException: The type initializer for 'Xunit.DiaSession' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Reflection.TypeExtensions, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
     at Xunit.DiaSession..cctor()
     --- End of inner exception stack trace ---
     at Xunit.DiaSession..ctor(String assemblyFileName)
     at Xunit.DiaSessionWrapper..ctor(String assemblyFilename)
     at Xunit.XunitFrontController..ctor(AppDomainSupport appDomainSupport, String assemblyFileName, String configFileName, Boolean shadowCopy, String shadowCopyFolder, ISourceInformationProvider sourceInformationProvider, IMessageSink diagnosticMessageSink)
     at Xunit.Runner.VisualStudio.TestAdapter.VsTestRunner.RunTestsInAssembly(IRunContext runContext, IFrameworkHandle frameworkHandle, LoggerHelper logger, IMessageSinkWithTypes reporterMessageHandler, AssemblyRunInfo runInfo)
  My current VS 2017 version is 15.4.5.

I have tried the work around which has been provided previously, but none did not work. And I have try to downgrade my VS 2016 to 15.3, but I could not find the 15.3 package to install. I have tried to install xunit to latest version.
Any help would be appreciated.

Update:

Project Type:xUnit Test Project(.NET Core)

Target: net 461

答:
It seems VS 2017 fail to load specific "xunit.runner.visualstudio", after checking VS2017 15.4.2 - Unable to run tests for projects targeting .NET Framework 4.6.x #1542 again, I deleted the "%TEMP%\VisualStudioTestExplorerExtensions", create a new Xunit project, change the nonworked.csproj xunit.runner.visualstudio from 2.2.0 to 2.3.1, it works now. Not sure why it did not work when I try it previous.

Hope it will help others.


问:
What AWS Service should I use?
We are currently runs in-house hardware that we would like to potentially move to AWS. Our main application uses MySQL on a Linux machine (200GB Disk, 32GB RAM, 4 Cores) serving content to customers through a hardware load balancer (around 1 million unique users per month).
We also use a 500 GB CDN hosted by a third party that we would like to move to AWS potentially. What AWS services would you recommend we look at to achieve comparable functionality and would you have a rough monthly cost estimate?
The main reason we would like to move to AWS would be for cost reduction in hardware and better backup strategies.

Thanks!

答:
Comparable functionality would be to use AWS RDS to replace your MySQL database, one or more EC2 instances to run your application, and then AWS Load Balancer to distribute the load amongst those EC2 web instances. A combination of S3 and Cloudfront to use as a CDN.

Cost is going to depend on how many ec2 instances you use, and the size and options you use for RDS database(s) plus storage and bandwidth - impossible for me to estimate for you

But you can do your own estimates here: https://awstcocalculator.com/

Title: What AWS Service should I use?


问:
Hybris Solr - how to exclude certain facet values when creating SearchQueryData
I am searching in Hybris using Solr. There are certain facet values for category that I want to exclude from that specific(those categories need to be visible to other searches) search. My Solr query is as following:

```<code>q=*:*&spellcheck=true&spellcheck.dictionary=en&spellcheck.collate=true&spellcheck.q=&fq={!tag=fk6}(type\-facet_string:ANSI)&fq=(((catalogId:"ProductCatalog") AND (catalogVersion:Online)))&start=0&rows=100&facet=true&facet.field=allCategories_string_mv&facet.field={!ex=fk0}productLine_string_mv&facet.field={!ex=fk8}style-facet_string&facet.field={!ex=fk5}price_usd_string&facet.field={!ex=fk4}allPromotions_string_mv&facet.field={!ex=fk6}type-facet_string&facet.field={!ex=fk1}size-facet_string&facet.field=categoryPath_string_mv&facet.field={!ex=fk9}availableInStores_string_mv&facet.field=category_string_mv&sort=name_sortable_en_sortabletext asc,score desc&facet.mincount=1&facet.limit=-1&facet.sort=count
</code>```

I don't have the ability to use raw query. All I can use is Hybris native SearchStateData and SearchQueryData. Category facet can be included in the search but I need to exclude from it i.e CategoryA and CategoryB. Right now my code just sets the value in SearchQueryData as a String in a following way:

```<code>":type-facet:" + type; or ":category:" + category
</code>```

I have tried :category:(-\"CategoryA\"); but it does not end up in the final Solr query. Can anyone point me in the right direction?

答:
Refer SearchResponseFacetsPopulator and you can override its method by creating custom populator

MySearchResponseFacetsPopulator :

```<code>public class MySearchResponseFacetsPopulator<FACET_SEARCH_CONFIG_TYPE, INDEXED_TYPE_TYPE, INDEXED_PROPERTY_TYPE, INDEXED_TYPE_SORT_TYPE, ITEM>
        extends
        SearchResponseFacetsPopulator<FACET_SEARCH_CONFIG_TYPE, INDEXED_TYPE_TYPE, INDEXED_PROPERTY_TYPE, INDEXED_TYPE_SORT_TYPE, ITEM>
{

    @Override
    public void populate(
            final SolrSearchResponse<FACET_SEARCH_CONFIG_TYPE, INDEXED_TYPE_TYPE, INDEXED_PROPERTY_TYPE, SearchQuery, INDEXED_TYPE_SORT_TYPE, SearchResult> source,
            final FacetSearchPageData<SolrSearchQueryData, ITEM> target)
    {
        super.populate(source, target);
    }

    @Override
    protected List<FacetData<SolrSearchQueryData>> buildFacets(final SearchResult solrSearchResult,
            final SolrSearchQueryData searchQueryData, final IndexedType indexedType)
    {
       // Do your stuff here
    }
}
</code>```

xml :

```<code><alias name="defaultMyCommerceSearchResponseFacetsPopulator" alias="commerceSearchResponseFacetsPopulator" />
        <bean id="defaultMyCommerceSearchResponseFacetsPopulator"   class="com.my.facades.populators.MySearchResponseFacetsPopulator"
            parent="defaultCommerceSearchResponseFacetsPopulator" />
</code>```

Body:
I am searching in Hybris using Solr. There are certain facet values for category that I want to exclude from that specific(those categories need to be visible to other searches) search. My Solr query is as following:

q=*:*&spellcheck=true&spellcheck.dictionary=en&spellcheck.collate=true&spellcheck.q=&fq={!tag=fk6}(type\-facet_string:ANSI)&fq=(((catalogId:"ProductCatalog") AND (catalogVersion:Online)))&start=0&rows=100&facet=true&facet.field=allCategories_string_mv&facet.field={!ex=fk0}productLine_string_mv&facet.field={!ex=fk8}style-facet_string&facet.field={!ex=fk5}price_usd_string&facet.field={!ex=fk4}allPromotions_string_mv&facet.field={!ex=fk6}type-facet_string&facet.field={!ex=fk1}size-facet_string&facet.field=categoryPath_string_mv&facet.field={!ex=fk9}availableInStores_string_mv&facet.field=category_string_mv&sort=name_sortable_en_sortabletext asc,score desc&facet.mincount=1&facet.limit=-1&facet.sort=count

I don't have the ability to use raw query. All I can use is Hybris native SearchStateData and SearchQueryData. Category facet can be included in the search but I need to exclude from it i.e CategoryA and CategoryB. Right now my code just sets the value in SearchQueryData as a String in a following way:

":type-facet:" + type; or ":category:" + category

I have tried :category:(-\"CategoryA\"); but it does not end up in the final Solr query. Can anyone point me in the right direction?

Body:
Refer SearchResponseFacetsPopulator and you can override its method by creating custom populator

MySearchResponseFacetsPopulator :

public class MySearchResponseFacetsPopulator<FACET_SEARCH_CONFIG_TYPE, INDEXED_TYPE_TYPE, INDEXED_PROPERTY_TYPE, INDEXED_TYPE_SORT_TYPE, ITEM>
        extends
        SearchResponseFacetsPopulator<FACET_SEARCH_CONFIG_TYPE, INDEXED_TYPE_TYPE, INDEXED_PROPERTY_TYPE, INDEXED_TYPE_SORT_TYPE, ITEM>
{

    @Override
    public void populate(
            final SolrSearchResponse<FACET_SEARCH_CONFIG_TYPE, INDEXED_TYPE_TYPE, INDEXED_PROPERTY_TYPE, SearchQuery, INDEXED_TYPE_SORT_TYPE, SearchResult> source,
            final FacetSearchPageData<SolrSearchQueryData, ITEM> target)
    {
        super.populate(source, target);
    }

    @Override
    protected List<FacetData<SolrSearchQueryData>> buildFacets(final SearchResult solrSearchResult,
            final SolrSearchQueryData searchQueryData, final IndexedType indexedType)
    {
       // Do your stuff here
    }
}

xml :

<alias name="defaultMyCommerceSearchResponseFacetsPopulator" alias="commerceSearchResponseFacetsPopulator" />
        <bean id="defaultMyCommerceSearchResponseFacetsPopulator"   class="com.my.facades.populators.MySearchResponseFacetsPopulator"
            parent="defaultCommerceSearchResponseFacetsPopulator" />


问:
Java Card: Problems selecting app with APDUtool
I'm using Eclipse with EclipseJCDE.

I made a simple java card applet as a .cap file to install on the simulator. I don't know if the installation failed because the download script is a bunch of ADPU commands which I don't understand. Is there any way to see what applets are currently on the simulator and what their AIDs are?

I then made a script for ADPUtool with just one command, selecting the applet. According to the .jca file in my project.

The AID for my applet:

0x1:0x2:0x3:0x4:0x5:0x6:0x7:0x8:0x9:0x0:0x0.

The command I made for selecting the applet:

0x00 0xA4 0x04 0x00 0x0b 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0x0 0x0

The 0x00 0xA4 0x04 0x00 at the beginning is for the select command, then 0x0b for the length, than the AID, and then 0x0 at the end for the Le byte which I don't think matters for this command. When I run this script with the ADPU tool I get this:

CLA: 00

INS: a4

P1: 04

P2: 00

Lc: 0b 01 02 03 04 05 06 07 08 09 00 00

Le: 00

SW1: 6d

SW2: 00

I believe the SW1 and SW2 bytes are the response to my command and I think 6d means it didn't find or wasn't able to load the applet. What am I doing wrong?

答:
6D00 means bad instruction (INS byte 'A4' not existing in class '00').

Post full trace of APDUs after ATR else I recommend you to check section 10 from http://www.etsi.eu/deliver/etsi_ts/102200_102299/102221/08.02.00_60/ts_102221v080200p.pdf, for example.


问:
Codingbat problems -- String
I came across a question on codingbat and the question is: </p>

<p>Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.
I solved the problem and the solution (below) is a better than mine, however, there is a problem with the solution code, when the string length is less than 2, say the length is only 1. str index will be -1. will the code still work? why does the site say the solution is correct? </p>

```<code> public String extraEnd(String str) {
      String end = str.substring(str.length()-2);
      return end + end + end;
</code>```

答:
The website will try to give you as many tests as possible to make sure it's mostly free of bugs, however some do slip through the crack and make exceptions. The code below is one that works through all tests given if you want to give it a go;

```<code>public String extraFront(String str) {
    if (str.length() <= 2)
    return str+str+str;
return str.substring(0,2)+str.substring(0,2)+str.substring(0,2);
}
</code>```

It seems that you're correct with the code, the index would be -1. Maybe follow it up with the challenge on String 2, it'll come in handy. Wish you best of luck!

Title: Codingbat problems -- String

Body:
I came across a question on codingbat and the question is:

Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.
I solved the problem and the solution (below) is a better than mine, however, there is a problem with the solution code, when the string length is less than 2, say the length is only 1. str index will be -1. will the code still work? why does the site say the solution is correct?

 public String extraEnd(String str) {
      String end = str.substring(str.length()-2);
      return end + end + end;

Body:
The website will try to give you as many tests as possible to make sure it's mostly free of bugs, however some do slip through the crack and make exceptions. The code below is one that works through all tests given if you want to give it a go;

public String extraFront(String str) {
    if (str.length() <= 2)
    return str+str+str;
return str.substring(0,2)+str.substring(0,2)+str.substring(0,2);
}

It seems that you're correct with the code, the index would be -1. Maybe follow it up with the challenge on String 2, it'll come in handy. Wish you best of luck!


问:
How to return all movies with the same crew in neo4j?
As I am new to neo4j, I am currently experimenting with the neo4j movie database sample.

I was wondering what the best way was to compare subgraphs and relationships, for example, how to get all movies with identical crew.

Based on other questions here on stackoverflow, I got it to work to return all movies where specific actors acted in together:

```<code>WITH ['Tom Hanks', 'Meg Ryan'] as names
MATCH (p:Person)
WHERE p.name in names
WITH collect(p) as persons
WITH head(persons) as head, tail(persons) as persons
MATCH (head)-[:ACTED_IN]->(m:Movie)
WHERE ALL(p in persons WHERE (p)-[:ACTED_IN]->(m))
RETURN m.title
</code>```

But, how could I retrieve movies with identical actors without specifying the actors names?

答:
This query should work:

```<code>// match the first movie and all its actors
match (m1:Movie)<-[:ACTED_IN]-(a1:Person)
// order actors by name
with m1, a1 order by a1.name
// store ordered actors into actors1 variable
with m1, collect(a1) as actors1
// match the second movie and all its actors
match (m2:Movie)<-[:ACTED_IN]-(a2:Person)
// avoid match the same movie with where id(m1) > id(m2)
where id(m1) > id(m2)
// order actors of m2 by name
with m1, m2, actors1, a2 order by a2.name
// store ordered actors of m2 into actors2 variable
// pass to the next context only when the ordered arrays (actors1 and actors2) are equals
with m1, m2, actors1, collect(a2) actors2 where actors1 = actors2
// return movies that have the same actors
return m1, m2
</code>```

Using the movie database (:play movie graph) this query produced this output:

```<code>╒══════════════════════════════════════════════════════════════════════╤══════════════════════════════════════════════════════════════════════╕
│"m1"                                                                  │"m2"                                                                  │
╞══════════════════════════════════════════════════════════════════════╪══════════════════════════════════════════════════════════════════════╡
│{"title":"The Matrix Revolutions","tagline":"Everything that has a beg│{"title":"The Matrix Reloaded","tagline":"Free your mind","released":2│
│inning has an end","released":2003}                                   │003}                                                                  │
└──────────────────────────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────────────┘
</code>```

Body:
As I am new to neo4j, I am currently experimenting with the neo4j movie database sample.

I was wondering what the best way was to compare subgraphs and relationships, for example, how to get all movies with identical crew.

Based on other questions here on stackoverflow, I got it to work to return all movies where specific actors acted in together:

WITH ['Tom Hanks', 'Meg Ryan'] as names
MATCH (p:Person)
WHERE p.name in names
WITH collect(p) as persons
WITH head(persons) as head, tail(persons) as persons
MATCH (head)-[:ACTED_IN]->(m:Movie)
WHERE ALL(p in persons WHERE (p)-[:ACTED_IN]->(m))
RETURN m.title

But, how could I retrieve movies with identical actors without specifying the actors names?

Body:
This query should work:

// match the first movie and all its actors
match (m1:Movie)<-[:ACTED_IN]-(a1:Person)
// order actors by name
with m1, a1 order by a1.name
// store ordered actors into actors1 variable
with m1, collect(a1) as actors1
// match the second movie and all its actors
match (m2:Movie)<-[:ACTED_IN]-(a2:Person)
// avoid match the same movie with where id(m1) > id(m2)
where id(m1) > id(m2)
// order actors of m2 by name
with m1, m2, actors1, a2 order by a2.name
// store ordered actors of m2 into actors2 variable
// pass to the next context only when the ordered arrays (actors1 and actors2) are equals
with m1, m2, actors1, collect(a2) actors2 where actors1 = actors2
// return movies that have the same actors
return m1, m2

Using the movie database (:play movie graph) this query produced this output:

╒══════════════════════════════════════════════════════════════════════╤══════════════════════════════════════════════════════════════════════╕
│"m1"                                                                  │"m2"                                                                  │
╞══════════════════════════════════════════════════════════════════════╪══════════════════════════════════════════════════════════════════════╡
│{"title":"The Matrix Revolutions","tagline":"Everything that has a beg│{"title":"The Matrix Reloaded","tagline":"Free your mind","released":2│
│inning has an end","released":2003}                                   │003}                                                                  │
└──────────────────────────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────────────┘


问:
Representing a phrase as a block of code
How can I represent the concept “I have 99 issues but a bug ain’t one” using some fancy code?

Background

I picked the lead dev for Secret Santa. I’d like to get him a tshirt with the above on it expressed as a block of code / fuction / query string.
We were all in a meeting one day discussing Jira issues and he said “I have 99 issues” and I shouted out “but a bug ain’t one” and everyone had a good laugh.
So I’d like to put that on a tshirt for him as it think it would be a fun present.
He is a really awesome guy, super smart, always has time to explain something to us non tech folk, a real heat of gold.
Can you help me?

If it could have something to do with .net/SQL/Bash that would be great.

Thanks

答:
Very goofy question but I'll shoot xD.

Javascript Classical

```<code>class Me{
  issues: 99,
  bug: 0,
}
</code>```

JavaScript Functional

```<code>function status() {
  if (I.problems === 99 && I.bugs !== 1) {
    console.log('hit it');
  }
}
</code>```

SQL

```<code>SELECT * FROM I
WHERE issues=99 AND bugs<>1;
</code>```

Body:
Very goofy question but I'll shoot xD.

Javascript Classical

class Me{
  issues: 99,
  bug: 0,
}

JavaScript Functional

function status() {
  if (I.problems === 99 && I.bugs !== 1) {
    console.log('hit it');
  }
}

SQL

SELECT * FROM I
WHERE issues=99 AND bugs<>1;


问:
Can not put single artist in more than one figure
Here is my issue.

I create a function that plot a list of circles.
I need to plot my circle C1 first with a circle C2 then with C3.... until C40.

```<code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle

def plot_circle(Liste_circles):

    fig = plt.figure(figsize=(5,5))
    ax = fig.add_subplot(111)

    # On définie un fond blanc
    ax.set_facecolor((1, 1, 1))

    ax.set_xlim(-5, 15)
    ax.set_ylim(-6, 12)

    for c in Liste_circles:
        ax.add_patch(c)

    plt.show()
</code>```

Now I create C1:

```<code>C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
</code>```

An finally I try to plot it.

The first plot worked:

```<code>C2=Circle(xy=(6, 3), radius=4, fill=False, color='b')
plot_circle([C1,C2])
</code>```

The second one failed:

```<code>C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])
</code>```

with the error:

RuntimeError: Can not put single artist in more than one figure

I can make it worked by doing:

```<code>C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])
</code>```

How can I do to plot my circle C1 with 40 other circles without having to recreate C1 each time? (My program took 10min to create C1 throught a complicated algorithme, I cannot recreate it at each of the 40 plot....).

答:
Moreover if you are interested you can set the x and y axes regarding the values of the circles:</p>

```<code>import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from copy import copy

def plot_circles (Liste_circles):

    if len(Liste_circles) == 0:
        print('No circles to display')
    else:

        fig = plt.figure(figsize=(5,5))
        ax = fig.add_subplot(111)

        # On définie un fond blanc
        ax.set_facecolor((1, 1, 1))

        # On définie les limites des axes pour que nos cercles soient au centre de notre graphique
        # --> xmin sera le plus petit des x de tous les cercles - 2 fois le plus grand des rayons
        # --> xmax sera le plus grand des x de tous les cercles + 2 fois le plus grand des rayons
        # --> ymin sera le plus petit des y de tous les cercles - 2 fois le plus grand des rayons
        # --> ymax sera le plus grand des y de tous les cercles + 2 fois le plus grand des rayons
        L_x = [c.center[0] for c in Liste_circles]
        L_y = [c.center[1] for c in Liste_circles]
        L_r = [c.radius for c in Liste_circles]

        min_x=min(L_x); max_x=max(L_x);min_y=min(L_y); max_y=max(L_y);max_r=max(L_r)

        xmin = min_x - 2*max_r
        xmax = max_x + 2*max_r

        ymin = min_y - 2*max_r
        ymax = max_y + 2*max_r

        ax.set_xlim(xmin, xmax)
        ax.set_ylim(ymin, ymax)

        for c in Liste_circles:
            new_c=copy(c)
            ax.add_patch(new_c)

        plt.show()

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C2=Circle(xy=(6, 3), radius=4, fill=False, color='b')
C3=Circle(xy=(7, 2), radius=4, fill=False, color='r')
</code>```

Body:
Here is my issue.

I create a function that plot a list of circles.
I need to plot my circle C1 first with a circle C2 then with C3.... until C40.

import matplotlib.pyplot as plt
from matplotlib.patches import Circle

def plot_circle(Liste_circles):

    fig = plt.figure(figsize=(5,5))
    ax = fig.add_subplot(111)

    # On définie un fond blanc
    ax.set_facecolor((1, 1, 1))

    ax.set_xlim(-5, 15)
    ax.set_ylim(-6, 12)

    for c in Liste_circles:
        ax.add_patch(c)

    plt.show()

Now I create C1:

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')

An finally I try to plot it.

The first plot worked:

C2=Circle(xy=(6, 3), radius=4, fill=False, color='b')
plot_circle([C1,C2])

The second one failed:

C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])

with the error:

RuntimeError: Can not put single artist in more than one figure

I can make it worked by doing:

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C3=Circle(xy=(7, 2), radius=4, fill=False, color='b')
plot_circle([C1,C3])

How can I do to plot my circle C1 with 40 other circles without having to recreate C1 each time? (My program took 10min to create C1 throught a complicated algorithme, I cannot recreate it at each of the 40 plot....).

Body:
Moreover if you are interested you can set the x and y axes regarding the values of the circles:

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from copy import copy

def plot_circles (Liste_circles):

    if len(Liste_circles) == 0:
        print('No circles to display')
    else:

        fig = plt.figure(figsize=(5,5))
        ax = fig.add_subplot(111)

        # On définie un fond blanc
        ax.set_facecolor((1, 1, 1))

        # On définie les limites des axes pour que nos cercles soient au centre de notre graphique
        # --> xmin sera le plus petit des x de tous les cercles - 2 fois le plus grand des rayons
        # --> xmax sera le plus grand des x de tous les cercles + 2 fois le plus grand des rayons
        # --> ymin sera le plus petit des y de tous les cercles - 2 fois le plus grand des rayons
        # --> ymax sera le plus grand des y de tous les cercles + 2 fois le plus grand des rayons
        L_x = [c.center[0] for c in Liste_circles]
        L_y = [c.center[1] for c in Liste_circles]
        L_r = [c.radius for c in Liste_circles]

        min_x=min(L_x); max_x=max(L_x);min_y=min(L_y); max_y=max(L_y);max_r=max(L_r)

        xmin = min_x - 2*max_r
        xmax = max_x + 2*max_r

        ymin = min_y - 2*max_r
        ymax = max_y + 2*max_r

        ax.set_xlim(xmin, xmax)
        ax.set_ylim(ymin, ymax)

        for c in Liste_circles:
            new_c=copy(c)
            ax.add_patch(new_c)

        plt.show()

C1=Circle(xy=(3, 4), radius=2, fill=False, color='g')
C2=Circle(xy=(6, 3), radius=4, fill=False, color='b')
C3=Circle(xy=(7, 2), radius=4, fill=False, color='r')


问:
how to translate formatted text in react native?
I use react-native-i18n for translating my app. I have a "formatted" text, like:

```<code><Text>Normal text <Text bold>this is bold</Text> back to normal</Text>
</code>```

Is it possible to make this text translatable in 1 or 2 strings instead of 3?

答: Finally, I've switched to i18next. It has a pretty decent react-native support, and seems to be much more elaborate than react-native-i18n is.</p>

Body:
I use react-native-i18n for translating my app. I have a "formatted" text, like:

<Text>Normal text <Text bold>this is bold</Text> back to normal</Text>

Is it possible to make this text translatable in 1 or 2 strings instead of 3?


问:
jquery .on is not working
When using $(document).on('ready', function(){////}) nothing is happens so I changed to $(document).ready(function(){////}).

When using .on function its not working and throwing error and exeption as follows:

Warning:

jQuery.Deferred exception: tabs[i].on is not a function TypeError:
  tabs[i].on is not a function
      at HTMLDocument. (https://animesh.dev/wp-content/plugins/hyparticles/assests/script.js?ver=4.9.1:7:11)
      at j (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:29999)
      at k (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:30313)
  undefined

Error:

Uncaught TypeError: tabs[i].on is not a function
      at HTMLDocument. (script.js?ver=4.9.1:7)
      at j (jquery-3.2.1.min.js?ver=4.9.1:2)
      at k (jquery-3.2.1.min.js?ver=4.9.1:2)

note: tabs is a variable defined by me inside script.js

note: I'm using jquery v3.2.1(latest) in minify version

why the error coming out

My script.js:

```<code>$(document).ready(function() {
    alert("ready");
    var tabs = $("ul.nav-tabs > li");

    for (i = 0; i < tabs.length; i++) {
        tabs[i].on("click", switchTab);
    }

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});
</code>```

答:
Try This</p>

```<code>$(document).ready(function() {
    $(document).on("ul.nav-tabs li" ,"click", function(event){
        event.preventDefault();
        console.log(event);
    });
});
</code>```

Title: jquery .on is not working

Body:
When using $(document).on('ready', function(){////}) nothing is happens so I changed to $(document).ready(function(){////}).

When using .on function its not working and throwing error and exeption as follows:

Warning:

jQuery.Deferred exception: tabs[i].on is not a function TypeError:
  tabs[i].on is not a function
      at HTMLDocument. (https://animesh.dev/wp-content/plugins/hyparticles/assests/script.js?ver=4.9.1:7:11)
      at j (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:29999)
      at k (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:30313)
  undefined

Error:

Uncaught TypeError: tabs[i].on is not a function
      at HTMLDocument. (script.js?ver=4.9.1:7)
      at j (jquery-3.2.1.min.js?ver=4.9.1:2)
      at k (jquery-3.2.1.min.js?ver=4.9.1:2)

note: tabs is a variable defined by me inside script.js

note: I'm using jquery v3.2.1(latest) in minify version

why the error coming out

My script.js:

$(document).ready(function() {
    alert("ready");
    var tabs = $("ul.nav-tabs > li");

    for (i = 0; i < tabs.length; i++) {
        tabs[i].on("click", switchTab);
    }

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});

Body:
Try This

$(document).ready(function() {
    $(document).on("ul.nav-tabs li" ,"click", function(event){
        event.preventDefault();
        console.log(event);
    });
});


问:
Appending an element to the child fires the drop event in the parent
I'm a bit confused with jquery's drag and drop behaviour.
Please check this fiddle:

I'm trying to check if the draggable element is dropped in the list (child) or the div (parent). It works fine if I comment the append call.
I tried inserting the greedy option in the child and checking the event.target in the parent's event handler but it always comes up as event.target=the parent

答:
Why you are binding droppable widget twice? Remove following widget

```<code>$("div.ui-droppable").droppable({
    greedy: true,
    drop: function (event, ui) {
        printEventReceiver("parent",event)
    }
})
</code>```

and, change

```<code>$("ul.ui-droppable").droppable({
</code>```

to

```<code>$(".ui-droppable").droppable({
</code>```

Basically, greedy flag work only within the context of one widget initialisation. So, it's better to initialise widget once by using some common class and remove duplicate initialisations when possible.

Check here: https://jsfiddle.net/scorpy2007/yu0pontg/23/

Body:
Why you are binding droppable widget twice? Remove following widget

$("div.ui-droppable").droppable({
    greedy: true,
    drop: function (event, ui) {
        printEventReceiver("parent",event)
    }
})

and, change

$("ul.ui-droppable").droppable({

to

$(".ui-droppable").droppable({

Basically, greedy flag work only within the context of one widget initialisation. So, it's better to initialise widget once by using some common class and remove duplicate initialisations when possible.

Check here: https://jsfiddle.net/scorpy2007/yu0pontg/23/


问:
How to use boost::geometry::rtree with glm::vec3 as a custom point type?
I'm using

```<code>BOOST_GEOMETRY_REGISTER_POINT_3D(glm::vec3, float, boost::geometry::cs::cartesian, x, y, z);
</code>```

with an RTree defined as:

```<code>  using IndexedPoint = std::pair<glm::vec3, uint32_t>;
  using RTree = boost::geometry::index::rtree<IndexedPoint, boost::geometry::index::rstar<8>>;
</code>```

When I try to run a nearest neighbor query with this it fails to compile:

```<code>auto it = rtree.qbegin(boost::geometry::index::nearest(glm::vec3(), 3))
</code>```

The error is:

```<code>error C2664: 'int boost::mpl::assertion_failed<false>(boost::mpl::assert<false>::type)': cannot convert argument 1 from 'boost::mpl::failed ************(__cdecl boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag,boost::geometry::box_tag,glm::vec<3,float,0>,boost::geometry::model::point<float,3,boost::geometry::cs::cartesian>,boost::geometry::cartesian_tag,boost::geometry::cartesian_tag,void>::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE_COMBINATION::* ***********)(boost::mpl::assert_::types<Point1,Point2,CsTag1,CsTag2>)' to 'boost::mpl::assert<false>::type'
        with
        [
            Point1=glm::vec<3,float,0>,
            Point2=boost::geometry::model::point<float,3,boost::geometry::cs::cartesian>,
            CsTag1=boost::geometry::cartesian_tag,
            CsTag2=boost::geometry::cartesian_tag
        ]
</code>```

It seems comparable_distance_result is missing specializations for vec3 vs boost::geometry::model::point and boost::geometry::model::box. I have tried adding them manually, but couldn't make it work. How can I add the required distance type specializations?

Note that I can use the same setup for spatial queries just fine, so it seems basically sound.

答:
I can not reproduce the problem with GCC/Boost 1.65.1:

Live¹ On Coliru

```<code>#include <boost/geometry.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/register/point.hpp>

namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;

#include <glm/vec3.hpp>
BOOST_GEOMETRY_REGISTER_POINT_3D(glm::vec3, float, bg::cs::cartesian, x, y, z)

#include <iostream>
int main() {

    using IndexedPoint = std::pair<glm::vec3, uint32_t>;
    using RTree = boost::geometry::index::rtree<IndexedPoint, boost::geometry::index::rstar<8>>;

    RTree rtree;
    rtree.insert({glm::vec3(1,1,1), 1});
    rtree.insert({glm::vec3(2,2,2), 2});
    rtree.insert({glm::vec3(3,3,3), 3});
    rtree.insert({glm::vec3(4,4,4), 4});

    auto it = rtree.qbegin(bgi::nearest(glm::vec3(2.9, 2.9, 2.9), 99));

    auto p = it->first;
    std::cout << "Nearest: # " << it->second << " (" << p.x << ", " << p.y << " " << p.z << ")\n";
}
</code>```

Prints

```<code>Nearest: # 3 (3, 3 3)
</code>```

¹ Coliru doesn't have libglm

Body:
I'm using

BOOST_GEOMETRY_REGISTER_POINT_3D(glm::vec3, float, boost::geometry::cs::cartesian, x, y, z);

with an RTree defined as:

  using IndexedPoint = std::pair<glm::vec3, uint32_t>;
  using RTree = boost::geometry::index::rtree<IndexedPoint, boost::geometry::index::rstar<8>>;

When I try to run a nearest neighbor query with this it fails to compile:

auto it = rtree.qbegin(boost::geometry::index::nearest(glm::vec3(), 3))

The error is:

error C2664: 'int boost::mpl::assertion_failed<false>(boost::mpl::assert<false>::type)': cannot convert argument 1 from 'boost::mpl::failed ************(__cdecl boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag,boost::geometry::box_tag,glm::vec<3,float,0>,boost::geometry::model::point<float,3,boost::geometry::cs::cartesian>,boost::geometry::cartesian_tag,boost::geometry::cartesian_tag,void>::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE_COMBINATION::* ***********)(boost::mpl::assert_::types<Point1,Point2,CsTag1,CsTag2>)' to 'boost::mpl::assert<false>::type'
        with
        [
            Point1=glm::vec<3,float,0>,
            Point2=boost::geometry::model::point<float,3,boost::geometry::cs::cartesian>,
            CsTag1=boost::geometry::cartesian_tag,
            CsTag2=boost::geometry::cartesian_tag
        ]

It seems comparable_distance_result is missing specializations for vec3 vs boost::geometry::model::point and boost::geometry::model::box. I have tried adding them manually, but couldn't make it work. How can I add the required distance type specializations?

Note that I can use the same setup for spatial queries just fine, so it seems basically sound.

Body:
I can not reproduce the problem with GCC/Boost 1.65.1:

Live¹ On Coliru

#include <boost/geometry.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/register/point.hpp>

namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;

#include <glm/vec3.hpp>
BOOST_GEOMETRY_REGISTER_POINT_3D(glm::vec3, float, bg::cs::cartesian, x, y, z)

#include <iostream>
int main() {

    using IndexedPoint = std::pair<glm::vec3, uint32_t>;
    using RTree = boost::geometry::index::rtree<IndexedPoint, boost::geometry::index::rstar<8>>;

    RTree rtree;
    rtree.insert({glm::vec3(1,1,1), 1});
    rtree.insert({glm::vec3(2,2,2), 2});
    rtree.insert({glm::vec3(3,3,3), 3});
    rtree.insert({glm::vec3(4,4,4), 4});

    auto it = rtree.qbegin(bgi::nearest(glm::vec3(2.9, 2.9, 2.9), 99));

    auto p = it->first;
    std::cout << "Nearest: # " << it->second << " (" << p.x << ", " << p.y << " " << p.z << ")\n";
}

Prints

Nearest: # 3 (3, 3 3)

¹ Coliru doesn't have libglm


问:
Throughput coming very low as against the desired RPS-Jmeter
In Jmeter, how can I achieve a 100 RPS for an http request which is taking an average of 20 seconds response time? The more the thread count I gave, the more response time it took.

What should be the thread count that I should ideally give in this situation? If I am adding a constant throughput timer or throughput shaping timer what should the thread count as well as the settings of the timers?

I have adjusted thread count to 100,250,500, 2500. But it is not giving anything close to 100 RPS. It is about 20/minute that I see.

答:
This sounds like a bottleneck so

First of all ensure that you're following JMeter Best Practices as it might be the case JMeter configuration is not suitable for kicking off that many threads.

Second I would recommend checking whether your system under test has enough headroom in terms of resources (CPU, RAM, Network, Disk, etc.), you can do this using i.e. JMeter Perfmon Plugin

If there is no lack of resources but application performance is not satisfactory, like at point 1 you can check infrastructure configuration (web/application server settings, database settings, etc.) as in majority of cases default configurations are not good enough for high loads. Refer documentation on your infrastructure software for tuning tips.

And finally there could be problems with your application code itself, re-run your test having profiling tools telemetry enabled, this way you will be able to tell for sure where your application spends time and/or resources.


问:
How to dynamically create sub-domains with different IP than the original domain correctly and efficiently?
How to efficiently create subdomains dynamically that are resolved to different IP than the original domain?

Most dynamic subdomain creation solutions I've found here would add a *.domain.com A-record to the DNS server (usually using BIND), but that's not what I want.

Does that mean the zone file needs to be set to always Expire?  Wouldn't that tax our DNS server heavily?

However, what if the client ISP doesn't go and fetch the new zone file I just dynamically changed?  Wouldn't they not able to resolve our new sub-domain entry?

Would setting up DDNS in BIND be the logical path for implementing such system?  DDNS would allow me dynamically insert A-record without restarting BIND, right?

I'm sure there are some way to do this, since most large blogging service that doesn't point all account to the same IP as the blogging engine, are doing something similar to what I need.

Thank you!

答: I would imagine that most services that do this have their wildcard (*.) DNS entry setup for these accounts, and probabley point it to a load balancer, that distributes requests based on host name etc. They then have the non-standard entrys setup as normal A records in DNS.</p>

OwnerDisplayName: Henry

LastEditorDisplayName: Ishmaeel


问:
Ipykernel in anaconda2 on Linux can't create new virtualenv into Jupyter notebook
I am using a Vagrant Ubuntu VM to create a new virtualenv for jupyter notebook. I installed ipykernel and activated the virtualenv by anaconda2.

When I typed the follow command to add the virtualenv to jupyter notebook:

```<code>python -m ipykernel install --user --name my-env --display-name "my-env"
</code>```

The error info was as below:

```<code>[Errno 13] Permission denied: '/home/vagrant/.local/share'
Perhaps you want `sudo` or `--user`?
</code>```

Then, I typed again with "sudo" before the command, the info turned out as:

```<code>/usr/bin/python: No module named ipykernel
</code>```

So, how can I get rid of it?

答:
Well, I solved the problem by myself.

First, you indeed need "sudo" to verify this operation as root. But after this the second problem appeared, "sudo" uses default python path, which is the system built-in python path, NOT your anaconda environment's python path.

All you need is just to set the default python path to the environment's,
with this line of commands as:

```<code>sudo update-alternatives --install /usr/bin/python python ~/anaconda2/env/my-env/bin/python 1
</code>```

And then, run:

```<code>sudo python -m ipykernel install --user --name my-env --display-name "my-env"
</code>```

Body:
I am using a Vagrant Ubuntu VM to create a new virtualenv for jupyter notebook. I installed ipykernel and activated the virtualenv by anaconda2.

When I typed the follow command to add the virtualenv to jupyter notebook:

python -m ipykernel install --user --name my-env --display-name "my-env"

The error info was as below:

[Errno 13] Permission denied: '/home/vagrant/.local/share'
Perhaps you want `sudo` or `--user`?

Then, I typed again with "sudo" before the command, the info turned out as:

/usr/bin/python: No module named ipykernel

So, how can I get rid of it?

Body:
Well, I solved the problem by myself.

First, you indeed need "sudo" to verify this operation as root. But after this the second problem appeared, "sudo" uses default python path, which is the system built-in python path, NOT your anaconda environment's python path.

All you need is just to set the default python path to the environment's,
with this line of commands as:

sudo update-alternatives --install /usr/bin/python python ~/anaconda2/env/my-env/bin/python 1

And then, run:

sudo python -m ipykernel install --user --name my-env --display-name "my-env"