问:
How do I make it so that my program reads multiple txt files and creates it into a dataframe for python?
Currently I am making a program to cycle through multiple txt files and turn them into dataframes so that the data can be analysed. I have used the glob function to return a list of txt files. After that, I have created a for loop which cycles through every item in the list. Then I use the read_csv function to read this data, data.head() to print it. I know my code is probably really stupid but please help me fix it. I am currently at a loss for what to do.

Here is my original code:

```<code>import glob
import pandas as pd
path = '/content/gdrive/My Drive/Datapoints/*.txt'
dataframes = []
for filename in glob.glob(path):
  data = pd.read_csv(filename, header=None, delimiter='\t')
  data.head()
</code>```

For reasons I do not understand (I am a novice when it comes to programming), my code is getting a lot of errors:

```<code>ParserError                               Traceback (most recent call last)

<ipython-input-52-f940d2e4b46d> in <module>()
      2 dataframes = []
      3 for filename in glob.glob(path):
----> 4   data = pd.read_csv(filename, header=None, delimiter='\t')

3 frames

/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py in read(self, nrows)
   2035     def read(self, nrows=None):
   2036         try:
-> 2037             data = self._reader.read(nrows)
   2038         except StopIteration:
   2039             if self._first_chunk:

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows()

pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error()

ParserError: Error tokenizing data. C error: Expected 9 fields in line 110853, saw 10
</code>```

答:
Looks like one of your CSV's has an incorrect number of columns. It's on line 110853. You could add some test code to help troubleshoot it, like this:

```<code>import glob
import pandas as pd
path = '/content/gdrive/My Drive/Datapoints/*.txt'
dataframes = []
for filename in glob.iglob(path):
  try:
    data = pd.read_csv(filename, header=None, delimiter='\t')
    data.head()
  except pd.errors.ParserError:
    print(f'Error in file: {filename}')
    raise
</code>```

This should print out the filename that is causing the problem.

Note that I changed glob.glob(path) to glob.iglob(path), which probably won't make much difference, unless you have an enormous number of files. iglob gives you an iterator, whereas glob gives a list, and then behind the scenes it ends up using the list.__iter__ method in the same way. iglob will be slightly more efficient, and is a bit more pythonic.

Also, the except block ends with a raise statement, which is usually good practice when you do exception handling, since it prevents information about the error from being lost. It will also stop any additional files from being processed, which is a good thing in situations where the error is not recoverable and the code that caused the error should not be allowed to continue running.

Body:
Currently I am making a program to cycle through multiple txt files and turn them into dataframes so that the data can be analysed. I have used the glob function to return a list of txt files. After that, I have created a for loop which cycles through every item in the list. Then I use the read_csv function to read this data, data.head() to print it. I know my code is probably really stupid but please help me fix it. I am currently at a loss for what to do.

Here is my original code:

import glob
import pandas as pd
path = '/content/gdrive/My Drive/Datapoints/*.txt'
dataframes = []
for filename in glob.glob(path):
  data = pd.read_csv(filename, header=None, delimiter='\t')
  data.head()

For reasons I do not understand (I am a novice when it comes to programming), my code is getting a lot of errors:

ParserError                               Traceback (most recent call last)

<ipython-input-52-f940d2e4b46d> in <module>()
      2 dataframes = []
      3 for filename in glob.glob(path):
----> 4   data = pd.read_csv(filename, header=None, delimiter='\t')

3 frames

/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py in read(self, nrows)
   2035     def read(self, nrows=None):
   2036         try:
-> 2037             data = self._reader.read(nrows)
   2038         except StopIteration:
   2039             if self._first_chunk:

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows()

pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error()

ParserError: Error tokenizing data. C error: Expected 9 fields in line 110853, saw 10

Body:
Looks like one of your CSV's has an incorrect number of columns. It's on line 110853. You could add some test code to help troubleshoot it, like this:

import glob
import pandas as pd
path = '/content/gdrive/My Drive/Datapoints/*.txt'
dataframes = []
for filename in glob.iglob(path):
  try:
    data = pd.read_csv(filename, header=None, delimiter='\t')
    data.head()
  except pd.errors.ParserError:
    print(f'Error in file: {filename}')
    raise

This should print out the filename that is causing the problem.

Note that I changed glob.glob(path) to glob.iglob(path), which probably won't make much difference, unless you have an enormous number of files. iglob gives you an iterator, whereas glob gives a list, and then behind the scenes it ends up using the list.__iter__ method in the same way. iglob will be slightly more efficient, and is a bit more pythonic.

Also, the except block ends with a raise statement, which is usually good practice when you do exception handling, since it prevents information about the error from being lost. It will also stop any additional files from being processed, which is a good thing in situations where the error is not recoverable and the code that caused the error should not be allowed to continue running.


来源: stackexchange

问:
Groovy Email client to work on both Exchange 2003 and Exchange 2010
I need to implement a feature in my application to process an email, that I need to read by logging into the Exchange server. My question is what is the way to make my solution to work in both Exchange 2003 and 2010?

In near future my exchange sever may get upgraded

Note: I cannot use Imap, POP, etc...

I can use only Mapi or EWS.

答: There appear to be several options in Java to do this but no groovy specific ones. Pick one of them and use it from your groovy code. I haven't tried any of these but have a look at all the exchange providers listed on this page</p>

ContentLicense: CC BY-SA 3.0


问:
Netsuite: How to link Purchase Order to Sales Order
I’m trying to automate linking the NetSuite purchase order to a NetSuite sale order and the following is the code I tried to accomplish this task. But I'm getting error (see at the bottom). Can you please check and let me know what I’m missing here?

Purchase Order Creation code:

```<code>var createPurchaseOrder = new PurchaseOrder();

createPurchaseOrder.entity = new RecordRef()
{
internalId = “653”
//type = RecordType.purchaseOrder,
//typeSpecified = true
};

RecordRef soRecordRef = new RecordRef();
soRecordRef.internalId = “XXXXXXXX”;
soRecordRef.type = RecordType.salesOrder;
soRecordRef.typeSpecified = true;

createPurchaseOrder.createdFrom = soRecordRef;

RecordRef depRecordRef = new RecordRef();
depRecordRef.internalId = “3”;
depRecordRef.name = “eBay : eBay FNC”;
depRecordRef.type = RecordType.department;
depRecordRef.typeSpecified = true;

createPurchaseOrder.department = depRecordRef;

PurchaseOrderItem[] Items = new PurchaseOrderItem[1];

Items[0] = new PurchaseOrderItem();
RecordRef item = new RecordRef();
item.type = RecordType.nonInventoryPurchaseItem;
item.typeSpecified = true;
item.internalId = “XXXXX”;
Items[0].item = item;

Items[0].rate = “5”;
Items[0].quantity = 1;
Items[0].quantitySpecified = true;

PurchaseOrderItemList purchaseOrderItemList = new PurchaseOrderItemList();
purchaseOrderItemList.item = Items;
createPurchaseOrder.itemList = purchaseOrderItemList;

WriteResponse response = Service.add(createPurchaseOrder);
</code>```

Code I'm using to Update Purchase Order Number in Sales Order:

```<code>var updateSalesOrder = new SalesOrder();
updateSalesOrder.internalId = “XXXXXXXX”;

SalesOrderItem[] soItems = new SalesOrderItem[1];

var soItem = new SalesOrderItem();

RecordRef roItem = new RecordRef();
roItem.type = RecordType.inventoryItem;
roItem.typeSpecified = true;
roItem.internalId = “XXXXX”;
soItem.item = roItem;

RecordRef prLevel = new RecordRef();
prLevel.type = RecordType.priceLevel;
prLevel.internalId = “-1”;
prLevel.typeSpecified = true;

soItem.price = prLevel;
soItem.rate = “15”;
soItem.quantity = 1;
soItem.quantitySpecified = true;

RecordRef poItem = new RecordRef();
poItem.type = RecordType.purchaseOrder;
poItem.typeSpecified = true;
poItem.internalId = purchaseOrder.internalId;
soItem.createdPo = poItem;

soItems[0] = soItem;

SalesOrderItemList salesOrderItemList = new SalesOrderItemList();
salesOrderItemList.item = soItems;
updateSalesOrder.itemList = salesOrderItemList;

response = Service.update(updateSalesOrder);
if (response.status.isSuccess != true) throw new Exception(response.status.statusDetail[0].message);
</code>```

But I get the follwoing Error:
You do not have permissions to set a value for element createPOSpecified due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases.

Note: createPOSpecified is not displayed in the sales order screen in NetSuite. When I try to update a field in the sales order which exist in the form, then I am able to update it successfully but the field I am trying to update (createPOSpecified ) is not available in this sales form. In this case how can I update this ? Also is this the better way of linking the purchase order with sales order?

Thanks,
Hemant.

Updated 25-May-2020 (Responding to Anand Rajaram)

We are using the ADMINISTRATOR role for creating purchase order and linking that to sales order. A user with this role has been provided by our client and we don’t have permission to see fields that are displayed in the screen and have been restricted for EDIT. But we are able to edit most of the field displayed in the screen.

createPOSpecified is not a custom field. It’s a property in the SALESORDETITEM class. It will not be displayed in any sales order form.

If this is the proper code for creating purchase order and linking that to sales order, then I have few queries:

3.1 When we create purchase order through NetSuite by clicking the dropship link in the sales order item grid, we are able to see Mark Shipped button.

But when we create purchase order through code, it is displaying the Receive button and there was no changes in the purchase order status.

```<code>3.2 **createdFrom** field is displaying as below when we create purchase order through netsuite.
</code>```

This field is not displaying when we are creating purchase order through code. We have provided information for createdFrom property, but not sure why it is not displaying

We assume this is the field that helps to link with sales order. We have provided this information while creating item fulfillment and vendor bill and these are properly linked with sales order, but we are not sure why purchase order is not getting linked with sales order.

Finally on the below comments which you have provided
Which is basically having a custom transaction body field on Sales Order form, and once PO is created, update the newly created PO in Sales Order field.

We don’t have any custom transaction body field in our sales order form for providing purchase order. But once purchase order is created through NetSuite, purchase order number will be displayed in the sales order item grid.

So all this boils down to: what is that we have missed in the code and what is that we have to fix to display the "Mark Shipped" button, “Created From" label and linking Purchase Order to Sales Order.

Thanks,
Hemant.

答:
I don't have an answer, but hopefully I can contribute. First of all, I think you're approaching this from the wrong direction. Rather than creating the PO and then trying to link it to the SO, I think you'll have to initialize the PO via the native dropship process and then save the PO. For example, creating a drop ship PO is pretty easy in SuiteScript 2.0. Here's how it's done:

```<code>var purchaseOrder = record.create ({
    type: record.Type.PURCHASE_ORDER,
    isDynamic: true,
    defaultValues: {
        recordmode: 'dynamic',
        soid: '11111',
        dropship: true,
        custid: '22222',
        entity: '33333'
    }
})
</code>```

This new PO is populated with all valid items from the SO and when it's saved all the linking is done automatically (createdFrom is automatically set on the PO; createdPo is automatically set on the SO item). I tried to recreate this in SuiteTalk using two different methods, both of which failed. Here they are:

The first approach tries to emulate the SuiteScript method using the initialize() method. This is how you create an SO from an Estimate, or an IF from an SO, so it seems promising:

```<code>var initrec = new InitializeRecord
{
    type = InitializeType.purchaseOrder,
    reference = new InitializeRef
    {
        internalId = "11111",
        type = InitializeRefType.salesOrder,
        typeSpecified = true
    }
};
var res = NSBase.Client.Service.initialize(initrec);
// "You can not initialize purchaseOrder by referencing salesOrder."
</code>```

The error is self-explanatory. It's not possible to create a PO from an SO using initialize(). This is very disheartening.

The second approach essentially tries to programmatically click the "drop ship" link on the line item. It fails with a similar error to the one you encountered before:

```<code>var objSO = new SalesOrder();
objSO.internalId = "11111";
objSO.itemList = new SalesOrderItemList
{
    item = new SalesOrderItem[]
    {
        new SalesOrderItem { line = 10, lineSpecified = true, createPo = SalesOrderItemCreatePo._dropShipment, createPoSpecified = true }
    },
    replaceAll = false
};
var result = Service.update(objSO);
// "You do not have permissions to set a value for element item.createpo due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases."
</code>```

Unfortunately, this is the best I can do. The initialization approach definitely seems like the most likely solution to the problem, and the fact that it fails makes me wonder if it is even possible to create a drop ship/special order PO using SuiteTalk.

ContentLicense: CC BY-SA 4.0

Body:
I’m trying to automate linking the NetSuite purchase order to a NetSuite sale order and the following is the code I tried to accomplish this task. But I'm getting error (see at the bottom). Can you please check and let me know what I’m missing here?

Purchase Order Creation code:

var createPurchaseOrder = new PurchaseOrder();

createPurchaseOrder.entity = new RecordRef()
{
internalId = “653”
//type = RecordType.purchaseOrder,
//typeSpecified = true
};

RecordRef soRecordRef = new RecordRef();
soRecordRef.internalId = “XXXXXXXX”;
soRecordRef.type = RecordType.salesOrder;
soRecordRef.typeSpecified = true;

createPurchaseOrder.createdFrom = soRecordRef;

RecordRef depRecordRef = new RecordRef();
depRecordRef.internalId = “3”;
depRecordRef.name = “eBay : eBay FNC”;
depRecordRef.type = RecordType.department;
depRecordRef.typeSpecified = true;

createPurchaseOrder.department = depRecordRef;

PurchaseOrderItem[] Items = new PurchaseOrderItem[1];

Items[0] = new PurchaseOrderItem();
RecordRef item = new RecordRef();
item.type = RecordType.nonInventoryPurchaseItem;
item.typeSpecified = true;
item.internalId = “XXXXX”;
Items[0].item = item;

Items[0].rate = “5”;
Items[0].quantity = 1;
Items[0].quantitySpecified = true;

PurchaseOrderItemList purchaseOrderItemList = new PurchaseOrderItemList();
purchaseOrderItemList.item = Items;
createPurchaseOrder.itemList = purchaseOrderItemList;

WriteResponse response = Service.add(createPurchaseOrder);

Code I'm using to Update Purchase Order Number in Sales Order:

var updateSalesOrder = new SalesOrder();
updateSalesOrder.internalId = “XXXXXXXX”;

SalesOrderItem[] soItems = new SalesOrderItem[1];

var soItem = new SalesOrderItem();

RecordRef roItem = new RecordRef();
roItem.type = RecordType.inventoryItem;
roItem.typeSpecified = true;
roItem.internalId = “XXXXX”;
soItem.item = roItem;

RecordRef prLevel = new RecordRef();
prLevel.type = RecordType.priceLevel;
prLevel.internalId = “-1”;
prLevel.typeSpecified = true;

soItem.price = prLevel;
soItem.rate = “15”;
soItem.quantity = 1;
soItem.quantitySpecified = true;

RecordRef poItem = new RecordRef();
poItem.type = RecordType.purchaseOrder;
poItem.typeSpecified = true;
poItem.internalId = purchaseOrder.internalId;
soItem.createdPo = poItem;

soItems[0] = soItem;

SalesOrderItemList salesOrderItemList = new SalesOrderItemList();
salesOrderItemList.item = soItems;
updateSalesOrder.itemList = salesOrderItemList;

response = Service.update(updateSalesOrder);
if (response.status.isSuccess != true) throw new Exception(response.status.statusDetail[0].message);

But I get the follwoing Error:
You do not have permissions to set a value for element createPOSpecified due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases.

Note: createPOSpecified is not displayed in the sales order screen in NetSuite. When I try to update a field in the sales order which exist in the form, then I am able to update it successfully but the field I am trying to update (createPOSpecified ) is not available in this sales form. In this case how can I update this ? Also is this the better way of linking the purchase order with sales order?

Thanks,
Hemant.

Updated 25-May-2020 (Responding to Anand Rajaram)

We are using the ADMINISTRATOR role for creating purchase order and linking that to sales order. A user with this role has been provided by our client and we don’t have permission to see fields that are displayed in the screen and have been restricted for EDIT. But we are able to edit most of the field displayed in the screen.

createPOSpecified is not a custom field. It’s a property in the SALESORDETITEM class. It will not be displayed in any sales order form.

If this is the proper code for creating purchase order and linking that to sales order, then I have few queries:

3.1 When we create purchase order through NetSuite by clicking the dropship link in the sales order item grid, we are able to see Mark Shipped button.

But when we create purchase order through code, it is displaying the Receive button and there was no changes in the purchase order status.

3.2 **createdFrom** field is displaying as below when we create purchase order through netsuite.

This field is not displaying when we are creating purchase order through code. We have provided information for createdFrom property, but not sure why it is not displaying

We assume this is the field that helps to link with sales order. We have provided this information while creating item fulfillment and vendor bill and these are properly linked with sales order, but we are not sure why purchase order is not getting linked with sales order.

Finally on the below comments which you have provided
Which is basically having a custom transaction body field on Sales Order form, and once PO is created, update the newly created PO in Sales Order field.

We don’t have any custom transaction body field in our sales order form for providing purchase order. But once purchase order is created through NetSuite, purchase order number will be displayed in the sales order item grid.

So all this boils down to: what is that we have missed in the code and what is that we have to fix to display the "Mark Shipped" button, “Created From" label and linking Purchase Order to Sales Order.

Thanks,
Hemant.

Body:
I don't have an answer, but hopefully I can contribute. First of all, I think you're approaching this from the wrong direction. Rather than creating the PO and then trying to link it to the SO, I think you'll have to initialize the PO via the native dropship process and then save the PO. For example, creating a drop ship PO is pretty easy in SuiteScript 2.0. Here's how it's done:

var purchaseOrder = record.create ({
    type: record.Type.PURCHASE_ORDER,
    isDynamic: true,
    defaultValues: {
        recordmode: 'dynamic',
        soid: '11111',
        dropship: true,
        custid: '22222',
        entity: '33333'
    }
})

This new PO is populated with all valid items from the SO and when it's saved all the linking is done automatically (createdFrom is automatically set on the PO; createdPo is automatically set on the SO item). I tried to recreate this in SuiteTalk using two different methods, both of which failed. Here they are:

The first approach tries to emulate the SuiteScript method using the initialize() method. This is how you create an SO from an Estimate, or an IF from an SO, so it seems promising:

var initrec = new InitializeRecord
{
    type = InitializeType.purchaseOrder,
    reference = new InitializeRef
    {
        internalId = "11111",
        type = InitializeRefType.salesOrder,
        typeSpecified = true
    }
};
var res = NSBase.Client.Service.initialize(initrec);
// "You can not initialize purchaseOrder by referencing salesOrder."

The error is self-explanatory. It's not possible to create a PO from an SO using initialize(). This is very disheartening.

The second approach essentially tries to programmatically click the "drop ship" link on the line item. It fails with a similar error to the one you encountered before:

var objSO = new SalesOrder();
objSO.internalId = "11111";
objSO.itemList = new SalesOrderItemList
{
    item = new SalesOrderItem[]
    {
        new SalesOrderItem { line = 10, lineSpecified = true, createPo = SalesOrderItemCreatePo._dropShipment, createPoSpecified = true }
    },
    replaceAll = false
};
var result = Service.update(objSO);
// "You do not have permissions to set a value for element item.createpo due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases."

Unfortunately, this is the best I can do. The initialization approach definitely seems like the most likely solution to the problem, and the fact that it fails makes me wonder if it is even possible to create a drop ship/special order PO using SuiteTalk.


答:
It seems, that one of your csv is having some inconsistency, error or misleading structure and pandas is not able to figure out on its own how to read it. In the current message it is expecting 9 columns but finds 10 column in line 110853. This needs further investigation and for that you need to catch which file is causing this:

The following code will catch the ParserError exception and print the file name for you. Based on this you can start checking what's going on.

```<code>path = '/content/gdrive/My Drive/Datapoints/*.txt'
dataframes = []
for filename in glob.glob(path):
    try:
        data = pd.read_csv(filename, header=None, delimiter='\t')
        dataframes.append(data)
    except pd.errors.ParserError as err:
        print(filename)
</code>```

Title: How do I make it so that my program reads multiple txt files and creates it into a dataframe for python?

Body:
It seems, that one of your csv is having some inconsistency, error or misleading structure and pandas is not able to figure out on its own how to read it. In the current message it is expecting 9 columns but finds 10 column in line 110853. This needs further investigation and for that you need to catch which file is causing this:

The following code will catch the ParserError exception and print the file name for you. Based on this you can start checking what's going on.

path = '/content/gdrive/My Drive/Datapoints/*.txt'
dataframes = []
for filename in glob.glob(path):
    try:
        data = pd.read_csv(filename, header=None, delimiter='\t')
        dataframes.append(data)
    except pd.errors.ParserError as err:
        print(filename)


问:
Alert button to dismiss Alert and go back to previous View Controller
I'm kind of new to Swift and I can't figure this out. I have an Alert that should show on a successful URL request. After a user clicks an Ok button on the alert, I need the alert dismissed and I need the presented controller to go back in the navigation stack to the previous view controller. I don't get any errors but nothing happens. If I move the entire code for the Alert inside the CustomClass, then it works fine. I assume I am not referencing the CustomClass the right way. Any help would be greatly appreciated!

```<code> struct Alert {
    static func CustomAlert(vc: UIViewController, title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            let vc = CustomClass()
            vc.GoBackToPreviousVC()
        }))
         vc.present(myAlert, animated: true, completion: nil)
    }
 }

 class: CustomClass: UIViewController {

    func GoBackToPreviousVC(){
        navigationController?popViewController(animated: true)
    }

    function Download(){

      code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200"){
            Alert.CustomAlert(vc: self, title: "", message: "")
        }

      }

    }
}
</code>```

答:
Swift 5.3

You add Utility class. I use it like this.

```<code>public class UtilsClass: NSObject  {
    public static let shared = UtilsClass()

    public func customAlertYN(ViewController:UIViewController,title:String!,actionTitle:String!,message:String!,okButtonString:String!,cancelButtonString:String!,okCallback: @escaping () -> Void = {}){
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let ok = UIAlertAction(title: okButtonString, style: .default, handler: { (action) -> Void in
                okCallback()
            })

            let cancel = UIAlertAction(title: cancelButtonString, style: .cancel) { (action) -> Void in

            }

            alert.addAction(ok)
            alert.addAction(cancel)
            ViewController.present(alert, animated: true, completion: nil)
        }
      }
</code>```

And use this way. Add your viewController.

```<code>UtilsClass.shared.customAlertYN(ViewController: self, title: "Alert", actionTitle: "", message: "Are you sure you want to logout?", okButtonString: "Yes", cancelButtonString: "No",okCallback: {
                //TODO:
   })
</code>```

Body:
I'm kind of new to Swift and I can't figure this out. I have an Alert that should show on a successful URL request. After a user clicks an Ok button on the alert, I need the alert dismissed and I need the presented controller to go back in the navigation stack to the previous view controller. I don't get any errors but nothing happens. If I move the entire code for the Alert inside the CustomClass, then it works fine. I assume I am not referencing the CustomClass the right way. Any help would be greatly appreciated!

 struct Alert {
    static func CustomAlert(vc: UIViewController, title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            let vc = CustomClass()
            vc.GoBackToPreviousVC()
        }))
         vc.present(myAlert, animated: true, completion: nil)
    }
 }

 class: CustomClass: UIViewController {

    func GoBackToPreviousVC(){
        navigationController?popViewController(animated: true)
    }

    function Download(){

      code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200"){
            Alert.CustomAlert(vc: self, title: "", message: "")
        }

      }

    }
}

Body:
Swift 5.3

You add Utility class. I use it like this.

public class UtilsClass: NSObject  {
    public static let shared = UtilsClass()

    public func customAlertYN(ViewController:UIViewController,title:String!,actionTitle:String!,message:String!,okButtonString:String!,cancelButtonString:String!,okCallback: @escaping () -> Void = {}){
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let ok = UIAlertAction(title: okButtonString, style: .default, handler: { (action) -> Void in
                okCallback()
            })

            let cancel = UIAlertAction(title: cancelButtonString, style: .cancel) { (action) -> Void in

            }

            alert.addAction(ok)
            alert.addAction(cancel)
            ViewController.present(alert, animated: true, completion: nil)
        }
      }

And use this way. Add your viewController.

UtilsClass.shared.customAlertYN(ViewController: self, title: "Alert", actionTitle: "", message: "Are you sure you want to logout?", okButtonString: "Yes", cancelButtonString: "No",okCallback: {
                //TODO:
   })


问:
If compared values are true then $.getJSON()
This is a follow up to my earlier question.

I wanted to compare the results I get back from filling out a form.

This is what I have so far:

```<code>const eqObj = (obj, source) =>
    Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);

$('#btn').on('click', function() {
    let $inputs = $('#new_form :input');
    let new_vals = {};
    $inputs.each(function() {
        new_form[this.id] = $(this).val();
    });

    console.log(new_vals);
    $.getJSON(api, function(data) {
        data.forEach(d => {
            console.log(d.values);
            if (eqObj(new_vals, d.values){//open first models and append matched values}
            else {//open other modal}
        });
    });
});
</code>```

My console.log() for new_vals: {start_date: "2019-12-25", end_date: "2020-04-15"}

my console.log() for d.values:

```<code>{start_date: "2020-01-01", end_date: "2020-03-15"}
{start_date: "2020-01-01", end_date: "2020-03-15"}
{start_date: "2019-12-25", end_date: "2020-04-15"}
{start_date: "2020-03-20", end_date: "2020-03-31"}
{start_date: "2019-10-01", end_date: "2020-03-31"}
{start_date: "2019-10-01", end_date: "2020-03-31"}
{start_date: "2020-01-01", end_date: "2020-01-31"}
{start_date: "2020-01-19", end_date: "2020-01-25"}
</code>```

When I enter the unmatched values, I am able to open the second modal as I want, but when I enter the matched value in my form, it opens both modals.

Why are both modals opening in my if statement? Is there any way I just do the $.getJSON() in my if statement? I don't need it? I only need the $.getJson() if there are matches, if not I need to open another modal.

答:
You probably need to improve your if statement.
If you want to show one or another modal only and never both you need to return as soon as the match happens.
Try this:</p>

```<code>       data.forEach(d => {
            console.log(d.values);
            if (eqObj(new_run_vals, d.values) {
              //open first models and append matched values;
              return;
            }
            //open other modal
        });
</code>```

Body:
This is a follow up to my earlier question.

I wanted to compare the results I get back from filling out a form.

This is what I have so far:

const eqObj = (obj, source) =>
    Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);

$('#btn').on('click', function() {
    let $inputs = $('#new_form :input');
    let new_vals = {};
    $inputs.each(function() {
        new_form[this.id] = $(this).val();
    });

    console.log(new_vals);
    $.getJSON(api, function(data) {
        data.forEach(d => {
            console.log(d.values);
            if (eqObj(new_vals, d.values){//open first models and append matched values}
            else {//open other modal}
        });
    });
});

My console.log() for new_vals: {start_date: "2019-12-25", end_date: "2020-04-15"}

my console.log() for d.values:

{start_date: "2020-01-01", end_date: "2020-03-15"}
{start_date: "2020-01-01", end_date: "2020-03-15"}
{start_date: "2019-12-25", end_date: "2020-04-15"}
{start_date: "2020-03-20", end_date: "2020-03-31"}
{start_date: "2019-10-01", end_date: "2020-03-31"}
{start_date: "2019-10-01", end_date: "2020-03-31"}
{start_date: "2020-01-01", end_date: "2020-01-31"}
{start_date: "2020-01-19", end_date: "2020-01-25"}

When I enter the unmatched values, I am able to open the second modal as I want, but when I enter the matched value in my form, it opens both modals.

Why are both modals opening in my if statement? Is there any way I just do the $.getJSON() in my if statement? I don't need it? I only need the $.getJson() if there are matches, if not I need to open another modal.

Body:
You probably need to improve your if statement.
If you want to show one or another modal only and never both you need to return as soon as the match happens.
Try this:

       data.forEach(d => {
            console.log(d.values);
            if (eqObj(new_run_vals, d.values) {
              //open first models and append matched values;
              return;
            }
            //open other modal
        });


问:
Compare two files if they both match first column then replace the values of column 2 and 3 (Python)
There are two files. If the ID number matches both files, then I want only the value 1 and value 2 from File2.txt , Please let me know if my question is unclear

```<code>File1.txt

ID Number   Value 1     Value 2     Country
0001        23            55        Spain
0231        15            23        USA
4213        10            11        Canada
7541        32            29        Italy

File2.txt

0001        5       6
0231        7       18
4213        54      87
5554        12      10
1111        31      13
6422        66      51
</code>```

The output should look like this.

```<code>ID Number   Value 1     Value 2     Country
0001          5           6         Spain
0231          7          18         USA
4213          54         87         Canada
7541          32         29         Italy
</code>```

New example:

```<code>File3.txt

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.739000  -114.635700
01711 CX 21 --   3  32.779700  -115.567500
08433 CX 21 --   2  31.919930  -123.321000

File4.txt

20022,32.45,-114.88
01192,32.839,-115.487
01711,32.88,-115.45
01218,32.717,-115.637

output
#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000
</code>```

Code I got so far

```<code>f = open("File3.txt", "r")
x= open("File4.txt","r")

df1 = pd.read_csv(f, sep=' ', engine='python')
df2 = pd.read_csv(x, sep=' ', header=None, engine='python')

df2 = df2.set_index(0).rename_axis("#ID")
df2 = df2.rename(columns={5:'LATITUDE', 6: 'LONGITUDE'})
df1 = df1.set_index('#ID')
df1.update(df2)
print(df1)
</code>```

答:
Okay, what you need to do here is to get the indexes to match in both dataframes after importing.  This is important because pandas use data alignment based on indexes.

Here is a complete example using your data:

```<code>from io import StringIO
import pandas as pd

File1txt=StringIO("""ID Number   Value 1     Value 2     Country
0001        23            55        Spain
0231        15            23        USA
4213        10            11        Canada
7541        32            29        Italy""")

File2txt = StringIO("""0001        5       6
0231        7       18
4213        54      87
5554        12      10
1111        31      13
6422        66      51""")

df1 = pd.read_csv(File1txt, sep='\s\s+', engine='python')
df2 = pd.read_csv(File2txt, sep='\s\s+', header=None, engine='python')

print(df1)
#    ID Number  Value 1  Value 2 Country
# 0          1       23       55   Spain
# 1        231       15       23     USA
# 2       4213       10       11  Canada
# 3       7541       32       29   Italy

print(df2)
#       0   1   2
# 0     1   5   6
# 1   231   7  18
# 2  4213  54  87
# 3  5554  12  10
# 4  1111  31  13
# 5  6422  66  51

df2 = df2.set_index(0).rename_axis('ID Number')
df2 = df2.rename(columns={1:'Value 1', 2: 'Value 2'})
df1 = df1.set_index('ID Number')
df1.update(df2)
print(df1.reset_index())
</code>```

Output:

```<code>   ID Number  Value 1  Value 2 Country
0          1      5.0      6.0   Spain
1        231      7.0     18.0     USA
2       4213     54.0     87.0  Canada
3       7541     32.0     29.0   Italy
</code>```

Body:
There are two files. If the ID number matches both files, then I want only the value 1 and value 2 from File2.txt , Please let me know if my question is unclear

File1.txt

ID Number   Value 1     Value 2     Country
0001        23            55        Spain
0231        15            23        USA
4213        10            11        Canada
7541        32            29        Italy

File2.txt

0001        5       6
0231        7       18
4213        54      87
5554        12      10
1111        31      13
6422        66      51

The output should look like this.

ID Number   Value 1     Value 2     Country
0001          5           6         Spain
0231          7          18         USA
4213          54         87         Canada
7541          32         29         Italy

New example:

File3.txt

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.739000  -114.635700
01711 CX 21 --   3  32.779700  -115.567500
08433 CX 21 --   2  31.919930  -123.321000

File4.txt

20022,32.45,-114.88
01192,32.839,-115.487
01711,32.88,-115.45
01218,32.717,-115.637

output
#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000

Code I got so far

f = open("File3.txt", "r")
x= open("File4.txt","r")

df1 = pd.read_csv(f, sep=' ', engine='python')
df2 = pd.read_csv(x, sep=' ', header=None, engine='python')

df2 = df2.set_index(0).rename_axis("#ID")
df2 = df2.rename(columns={5:'LATITUDE', 6: 'LONGITUDE'})
df1 = df1.set_index('#ID')
df1.update(df2)
print(df1)

Body:
Okay, what you need to do here is to get the indexes to match in both dataframes after importing.  This is important because pandas use data alignment based on indexes.

Here is a complete example using your data:

from io import StringIO
import pandas as pd

File1txt=StringIO("""ID Number   Value 1     Value 2     Country
0001        23            55        Spain
0231        15            23        USA
4213        10            11        Canada
7541        32            29        Italy""")

File2txt = StringIO("""0001        5       6
0231        7       18
4213        54      87
5554        12      10
1111        31      13
6422        66      51""")

df1 = pd.read_csv(File1txt, sep='\s\s+', engine='python')
df2 = pd.read_csv(File2txt, sep='\s\s+', header=None, engine='python')

print(df1)
#    ID Number  Value 1  Value 2 Country
# 0          1       23       55   Spain
# 1        231       15       23     USA
# 2       4213       10       11  Canada
# 3       7541       32       29   Italy

print(df2)
#       0   1   2
# 0     1   5   6
# 1   231   7  18
# 2  4213  54  87
# 3  5554  12  10
# 4  1111  31  13
# 5  6422  66  51

df2 = df2.set_index(0).rename_axis('ID Number')
df2 = df2.rename(columns={1:'Value 1', 2: 'Value 2'})
df1 = df1.set_index('ID Number')
df1.update(df2)
print(df1.reset_index())

Output:

   ID Number  Value 1  Value 2 Country
0          1      5.0      6.0   Spain
1        231      7.0     18.0     USA
2       4213     54.0     87.0  Canada
3       7541     32.0     29.0   Italy


问:
Can these two LINQ-to-SQL queries be combined?
I have two tables, Exam and ExamGroup which have a *:* relationship. I am given a List<Exam> and need to determine if an ExamGroup for this list already exists. So the provided list might be A+B+C, ExamGroups will contain, A+B, A+C, A+B+C+D+E, etc. and I need to determine if A+B+C exists and create it if it doesn't. The code below seems to do it but I'm wondering if it's possible to do it in a single expression?

var givenExams = /* Provided list of exams */
var examGroup = _context
    .ExamGroups
    .Include(x => x.ExamGroupsExam) // Mapping table for EF Core
    .ThenInclude(y => y.Exam)
    .AsEnumerable();

examGroup = givenExams.Aggregate(
    examGroup,
    (current, exam) => current.Where(x => x.Exams.Contains(exam)));
```

At this point examGroup is either the relevant group (which has an ID and other fields I care about) or null, at which point I know to create it.

答:
Yes it is possible. You need to use only the ExamGroupsExam table to determine it. Please filter down the ExamGroupsExam table by ExamId (using givenExams list) inside a sub query and then group the ExamId by the ExamGroupId. From this point, the query can identify the number of exams in that group. If this number is matching with the number of items in the givenExams then the group is exists if not you can create it. :)

I did create a query from top of my head, hopefully it will help you move forward:

```<code>var examGroupExists = (from examGroupsExam in _context.ExamGroupsExam
                     where (from examGroupsExam in _context.ExamGroupsExam
                            where givenExams.Any(x => x.Id == examGroupsExam.ExamId)
                            select examGroupsExam.ExamGroupId).Any(x == examGroupsExam.ExamGroupId)
                     group examGroupsExam.ExamId by examGroupsExam.ExamGroupId
                     into examGroup
                     select new {
                        NumberOfExamsInGroup = examGroup.Count(),
                        ExamGroupId = examGroup.Key
                     }).Any(x => x.NumberOfExamsInGroup == givenExams.Count);

if (examGroupExists == false)
{
    // then create it
}
</code>```

EDIT: I've noticed there was a bug in the first query, so I've changed it above and added a subquery. Basically the bug was: if A + B + C + D exam was one group then if you were looking for A + B + C group is returned true, with the sub select this should work okay.

Body:
I have two tables, Exam and ExamGroup which have a *:* relationship. I am given a List<Exam> and need to determine if an ExamGroup for this list already exists. So the provided list might be A+B+C, ExamGroups will contain, A+B, A+C, A+B+C+D+E, etc. and I need to determine if A+B+C exists and create it if it doesn't. The code below seems to do it but I'm wondering if it's possible to do it in a single expression?

var givenExams = /* Provided list of exams */
var examGroup = _context
    .ExamGroups
    .Include(x => x.ExamGroupsExam) // Mapping table for EF Core
    .ThenInclude(y => y.Exam)
    .AsEnumerable();

examGroup = givenExams.Aggregate(
    examGroup,
    (current, exam) => current.Where(x => x.Exams.Contains(exam)));

At this point examGroup is either the relevant group (which has an ID and other fields I care about) or null, at which point I know to create it.

Body:
Yes it is possible. You need to use only the ExamGroupsExam table to determine it. Please filter down the ExamGroupsExam table by ExamId (using givenExams list) inside a sub query and then group the ExamId by the ExamGroupId. From this point, the query can identify the number of exams in that group. If this number is matching with the number of items in the givenExams then the group is exists if not you can create it. :)

I did create a query from top of my head, hopefully it will help you move forward:

var examGroupExists = (from examGroupsExam in _context.ExamGroupsExam
                     where (from examGroupsExam in _context.ExamGroupsExam
                            where givenExams.Any(x => x.Id == examGroupsExam.ExamId)
                            select examGroupsExam.ExamGroupId).Any(x == examGroupsExam.ExamGroupId)
                     group examGroupsExam.ExamId by examGroupsExam.ExamGroupId
                     into examGroup
                     select new {
                        NumberOfExamsInGroup = examGroup.Count(),
                        ExamGroupId = examGroup.Key
                     }).Any(x => x.NumberOfExamsInGroup == givenExams.Count);

if (examGroupExists == false)
{
    // then create it
}

EDIT: I've noticed there was a bug in the first query, so I've changed it above and added a subquery. Basically the bug was: if A + B + C + D exam was one group then if you were looking for A + B + C group is returned true, with the sub select this should work okay.


问:
JavaScript ES6: Test for arrow function, built-in function, regular function?
Is there an elegant way to tell Harmony's slim arrow functions apart from regular functions and built-in functions?

The Harmony wiki states that:

Arrow functions are like built-in functions in that both lack .prototype and any [[Construct]] internal method. So new (() => {}) throws a TypeError but otherwise arrows are like functions

Which means, you can test for arrow functions like:

```<code>!(()=>{}).hasOwnProperty("prototype") // true
!(function(){}).hasOwnProperty("prototype") // false
</code>```

But the test will also return true for any built-in function, e.g. setTimeout or Math.min.

It sort of works in Firefox if you get the source code and check if it's "native code", but it doesn't seem much reliable nor portable (other browser implementations, NodeJS / iojs):

```<code>setTimeout.toSource().indexOf("[native code]") > -1
</code>```

The small GitHub project node-is-arrow-function relies on RegExp-checks against the function source code, which isn't that neat.

edit: I gave the JavaScript parser acorn a try and it seems to work quite okay - even though it's pretty overkill.

```<code>acorn = require("./acorn");

function fn_sample(a,b){
    c = (d,e) => d-e;
    f = c(--a, b) * (b, a);
    return f;
}

function test(fn){
    fn = fn || fn_sample;
    try {
        acorn.parse("(" + fn.toString() + ")", {
            ecmaVersion: 6,
            onToken: function(token){
                if(typeof token.type == "object" && token.type.type == "=>"){
                    console.log("ArrowFunction found", token);
                }
            }
        });
    } catch(e) {
        console.log("Error, possibly caused by [native code]");
        console.log(e.message);
    }
}

exports.test = test;
</code>```

答:
Based documentation on mozilla.org and taking into account side effects of Use of the new operator and that page we could try to do something like:

function isArrow (fn) {
  if (typeof fn !== 'function') return false
  try {
    new fn()
  } catch(err) {
   if(err.name === 'TypeError' && err.message === 'fn is not a constructor') {
    return true
   }
  }
  return false
}

console.log(isArrow(()=>{})) // true
console.log(isArrow(function () {})) // false
console.log(isArrow({})) // false
console.log(isArrow(1)) // false

let hacky = function () { throw new TypeError('fn is not a constructor') }
console.log(isArrow(hacky)) // unfortunately true```

Body:
Is there an elegant way to tell Harmony's slim arrow functions apart from regular functions and built-in functions?

The Harmony wiki states that:

Arrow functions are like built-in functions in that both lack .prototype and any [[Construct]] internal method. So new (() => {}) throws a TypeError but otherwise arrows are like functions

Which means, you can test for arrow functions like:

!(()=>{}).hasOwnProperty("prototype") // true
!(function(){}).hasOwnProperty("prototype") // false

But the test will also return true for any built-in function, e.g. setTimeout or Math.min.

It sort of works in Firefox if you get the source code and check if it's "native code", but it doesn't seem much reliable nor portable (other browser implementations, NodeJS / iojs):

setTimeout.toSource().indexOf("[native code]") > -1

The small GitHub project node-is-arrow-function relies on RegExp-checks against the function source code, which isn't that neat.

edit: I gave the JavaScript parser acorn a try and it seems to work quite okay - even though it's pretty overkill.

acorn = require("./acorn");

function fn_sample(a,b){
    c = (d,e) => d-e;
    f = c(--a, b) * (b, a);
    return f;
}

function test(fn){
    fn = fn || fn_sample;
    try {
        acorn.parse("(" + fn.toString() + ")", {
            ecmaVersion: 6,
            onToken: function(token){
                if(typeof token.type == "object" && token.type.type == "=>"){
                    console.log("ArrowFunction found", token);
                }
            }
        });
    } catch(e) {
        console.log("Error, possibly caused by [native code]");
        console.log(e.message);
    }
}

exports.test = test;


问:
get enabled user from OU
How would I add filter on this to query only enable users ? </p>

```<code>(Get-ADUser -Filter * -SearchBase “ou=Users,dc=qq,dc=com”).count
</code>```

答:
Just tell it to look at the Enabled property in the -Filter parameter:

```<code>(Get-ADUser -Filter "Enabled -eq $true" -SearchBase "ou=Users,dc=qq,dc=com").Count
</code>```

Note that there is no Enabled attribute in AD itself. But PowerShell exposes an Enabled property that maps to the value in AD (the userAccountControl attribute). The actual LDAP query this gets translated to looks something like this:

```<code>(Get-ADUser -LDAPFilter "(!userAccountControl:1.2.840.113556.1.4.803:=2)" -SearchBase "ou=Users,dc=qq,dc=com").Count
</code>```

So PowerShell simplifies it a bit for you.

Title: get enabled user from OU

Body:
How would I add filter on this to query only enable users ?

(Get-ADUser -Filter * -SearchBase “ou=Users,dc=qq,dc=com”).count

Body:
Just tell it to look at the Enabled property in the -Filter parameter:

(Get-ADUser -Filter "Enabled -eq $true" -SearchBase "ou=Users,dc=qq,dc=com").Count

Note that there is no Enabled attribute in AD itself. But PowerShell exposes an Enabled property that maps to the value in AD (the userAccountControl attribute). The actual LDAP query this gets translated to looks something like this:

(Get-ADUser -LDAPFilter "(!userAccountControl:1.2.840.113556.1.4.803:=2)" -SearchBase "ou=Users,dc=qq,dc=com").Count

So PowerShell simplifies it a bit for you.


问:
how to save the result of a function in javascript?
I have a function that adds a CSS class to all "a" selectors when I click on the button, unfortunately when I refresh the page or go to another tab its result is lost and I have to click on the button again. How can I fix this?

JS code:

```<code>function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.classList.toggle("underline-links"));
}
</code>```

CSS:

```<code>.underline-links {
    text-decoration: underline!important; }
</code>```

答:
Actually jquery function in this case is applied only on click. From it's name --> "on click" means that it will function only when the button is clicked, and will lose the changes when refreshed.

In order to keep the css style changed when button is clicked you can use the following :

JS Local Storage . If you need to store the data for the specific browser only.

PHP & AJAX (Post/Get) with a condition (e.g: sql condition), if you want to keep the change permanently unless another condition occurs.

edit: In 2. ,you can use php&jquery alone without the use of ajax get/post methods

Body:
I have a function that adds a CSS class to all "a" selectors when I click on the button, unfortunately when I refresh the page or go to another tab its result is lost and I have to click on the button again. How can I fix this?

JS code:

function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.classList.toggle("underline-links"));
}

CSS:

.underline-links {
    text-decoration: underline!important; }


问:
How to Trigger child method in ReactJS Functional Component
I have some inline edit fields, clicking on save should trigger child method which executes the API call with other properties. Currently using useState to set the flag, but it is working only once, if I resubmit it is not working, instead I want to use the method.</p>

答:
Just wanted to add an answer that works with useState repeatedly.  The trick is to use a ever-changing value instead of a boolean and take your action when the value changes:</p>

```<code>function Parent() {
  const [signal, setSignal] = useState()

  const onClick = () => setSignal(Date.now()) // trigger the child to save

  return (
    <div>
      <Child signal={signal} />
      <button onClick={onClick}>Save</button>
    </div>
  }
}

function Child({signal}) {
  // send the data whenever signal changes
  useEffect(() => {
    if (signal != null) {
      sendData()
    }
  }, [signal])

  return <div>...</div>
}
</code>```

Body:
Just wanted to add an answer that works with useState repeatedly.  The trick is to use a ever-changing value instead of a boolean and take your action when the value changes:

function Parent() {
  const [signal, setSignal] = useState()

  const onClick = () => setSignal(Date.now()) // trigger the child to save

  return (
    <div>
      <Child signal={signal} />
      <button onClick={onClick}>Save</button>
    </div>
  }
}

function Child({signal}) {
  // send the data whenever signal changes
  useEffect(() => {
    if (signal != null) {
      sendData()
    }
  }, [signal])

  return <div>...</div>
}


问:
Add boxes with descriptive annotations to y-axis in ggplot2
I"M trying to add another label or description to my Y axis.  I attached a picture for reference for what I'm trying to accomplish.  I can't find anything that describes how to add additional elements to an axis.  It the "Good" and "Bad" boxes beside the Y axis that I"m trying to incorporate into my ggplot.  Thanks!

enter image description here

答:
One approach to achieve this is by using patchwork. You can set up the annotations of the y-axis as a second ggplot and glue it to your main plot using patchwork. Try this:

library(ggplot2)
library(patchwork)
library(dplyr)

p1 <- tibble(x = 1:10, y = 1:10) %>%
  ggplot(aes(x, y)) +
  geom_point() +
  scale_y_reverse(breaks = seq(1, 10)) +
  labs(y = NULL)

p2 <- tibble(ymin = c(0, 4), ymax = c(4, 10), fill = c("bad", "good")) %>%
  ggplot() +
  geom_rect(aes(xmin = 0, xmax = 1, ymin = ymin, ymax = ymax, fill = fill)) +
  geom_text(aes(x = .5, y = (ymin  + ymax) / 2, label = fill), angle = 90) +
  scale_y_reverse(breaks = seq(1, 10), expand = expansion(mult = c(0, 0))) +
  scale_x_continuous(breaks = c(0), expand = expansion(mult = c(0, 0))) +
  guides(fill = FALSE) +
  theme_void()

p2 + p1 + plot_layout(widths = c(1, 9))
```

Created on 2020-05-28 by the reprex package (v0.3.0)

Body:
One approach to achieve this is by using patchwork. You can set up the annotations of the y-axis as a second ggplot and glue it to your main plot using patchwork. Try this:

library(ggplot2)
library(patchwork)
library(dplyr)

p1 <- tibble(x = 1:10, y = 1:10) %>%
  ggplot(aes(x, y)) +
  geom_point() +
  scale_y_reverse(breaks = seq(1, 10)) +
  labs(y = NULL)

p2 <- tibble(ymin = c(0, 4), ymax = c(4, 10), fill = c("bad", "good")) %>%
  ggplot() +
  geom_rect(aes(xmin = 0, xmax = 1, ymin = ymin, ymax = ymax, fill = fill)) +
  geom_text(aes(x = .5, y = (ymin  + ymax) / 2, label = fill), angle = 90) +
  scale_y_reverse(breaks = seq(1, 10), expand = expansion(mult = c(0, 0))) +
  scale_x_continuous(breaks = c(0), expand = expansion(mult = c(0, 0))) +
  guides(fill = FALSE) +
  theme_void()

p2 + p1 + plot_layout(widths = c(1, 9))

Created on 2020-05-28 by the reprex package (v0.3.0)


问:
Eloquent relationship not working in mail
I have an Order, Product and OrderProduct model. The Order has a belongsToMany relationship with Products as in

```<code>public function products(){
        return $this->belongsToMany('App\Product')->withPivot('group');
}
</code>```

So a user creates an order into the database:

```<code>$order = Order::create([
                    'order_id' => $payment->metadata->order_id,
                    'user_email' => $request ->email,
]);
</code>```

and we also save the products (note they have the same order_id as Order):

```<code>foreach (Cart::content() as $item){
                    OrderProduct::create([
                        'order_id' => $payment->metadata->order_id,
                        'product_id' =>$item->model->id,
                        'group' => $item->options->group,
                    ]);
                }
</code>```

So then I want to send an e-mail with the Order information and the Products information retrieved from the DB, this is in my webhook file and when the payment is paid, an email is sent:

```<code>      //Let's send an email.
      $order = Order::where('order_id', '=', $payment->metadata->order_id)->firstOrFail();
      Mail::send (new OrderPlaced ($order));
</code>```

The email shows all the order information like order_id and user_email in my view through the output {{$order->order_id}} and {{$order->user_email}} but I don't see the products when I try to loop through them with:

```<code>@foreach ($order->products as $product) {{$product->name}} @endforeach
</code>```

It just returns nothing, no error, nothing. A dd ($product) returns nothing. What am I overlooking here?

My thoughts:

 1. I am not using id as a primary key, so maybe I need to specify second and third arguments in the belongsToMany relationship?

 2. The $order variable defined prior to Mail, maybe I can't get the relationship through here?

答:
in order to have the products relation data, you must load it first:

```<code> $order = Order::with('products')->where('order_id', '=',$payment->metadata->order_id)->firstOrFail();
</code>```

more details about loading relation in:

https://laravel.com/docs/7.x/eloquent-relationships#eager-loading

Body:
I have an Order, Product and OrderProduct model. The Order has a belongsToMany relationship with Products as in

public function products(){
        return $this->belongsToMany('App\Product')->withPivot('group');
}

So a user creates an order into the database:

$order = Order::create([
                    'order_id' => $payment->metadata->order_id,
                    'user_email' => $request ->email,
]);

and we also save the products (note they have the same order_id as Order):

foreach (Cart::content() as $item){
                    OrderProduct::create([
                        'order_id' => $payment->metadata->order_id,
                        'product_id' =>$item->model->id,
                        'group' => $item->options->group,
                    ]);
                }

So then I want to send an e-mail with the Order information and the Products information retrieved from the DB, this is in my webhook file and when the payment is paid, an email is sent:

      //Let's send an email.
      $order = Order::where('order_id', '=', $payment->metadata->order_id)->firstOrFail();
      Mail::send (new OrderPlaced ($order));

The email shows all the order information like order_id and user_email in my view through the output {{$order->order_id}} and {{$order->user_email}} but I don't see the products when I try to loop through them with:

@foreach ($order->products as $product) {{$product->name}} @endforeach

It just returns nothing, no error, nothing. A dd ($product) returns nothing. What am I overlooking here?

My thoughts:

 1. I am not using id as a primary key, so maybe I need to specify second and third arguments in the belongsToMany relationship?

 2. The $order variable defined prior to Mail, maybe I can't get the relationship through here?

Body:
in order to have the products relation data, you must load it first:

 $order = Order::with('products')->where('order_id', '=',$payment->metadata->order_id)->firstOrFail();

more details about loading relation in:

https://laravel.com/docs/7.x/eloquent-relationships#eager-loading


问:
How to check if a string contains exactly two words in an SQL query?
I need to execute a simple SQL query that will only select those names that are made up of exactly two words</p>

```<code>SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>
</code>```

答:
Another option is using LEN() (of course, I assume there are no trailing spaces):

```<code>SELECT [NAME]
FROM [GROUP]
WHERE LEN([NAME]) - LEN(REPLACE([NAME], ' ', '')) = 1
</code>```

If the data in the NAME column has trailing space, you may use TRIM (for SQL Server 2017+) or a combination of LTRIM() and RTRIM() for earlier versions:

```<code>SELECT [NAME]
FROM [GROUP]
WHERE LEN(TRIM([NAME])) - LEN(REPLACE(TRIM([NAME]), ' ', '')) = 1
</code>```

Body:
I need to execute a simple SQL query that will only select those names that are made up of exactly two words

SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>

Body:
Another option is using LEN() (of course, I assume there are no trailing spaces):

SELECT [NAME]
FROM [GROUP]
WHERE LEN([NAME]) - LEN(REPLACE([NAME], ' ', '')) = 1

If the data in the NAME column has trailing space, you may use TRIM (for SQL Server 2017+) or a combination of LTRIM() and RTRIM() for earlier versions:

SELECT [NAME]
FROM [GROUP]
WHERE LEN(TRIM([NAME])) - LEN(REPLACE(TRIM([NAME]), ' ', '')) = 1


问:
Intuitive problem with k-fold cross validation
I have some intuitive problems with checking prediction power with cross validation, I think I don't get the algorithm in 100%.
I want to tell my intuitive problems on example. Let k=5 (number of folds) and

```<code>library(caret)
x=runif(100)
z=rexp(100)
y=rnorm(100)
Q=data.frame(x,z,y)
train.control <- trainControl(method = "cv", number = 5)
train(y~x+z,method="lm",data=Q,trControl=train.control)
</code>```

And in output I got :

```<code>100 samples
  2 predictor

No pre-processing
Resampling: Cross-Validated (5 fold)
Summary of sample sizes: 80, 80, 80, 80, 80
Resampling results:

  RMSE      Rsquared   MAE
  1.032508  0.1272826  0.8213676

Tuning parameter 'intercept' was held constant at a value of TRUE
</code>```

and my questions are :

(1) why my sample was divided on subsamples with lengths : 80,80,80,80,80 instead of 20,20,20,20,20 ?
Length y,x and z is 100 not 400.

(2) algorithm is drawing just from x and z or from x and y and z ?

(3) what does the algorithm do after randomizing ? I cannot find anything about that in internet. I only saw that he calculates RMSE and MAE. But for example MAE calculates absolute value of differences between y and y.hat. I believe that h.hat are values predictive by model y~x+z (for example if i draw x=0.05 and z=0.16 then y.hat=0.21). But I have no idea what is the y for those draw numbers and I can't imagine possibility to choose correct one.

Please, can you answer my intuitive problems or just give me some good page to read about it ? In all pages I did read I couldn't find solutions to my problems. Thank you in advance.

答:
5 fold CV means you divide the data in 5 parts, train 4 parts and test on 1 remaining part. Hence you train on 80 and test on remaining 20. And you do this 5 times for different 20s. You can check out this vignette on cross-validation, i basically grab a diagram from there:

It samples the rows of your data frame. The x y and z has to go together and cannot be sampled independently, otherwise it's quite nonsense right.

You specified method="lm" and y~x+z so you fitted a linear model with y as the dependent variable and x and z as independent variable. Every time you draw a sample of 80, the coefficient of the model will (should) be different because of the samples draw. You predict the values for the test set and calculate the errors , RMSE or MAE. And after 5 rounds, we have the RMSE or MAE for 5 test sets and we take an average. Normally we do this iteratively for different hyper paramaters of a model to choose the best paramter, based on lowest error. But in your example, there is no hyper parameter to tune. You can check this nice introduction to statistical learning textbook

Body:
I have some intuitive problems with checking prediction power with cross validation, I think I don't get the algorithm in 100%.
I want to tell my intuitive problems on example. Let k=5 (number of folds) and

library(caret)
x=runif(100)
z=rexp(100)
y=rnorm(100)
Q=data.frame(x,z,y)
train.control <- trainControl(method = "cv", number = 5)
train(y~x+z,method="lm",data=Q,trControl=train.control)

And in output I got :

100 samples
  2 predictor

No pre-processing
Resampling: Cross-Validated (5 fold)
Summary of sample sizes: 80, 80, 80, 80, 80
Resampling results:

  RMSE      Rsquared   MAE
  1.032508  0.1272826  0.8213676

Tuning parameter 'intercept' was held constant at a value of TRUE

and my questions are :

(1) why my sample was divided on subsamples with lengths : 80,80,80,80,80 instead of 20,20,20,20,20 ?
Length y,x and z is 100 not 400.

(2) algorithm is drawing just from x and z or from x and y and z ?

(3) what does the algorithm do after randomizing ? I cannot find anything about that in internet. I only saw that he calculates RMSE and MAE. But for example MAE calculates absolute value of differences between y and y.hat. I believe that h.hat are values predictive by model y~x+z (for example if i draw x=0.05 and z=0.16 then y.hat=0.21). But I have no idea what is the y for those draw numbers and I can't imagine possibility to choose correct one.

Please, can you answer my intuitive problems or just give me some good page to read about it ? In all pages I did read I couldn't find solutions to my problems. Thank you in advance.


问:
MySQL licensing and GPL
As far as I know, when I build a desktop/server app using any GPL code like MySQL I will have to release the source code of my software under the GPL.

If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Must I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

答:
Provided that you keep it server-only(and therefore "private"), you don't have to release it as GPL.
But as soon as it reaches public desktops, it can no longer be considered an internal build, and therefore source code is needed.

So you can:

Release your code as GPL

Buy the commercial version of MySQL

Keep it server-only.

ContentLicense: CC BY-SA 2.5

Title: MySQL licensing and GPL

LastEditorDisplayName: Roger Pate

OwnerDisplayName: luiscubal


问:
Am getting gibberish when i run code on laravel query
I am new to laravel and I am practicing with laravel 7 by following an online tutorial featuring the query builder. Everything worked fine, until I got to the code to join the 2 table. Products and Users.

Initially I received a complaint with regards to the memory. I googled and found a solution, which I implemented on my php.ini file. Then, after running the script again, I got a page full of gibberish which I cannot make sense of.
Here is my controller where I am running the query:

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Profile extends Controller
{
function index(){

        $data = DB::table('users')->join('products','users.id','products.user_id');

        print_r($data);
</code>```

And here is my router

```<code>Route::get('/', function () {
    return view('welcome');
});
Route::get('profile','Profile@index');
</code>```

This is the response I received when I visited the profile page.

```<code>Illuminate\Database\Query\Builder Object ( [connection] => Illuminate\Database\MySqlConnection Object ( [pdo:protected] => Closure Object ( [static] => Array ( [config] => Array ( [driver] => mysql [host] => 127.0.0.1 [port] => 3306 [database] => lara7 [username] => root [password] => godly123 [unix_socket] => [charset] => utf8mb4 [collation] => utf8mb4_unicode_ci [prefix] => [prefix_indexes] => 1 [strict] => 1 [engine] => [options] => Array ( ) [name] => mysql ) ) [this] => Illuminate\Database\Connectors\ConnectionFactory Object ( [container:protected] => Illuminate\Foundation\Application Object ( [basePath:protected] => C:\newxampp\htdocs\lara7 [hasBeenBootstrapped:protected] => 1 [booted:protected] => 1 [bootingCallbacks:protected] => Array ( [0] => Closure Object ( [static] => Array ( [instance] => Illuminate\Queue\QueueServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) ) [this] => Illuminate\Foundation\Application Object *RECURSION* ) ) [bootedCallbacks:protected] => Array ( [0] => Closure Object ( [this] => App\Providers\RouteServiceProvider Object ( [namespace:protected] => App\Http\Controllers [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) ) ) [terminatingCallbacks:protected] => Array ( ) [serviceProviders:protected] => Array ( [0] => Illuminate\Events\EventServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [1] => Illuminate\Log\LogServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [2] => Illuminate\Routing\RoutingServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [3] => Illuminate\Auth\AuthServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [4] => Illuminate\Cookie\CookieServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [5] => Illuminate\Database\DatabaseServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [6] => Illuminate\Encryption\EncryptionServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [7] => Illuminate\Filesystem\FilesystemServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [8] => Illuminate\Foundation\Providers\FormRequestServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [9] =>
</code>```

etc etc

答:
Please append ->get(); after DB::table('users')->join('products','users.id','products.user_id').

DB::table('users')->join('products','users.id','products.user_id')->get();
```

This is happening because its returning an instance of query builder (this is what allows you to chain more conditions onto it). In order to actually execute a query, you need to chain a method that does so (like get() or first())

Body:
I am new to laravel and I am practicing with laravel 7 by following an online tutorial featuring the query builder. Everything worked fine, until I got to the code to join the 2 table. Products and Users.

Initially I received a complaint with regards to the memory. I googled and found a solution, which I implemented on my php.ini file. Then, after running the script again, I got a page full of gibberish which I cannot make sense of.
Here is my controller where I am running the query:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Profile extends Controller
{
function index(){

        $data = DB::table('users')->join('products','users.id','products.user_id');

        print_r($data);

And here is my router

Route::get('/', function () {
    return view('welcome');
});
Route::get('profile','Profile@index');

This is the response I received when I visited the profile page.

Illuminate\Database\Query\Builder Object ( [connection] => Illuminate\Database\MySqlConnection Object ( [pdo:protected] => Closure Object ( [static] => Array ( [config] => Array ( [driver] => mysql [host] => 127.0.0.1 [port] => 3306 [database] => lara7 [username] => root [password] => godly123 [unix_socket] => [charset] => utf8mb4 [collation] => utf8mb4_unicode_ci [prefix] => [prefix_indexes] => 1 [strict] => 1 [engine] => [options] => Array ( ) [name] => mysql ) ) [this] => Illuminate\Database\Connectors\ConnectionFactory Object ( [container:protected] => Illuminate\Foundation\Application Object ( [basePath:protected] => C:\newxampp\htdocs\lara7 [hasBeenBootstrapped:protected] => 1 [booted:protected] => 1 [bootingCallbacks:protected] => Array ( [0] => Closure Object ( [static] => Array ( [instance] => Illuminate\Queue\QueueServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) ) [this] => Illuminate\Foundation\Application Object *RECURSION* ) ) [bootedCallbacks:protected] => Array ( [0] => Closure Object ( [this] => App\Providers\RouteServiceProvider Object ( [namespace:protected] => App\Http\Controllers [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) ) ) [terminatingCallbacks:protected] => Array ( ) [serviceProviders:protected] => Array ( [0] => Illuminate\Events\EventServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [1] => Illuminate\Log\LogServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [2] => Illuminate\Routing\RoutingServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [3] => Illuminate\Auth\AuthServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [4] => Illuminate\Cookie\CookieServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [5] => Illuminate\Database\DatabaseServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [6] => Illuminate\Encryption\EncryptionServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [7] => Illuminate\Filesystem\FilesystemServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [8] => Illuminate\Foundation\Providers\FormRequestServiceProvider Object ( [app:protected] => Illuminate\Foundation\Application Object *RECURSION* ) [9] =>

etc etc

Body:
Please append ->get(); after DB::table('users')->join('products','users.id','products.user_id').

DB::table('users')->join('products','users.id','products.user_id')->get();

This is happening because its returning an instance of query builder (this is what allows you to chain more conditions onto it). In order to actually execute a query, you need to chain a method that does so (like get() or first())


问:
Qt Creator Android error "Platform SDK installed"
I am developing Qt Cross platform application for Android, recently i have updated Qt creator and Installed new Qt version. I am using 'Qt Creator version 4.5.0'. I have updated to 'QT version 5.10'. This Set up is done on Ubuntu 16.04.

Followed link Getting Started with QT Installation.

I am always getting Error message "Android Settings have error" in Qt Creator->Tools->Options->Devices->Android.

Because of above issue i am not able to build application for Android.

I have recently updated my Android sdk, I am able to build and run Sample application from Android Studio, indicating that SDK instalation is working properly. I am using Android SDK tools 26.1.1. Please check bellow screen shots.

Android SDK build tools Installed.

Android SDk platforms installed

Already gone through different links on Stack Overflow and QT forum, All are Suggesting downgrade of Android SDK tools(Due to QT Known bug), but none of the solution is working for me. I know there are few known bugs building Android application with QT 5.9 and Qt Creator version 4.0. I guess It is resolved, as same set up is working fine on Windows 10.

QT Creator wont list any available Android Build SDKs
QT Android Installation error

Please help if anybody here resolved same issue.

答:
I just had the exact same symptoms as the OP. Just that unlike the OP, I was using Qt Creator 4.8.0, as provided in the Ubuntu 19.10 repositories.

Symptoms

The relevant part from the Qt Creator self-check list is:

✓  SDK tools installed.
X  Platform SDK installed.
```

<p>An additional symptom was that the "SDK Manager" tab below had this message:</p>

<blockquote>
  <p>SDK manager is not available with the current version of SDK tools. Use Native SDK Manager.</p>
</blockquote>

<h2>Cause and Fix</h2>

<p>The reason for this issue was a <strong>wrong version of SDK tools</strong>. That wrong version is recognized ("SDK tools installed.") but cannot be utilized by Qt Creator to detect which platform SDK is installed or to install new ones.</p>

<p>In my case, I had simply downloaded the latest version, provided as <code>commandlinetools-linux-*_latest.zip</code> on the Android Studio download page. That version introduced changes that are not backwards compatible with the interface of earlier versions that Qt Creator is expecting. That new package is indeed quite different: it has a different name (<code>commandlinetools</code> vs. <code>sdk-tools</code>), expects to be in a different place etc..</p>

<p>To solve this, download and install "Android SDK Tools 26.1.1" (rev. 4333796) as follows, supplying your own Android SDK directory of course:</p>

<pre class="lang-none prettyprint-override"><code>cd /opt/android-sdk/
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip
unzip sdk-tools-linux-4333796.zip
</code>```

That fixed all the symptoms described above.

Body:
I just had the exact same symptoms as the OP. Just that unlike the OP, I was using Qt Creator 4.8.0, as provided in the Ubuntu 19.10 repositories.

Symptoms

The relevant part from the Qt Creator self-check list is:

✓  SDK tools installed.
X  Platform SDK installed.

An additional symptom was that the "SDK Manager" tab below had this message:

SDK manager is not available with the current version of SDK tools. Use Native SDK Manager.

Cause and Fix

The reason for this issue was a wrong version of SDK tools. That wrong version is recognized ("SDK tools installed.") but cannot be utilized by Qt Creator to detect which platform SDK is installed or to install new ones.

In my case, I had simply downloaded the latest version, provided as commandlinetools-linux-*_latest.zip on the Android Studio download page. That version introduced changes that are not backwards compatible with the interface of earlier versions that Qt Creator is expecting. That new package is indeed quite different: it has a different name (commandlinetools vs. sdk-tools), expects to be in a different place etc..

To solve this, download and install "Android SDK Tools 26.1.1" (rev. 4333796) as follows, supplying your own Android SDK directory of course:

cd /opt/android-sdk/
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip
unzip sdk-tools-linux-4333796.zip

That fixed all the symptoms described above.


问:
Reverse DNS lookup in python returns wrong host
I am trying to use python sockets to get hostname of ip. But, by some reason, when I try to do this:

import socket
result = socket.gethostbyaddr('216.58.207.46')  # google ip address
print(result[0])
```

I get printed out this: fra16s24-in-f14.1e100.net.

How do I get it to print out google.com?

Update: I am trying to parse range of IP addresses, and then convert them into hostnames (if can be converted). Obviously, when I convert 3.126.***.192, I want to see an actual hostname, and not ec2-3-126-***-192.eu-central-1.compute.amazonaws.com.

How do I do that?

答:
Although what you are expecting is not in line with the result you are getting, the result you are getting from Python's standard socket.gethostbyaddr() is correct. Let's start by taking a look at what's happening and then work to align your expectations accordingly...

DNS utilities such as dig are your friend when working through problems like this, so I'll show output from dig as I work toward an answer for you.

Reverse DNS lookup is not necessarily a one to one relationship, as others have indicated in comments above. It relies on a convention wherein (using the IPv4 address above as an example) you issue a DNS query for a PTR record for the reversed IP address suffixed with .in-addr.arpa; in your case, this is 46.207.58.216.in-addr.arpa:

```<code>▶ dig 46.207.58.216.in-addr.arpa in ptr

; <<>> DiG 9.10.6 <<>> 46.207.58.216.in-addr.arpa in ptr
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23082
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;46.207.58.216.in-addr.arpa.    IN  PTR

;; ANSWER SECTION:
46.207.58.216.in-addr.arpa. 77579 IN    PTR fra16s24-in-f14.1e100.net.

;; Query time: 85 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Thu May 28 13:17:17 PDT 2020
;; MSG SIZE  rcvd: 83
</code>```

The DNS response here is a PTR record for fra16s24-in-f14.1e100.net which is perfectly in line with what you are seeing when you use Python's socket.gethostbyaddr().

While it may be true that you associate this host with something related to google.com conceptually, it may not be tied to anything related to the google.com top level domain as far as DNS is concerned.

Edit (based on your update):

Obviously, when I convert 3.126.***.192, I want to see an actual hostname, and not ec2-3-126-***-192.eu-central-1.compute.amazonaws.com.

In the example you are giving here, you need to realize that ec2-3-126-***-192.eu-central-1.compute.amazonaws.com is an actual hostname. Take a look at the article I linked above about reverse DNS lookup and also take a look at a primer on how DNS works. It bears repeating that many address records may exist for a single name (and often this is the case for load balanced resources).

Here is an example of this for stackoverflow.com:

```<code>▶ dig stackoverflow.com in a

; <<>> DiG 9.10.6 <<>> stackoverflow.com in a
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 51644
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;stackoverflow.com.     IN  A

;; ANSWER SECTION:
stackoverflow.com.  106 IN  A   151.101.193.69
stackoverflow.com.  106 IN  A   151.101.129.69
stackoverflow.com.  106 IN  A   151.101.1.69
stackoverflow.com.  106 IN  A   151.101.65.69

;; Query time: 81 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Thu May 28 13:25:55 PDT 2020
;; MSG SIZE  rcvd: 99
</code>```

Should all of these IPs have PTR records that point back to stackoverflow.com? No, not necessarily... Let's look at one for an example:

```<code>▶ dig 69.193.101.151.in-addr.arpa in ptr

; <<>> DiG 9.10.6 <<>> 69.193.101.151.in-addr.arpa in ptr
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 418
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;69.193.101.151.in-addr.arpa.   IN  PTR

;; AUTHORITY SECTION:
151.in-addr.arpa.   3125    IN  SOA pri.authdns.ripe.net. dns.ripe.net. 1586415572 3600 600 864000 3600

;; Query time: 79 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Thu May 28 13:28:03 PDT 2020
;; MSG SIZE  rcvd: 116
</code>```

In this case, there are no PTR records when you perform a reverse DNS lookup on this IP address. So, how would Python's gethostbyaddr handle this case?

```<code>>>> socket.gethostbyaddr('151.101.193.69')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.herror: [Errno 1] Unknown host
</code>```

It raises an exception, in this case. If the DNS response has no reverse lookup PTR record, Python cannot really offer any further useful information.

If this answer is not clear enough, write back in a comment and I will amend this answer until everything is clear.

Body:
I am trying to use python sockets to get hostname of ip. But, by some reason, when I try to do this:

import socket
result = socket.gethostbyaddr('216.58.207.46')  # google ip address
print(result[0])

I get printed out this: fra16s24-in-f14.1e100.net.

How do I get it to print out google.com?

Update: I am trying to parse range of IP addresses, and then convert them into hostnames (if can be converted). Obviously, when I convert 3.126.***.192, I want to see an actual hostname, and not ec2-3-126-***-192.eu-central-1.compute.amazonaws.com.

How do I do that?

Body:
Although what you are expecting is not in line with the result you are getting, the result you are getting from Python's standard socket.gethostbyaddr() is correct. Let's start by taking a look at what's happening and then work to align your expectations accordingly...

DNS utilities such as dig are your friend when working through problems like this, so I'll show output from dig as I work toward an answer for you.

Reverse DNS lookup is not necessarily a one to one relationship, as others have indicated in comments above. It relies on a convention wherein (using the IPv4 address above as an example) you issue a DNS query for a PTR record for the reversed IP address suffixed with .in-addr.arpa; in your case, this is 46.207.58.216.in-addr.arpa:

▶ dig 46.207.58.216.in-addr.arpa in ptr

; <<>> DiG 9.10.6 <<>> 46.207.58.216.in-addr.arpa in ptr
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23082
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;46.207.58.216.in-addr.arpa.    IN  PTR

;; ANSWER SECTION:
46.207.58.216.in-addr.arpa. 77579 IN    PTR fra16s24-in-f14.1e100.net.

;; Query time: 85 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Thu May 28 13:17:17 PDT 2020
;; MSG SIZE  rcvd: 83

The DNS response here is a PTR record for fra16s24-in-f14.1e100.net which is perfectly in line with what you are seeing when you use Python's socket.gethostbyaddr().

While it may be true that you associate this host with something related to google.com conceptually, it may not be tied to anything related to the google.com top level domain as far as DNS is concerned.

Edit (based on your update):

Obviously, when I convert 3.126.***.192, I want to see an actual hostname, and not ec2-3-126-***-192.eu-central-1.compute.amazonaws.com.

In the example you are giving here, you need to realize that ec2-3-126-***-192.eu-central-1.compute.amazonaws.com is an actual hostname. Take a look at the article I linked above about reverse DNS lookup and also take a look at a primer on how DNS works. It bears repeating that many address records may exist for a single name (and often this is the case for load balanced resources).

Here is an example of this for stackoverflow.com:

▶ dig stackoverflow.com in a

; <<>> DiG 9.10.6 <<>> stackoverflow.com in a
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 51644
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;stackoverflow.com.     IN  A

;; ANSWER SECTION:
stackoverflow.com.  106 IN  A   151.101.193.69
stackoverflow.com.  106 IN  A   151.101.129.69
stackoverflow.com.  106 IN  A   151.101.1.69
stackoverflow.com.  106 IN  A   151.101.65.69

;; Query time: 81 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Thu May 28 13:25:55 PDT 2020
;; MSG SIZE  rcvd: 99

Should all of these IPs have PTR records that point back to stackoverflow.com? No, not necessarily... Let's look at one for an example:

▶ dig 69.193.101.151.in-addr.arpa in ptr

; <<>> DiG 9.10.6 <<>> 69.193.101.151.in-addr.arpa in ptr
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 418
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;69.193.101.151.in-addr.arpa.   IN  PTR

;; AUTHORITY SECTION:
151.in-addr.arpa.   3125    IN  SOA pri.authdns.ripe.net. dns.ripe.net. 1586415572 3600 600 864000 3600

;; Query time: 79 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Thu May 28 13:28:03 PDT 2020
;; MSG SIZE  rcvd: 116

In this case, there are no PTR records when you perform a reverse DNS lookup on this IP address. So, how would Python's gethostbyaddr handle this case?

>>> socket.gethostbyaddr('151.101.193.69')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.herror: [Errno 1] Unknown host

It raises an exception, in this case. If the DNS response has no reverse lookup PTR record, Python cannot really offer any further useful information.

If this answer is not clear enough, write back in a comment and I will amend this answer until everything is clear.


问:
Why string str = new string("abc") doesn't pass compiler?
Given public String(char*) why we cannot use the following statement?

```<code>string str = new string("aaa");
</code>```

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2

答:
Simply use:

```<code> string str = "aaa";
</code>```

You do not need to new a string.

"aaa" is a string.  It is not a char *.

char * is used with unsafe code.

Body:
Given public String(char*) why we cannot use the following statement?

string str = new string("aaa");

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2

Body:
Simply use:

 string str = "aaa";

You do not need to new a string.

"aaa" is a string.  It is not a char *.

char * is used with unsafe code.


问:
Spring boot 1.5.8 with jakson 2.10.0 object mapping issue
i have upgraded jakson api on spring boot 1.5.8 from jakson 2.8.0 to 2.10.0, since then mapping of object is behaving different.

when i am passing request body on springboot controller having propertyname cityCode
sample json

```<code>{
cityCode:DEL
}
</code>```

when adding jsonproperty mapping works fine

```<code>@JsonProperty("cityCode")
private String cityCode;
</code>```

but when i don't add @JsonProperty annotation
it looks for CityCode instead.
since json passed on request is

```<code>{
cityCode:DEL
}
</code>```

it assing

```<code>object{cityCode=null}
</code>```

please let me know if there is any property which i need to add on spring boot

because in most of my scenario i don't want to add @JsonProperty annotation to class fields

EDIT:

I enable log.level to trace i saw some message related to jackson

POJOPropertyBuilder - Unable to instantiate jackson 2.6 object. Using higher version of jackson.

EDIT2:

Adding Sample Model Class

```<code>import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(value = "CityRequest")
public class CityRequest implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty
    private String cityCode;

    @ApiModelProperty
    private String cityName;

    @ApiModelProperty
    private String area;

    @ApiModelProperty
    private List<String> areas;

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public List<String> getAreas() {
        return areas;
    }

    public void setAreas(List<String> areas) {
        this.areas = areas;
    }

    @Override
    public String toString() {
        return "CityRequest{" +
                "cityCode='" + cityCode + '\'' +
                ", cityName='" + cityName + '\'' +
                ", area='" + area + '\'' +
                ", areas=" + areas +
                '}';
    }
}
</code>```

on the controller method is being passed as

```<code>@ApiParam(value = "This field specifies the list of requests", required = true)
@Valid @RequestBody(required = true) CityRequest cityRequest
</code>```

答:
I haven't tried but maybe you can try changing the naming strategy to lowerCamelCase:

@JsonNaming(PropertyNamingStrategy.lowerCamelCase.class)
public class City {
    private String cityCode;
}
```

Body:
i have upgraded jakson api on spring boot 1.5.8 from jakson 2.8.0 to 2.10.0, since then mapping of object is behaving different.

when i am passing request body on springboot controller having propertyname cityCode
sample json

{
cityCode:DEL
}

when adding jsonproperty mapping works fine

@JsonProperty("cityCode")
private String cityCode;

but when i don't add @JsonProperty annotation
it looks for CityCode instead.
since json passed on request is

{
cityCode:DEL
}

it assing

object{cityCode=null}

please let me know if there is any property which i need to add on spring boot

because in most of my scenario i don't want to add @JsonProperty annotation to class fields

EDIT:

I enable log.level to trace i saw some message related to jackson

POJOPropertyBuilder - Unable to instantiate jackson 2.6 object. Using higher version of jackson.

EDIT2:

Adding Sample Model Class

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(value = "CityRequest")
public class CityRequest implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty
    private String cityCode;

    @ApiModelProperty
    private String cityName;

    @ApiModelProperty
    private String area;

    @ApiModelProperty
    private List<String> areas;

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public List<String> getAreas() {
        return areas;
    }

    public void setAreas(List<String> areas) {
        this.areas = areas;
    }

    @Override
    public String toString() {
        return "CityRequest{" +
                "cityCode='" + cityCode + '\'' +
                ", cityName='" + cityName + '\'' +
                ", area='" + area + '\'' +
                ", areas=" + areas +
                '}';
    }
}

on the controller method is being passed as

@ApiParam(value = "This field specifies the list of requests", required = true)
@Valid @RequestBody(required = true) CityRequest cityRequest


问:
How do I fix a clang: error: linker command failed with exit code 1 (use -v to see invocation)
I am trying to learn c++ but I cannot run a basic HelloWorld program.

Im am receiving an error saying
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

This is the code.

```<code> #include <iostream>

int main() {
    std::cout << "Hello World";

    return 0;
}
</code>```

答:
Nihal, If you are doing this work for a course, you should search/ask for instructions on how to successfully install the required environment.

If you are self-teaching, you might consider starting with an environment like repl.it (https://repl.it/). It's online, it's free, and if you ask it to create a C++ project for you, you will have everything you need to start with.

I use repl.it to teach my college-level C++ course. It works well for all the basic stuff, including file I/O.

Body:
I am trying to learn c++ but I cannot run a basic HelloWorld program.

Im am receiving an error saying
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

This is the code.

 #include <iostream>

int main() {
    std::cout << "Hello World";

    return 0;
}