问:
How to make multiplyList work? Haskell ref: https://en.wikibooks.org/wiki/Haskell/Lists_II
I am exercising the multiplyList function that uses applyToIntegers in GHCi.  I want it to multiply a list by 2. Below is what I tried and the error I got. Below that, for convenience, is an excerpt from Lists II.

The code in Lists II compiles OK. My problem is: where do I put the multiplier in the code?

I can use applyToIntegers by itself OK, and I can duplicate what it does using map. I just can't make the connection from multiplyList to applyToIntgers.

This is my first post as I am learning Haskell (which I had never heard of before last month!) from the excellent Haskell wikibook, and I must say that Haskell is the most beautiful high-level programming language I've ever encountered.

```<code>applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
-- E.g., applyToIntegers (2*) [1..5] = [2,4,6,8,10], also
-–  map (2*) [1..5] = [2,4,6,8,10]

-- Unable to come up with a working example:
multiplyList :: Integer -> [Integer] -> [Integer]
--multiplyList m = applyToIntegers ((*) m) -- Compiles OK.
-- If I try:
multiplyList m = applyToIntegers ((2*) m)
</code>```

I get the following:

```<code>*Main> :l ods.hs
[1 of 1] Compiling Main             ( ods.hs, interpreted )

ods.hs:15:35: error:
    • Couldn't match expected type ‘Integer -> Integer’
                  with actual type ‘Integer’
    • Possible cause: ‘2 *’ is applied to too many arguments
      In the first argument of ‘applyToIntegers’, namely ‘((2 *) m)’
      In the expression: applyToIntegers ((2 *) m)
      In an equation for ‘multiplyList’:
      multiplyList m = applyToIntegers ((2 *) m)
Failed, modules loaded: none.
Prelude>
</code>```

https://en.wikibooks.org/w/index.php?title=Haskell/Lists_II&oldid=3242682

We need a function that takes any other appropriate function and applies the

      given function to the elements of a list:

```<code>applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
</code>```

With applyToIntegers, we can take any Integer -> Integer function and apply
      it to the elements of a list of Integers. We can thus use this generalized
      function to redefine multiplyList:```<code>multiplyList :: Integer -> [Integer] -> [Integer]
multiplyList m = applyToIntegers ((*) m)</code>```

That uses the (*) function with a single initial argument to create a new
      function which is ready to take one more argument (which, in this use case,
      will come from the numbers in a given list).

答:
It's all about currying. (*) is a function with signature Integer -> Integer -> Integer. ((*) 2) generates a function with signature Integer -> Integer, that you can apply to a second number and get a product. This function is provided to applyToIntegers to produce a function multiplyList that will take a list as an argument. You could also see multiplyList as a function that takes two arguments, m, which is a number (e.g. 2), and a list.

So the compiler message is pretty on the spot, it's telling you applyToIntegers expected a function ((*) 2), but you provided a number (2*m). You must call it like

multiplyList 2 [1,2,3]

Just like in the previous example in the book chapter. This same function is just being rewritten in another way, where the arguments become implicit, "higher-order" style...

Body:
I am exercising the multiplyList function that uses applyToIntegers in GHCi.  I want it to multiply a list by 2. Below is what I tried and the error I got. Below that, for convenience, is an excerpt from Lists II.

The code in Lists II compiles OK. My problem is: where do I put the multiplier in the code?

I can use applyToIntegers by itself OK, and I can duplicate what it does using map. I just can't make the connection from multiplyList to applyToIntgers.

This is my first post as I am learning Haskell (which I had never heard of before last month!) from the excellent Haskell wikibook, and I must say that Haskell is the most beautiful high-level programming language I've ever encountered.

applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
-- E.g., applyToIntegers (2*) [1..5] = [2,4,6,8,10], also
-–  map (2*) [1..5] = [2,4,6,8,10]

-- Unable to come up with a working example:
multiplyList :: Integer -> [Integer] -> [Integer]
--multiplyList m = applyToIntegers ((*) m) -- Compiles OK.
-- If I try:
multiplyList m = applyToIntegers ((2*) m)

I get the following:

*Main> :l ods.hs
[1 of 1] Compiling Main             ( ods.hs, interpreted )

ods.hs:15:35: error:
    • Couldn't match expected type ‘Integer -> Integer’
                  with actual type ‘Integer’
    • Possible cause: ‘2 *’ is applied to too many arguments
      In the first argument of ‘applyToIntegers’, namely ‘((2 *) m)’
      In the expression: applyToIntegers ((2 *) m)
      In an equation for ‘multiplyList’:
      multiplyList m = applyToIntegers ((2 *) m)
Failed, modules loaded: none.
Prelude>

https://en.wikibooks.org/w/index.php?title=Haskell/Lists_II&oldid=3242682

We need a function that takes any other appropriate function and applies the

      given function to the elements of a list:

applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns

With applyToIntegers, we can take any Integer -> Integer function and apply
      it to the elements of a list of Integers. We can thus use this generalized
      function to redefine multiplyList:
multiplyList :: Integer -> [Integer] -> [Integer]
multiplyList m = applyToIntegers ((*) m)

That uses the (*) function with a single initial argument to create a new
      function which is ready to take one more argument (which, in this use case,
      will come from the numbers in a given list).


来源: stackexchange

问:
How can I achieve 8-bit graphics effect using Silverlight?
How can I achieve 8-bit graphics effect using Silverlight?

I want to make retro game for WP7 using Silverlight.

Should I use canvas and rectangle for this?

答: There is no built-in functionality for this. Since you are developing a game, you will have to create a custom layer engine that will be able to place colored rectangles in different zones of the screen, therefore achieving the desired effect.</p>

ContentLicense: CC BY-SA 2.5


问:
Docusign webhook message does not have way to differentiate different compositetemplate
I have created 1 envelope with 2 composite templates with embedded signing and I can hook it up with the webhook event notification to receive a message once users finish signing, so I can try to update my db and download the file. However, the webhook response does not have the custom fields that I need to identify which file belong to which for me to update the db row.

This is my json serialized envelope example. Notice the custom field on each inline template, that have the property of DocuInfoId. I will need the value of those to update my db row

```<code>{
  "status": "sent",
  "emailSubject": "DocuSign API - Template Example",
  "eventNotification": {
    "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available",
    "loggingEnabled": "false",
    "requireAcknowledgment": "true",
    "useSoapInterface": "false",
    "soapNameSpace": "",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "false",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "false",
    "includeDocumentFields": "false",
    "includeCertificateOfCompletion": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Sent",
        "includeDocuments": null
      },
      {
        "envelopeEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ],
    "recipientEvents": [
      {
        "recipientEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ]
  },
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just a bunch of text tabs, radio group, etc"
                }
              },
              {
                "clientUserId": "2",
                "recipientId": "2",
                "email": "testemail@test.com",
                "name": "Owner Name",
                "roleName": "Owner",
                "tabs": null
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "77",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "TemplateIDNumber1"
        }
      ]
    },
    {
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just another bunch of text tabs, radio group tab, etc"
                }
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "88",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "2",
          "templateId": "TemplateIDNumber2"
        }
      ]
    }
  ]
}
</code>```

And once I finished signing, the webhook event notification is triggered and called my api with this response message

```<code>{
  "EnvelopeStatus": {
    "EnvelopeID": "EnvelopeIDGivenByDocusign",
    "Status": "Completed",
    "CustomFields": [
      {
        "Name": "ContactID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "OpportunityID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "AccountID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "DocuInfoId",
        "Show": "False",
        "Required": "True",
        "Value": "88"
      },
      {
        "Name": "OpportunityId",
        "Show": "False",
        "Required": "True",
        "Value": "1"
      },
      {
        "Name": "LQAID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      }
    ],
    "DocumentStatuses": [
      {
        "ID": 1,
        "Name": "Document - TX - 1001.pdf",
        "TemplateName": "Document - TX",
        "Sequence": 1
      },
      {
        "ID": 2,
        "Name": "Rejection.pdf",
        "TemplateName": "Rejection Form",
        "Sequence": 2
      }
    ]
  },
  "DocumentPDFs": [
    {
      "Name": "Document - TX - 1001.pdf",
      "DocumentID": "1",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "Rejection.pdf",
      "DocumentID": "2",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "CertificateOfCompletion_78sd89fuas89sadf.pdf",
      "DocumentID": null,
      "DocumentType": "SUMMARY"
    }
  ]
}
</code>```

Looking at the response, there's only 1 docuinfoid with the value of 88, I'm also not sure where is the rest of custom field coming from e.g: "LQAID". Now, I'm not sure which docuinfoid is this belong to, the first pdf file (Document - TX - 1001.pdf) or the second pdf file (Rejection.pdf).

Is there anyway to know which pdf document belong to which docuinfoid, so that I can attach it to my database correctly?

答:
You can set compositeTemplateId for each CompositeTemplate and then use this Id in each envelope Custom Field. I have modified your JSON request to include CompositeTemplateId,

```<code>{
  "status": "sent",
  "emailSubject": "DocuSign API - Template Example",
  "eventNotification": {
    "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available",
    "loggingEnabled": "false",
    "requireAcknowledgment": "true",
    "useSoapInterface": "false",
    "soapNameSpace": "",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "false",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "false",
    "includeDocumentFields": "false",
    "includeCertificateOfCompletion": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Sent",
        "includeDocuments": null
      },
      {
        "envelopeEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ],
    "recipientEvents": [
      {
        "recipientEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ]
  },
  "compositeTemplates": [
    {
      "compositeTemplateId": "1",
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just a bunch of text tabs, radio group, etc"
                }
              },
              {
                "clientUserId": "2",
                "recipientId": "2",
                "email": "testemail@test.com",
                "name": "Owner Name",
                "roleName": "Owner",
                "tabs": null
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId_1",
                "required": "True",
                "show": "False",
                "value": "77",
                "listItems": null
              },
              {
                "name": "OpportunityId_1",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "TemplateIDNumber1"
        }
      ]
    },
    {
      "compositeTemplateId": "2",
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just another bunch of text tabs, radio group tab, etc"
                }
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId_2",
                "required": "True",
                "show": "False",
                "value": "88",
                "listItems": null
              },
              {
                "name": "OpportunityId_2",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "2",
          "templateId": "TemplateIDNumber2"
        }
      ]
    }
  ]
}
</code>```

Now, when you will receive WebHook response, you will be able to know which custom fields below to which composite template. I have one more suggestion, since you are not using any dropdowns, then it is better to use TextCustomFields instead of ListCustomFields.

ContentLicense: CC BY-SA 3.0

Body:
I have created 1 envelope with 2 composite templates with embedded signing and I can hook it up with the webhook event notification to receive a message once users finish signing, so I can try to update my db and download the file. However, the webhook response does not have the custom fields that I need to identify which file belong to which for me to update the db row.

This is my json serialized envelope example. Notice the custom field on each inline template, that have the property of DocuInfoId. I will need the value of those to update my db row

{
  "status": "sent",
  "emailSubject": "DocuSign API - Template Example",
  "eventNotification": {
    "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available",
    "loggingEnabled": "false",
    "requireAcknowledgment": "true",
    "useSoapInterface": "false",
    "soapNameSpace": "",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "false",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "false",
    "includeDocumentFields": "false",
    "includeCertificateOfCompletion": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Sent",
        "includeDocuments": null
      },
      {
        "envelopeEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ],
    "recipientEvents": [
      {
        "recipientEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ]
  },
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just a bunch of text tabs, radio group, etc"
                }
              },
              {
                "clientUserId": "2",
                "recipientId": "2",
                "email": "testemail@test.com",
                "name": "Owner Name",
                "roleName": "Owner",
                "tabs": null
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "77",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "TemplateIDNumber1"
        }
      ]
    },
    {
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just another bunch of text tabs, radio group tab, etc"
                }
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "88",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "2",
          "templateId": "TemplateIDNumber2"
        }
      ]
    }
  ]
}

And once I finished signing, the webhook event notification is triggered and called my api with this response message

{
  "EnvelopeStatus": {
    "EnvelopeID": "EnvelopeIDGivenByDocusign",
    "Status": "Completed",
    "CustomFields": [
      {
        "Name": "ContactID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "OpportunityID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "AccountID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "DocuInfoId",
        "Show": "False",
        "Required": "True",
        "Value": "88"
      },
      {
        "Name": "OpportunityId",
        "Show": "False",
        "Required": "True",
        "Value": "1"
      },
      {
        "Name": "LQAID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      }
    ],
    "DocumentStatuses": [
      {
        "ID": 1,
        "Name": "Document - TX - 1001.pdf",
        "TemplateName": "Document - TX",
        "Sequence": 1
      },
      {
        "ID": 2,
        "Name": "Rejection.pdf",
        "TemplateName": "Rejection Form",
        "Sequence": 2
      }
    ]
  },
  "DocumentPDFs": [
    {
      "Name": "Document - TX - 1001.pdf",
      "DocumentID": "1",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "Rejection.pdf",
      "DocumentID": "2",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "CertificateOfCompletion_78sd89fuas89sadf.pdf",
      "DocumentID": null,
      "DocumentType": "SUMMARY"
    }
  ]
}

Looking at the response, there's only 1 docuinfoid with the value of 88, I'm also not sure where is the rest of custom field coming from e.g: "LQAID". Now, I'm not sure which docuinfoid is this belong to, the first pdf file (Document - TX - 1001.pdf) or the second pdf file (Rejection.pdf).

Is there anyway to know which pdf document belong to which docuinfoid, so that I can attach it to my database correctly?

Body:
You can set compositeTemplateId for each CompositeTemplate and then use this Id in each envelope Custom Field. I have modified your JSON request to include CompositeTemplateId,

{
  "status": "sent",
  "emailSubject": "DocuSign API - Template Example",
  "eventNotification": {
    "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available",
    "loggingEnabled": "false",
    "requireAcknowledgment": "true",
    "useSoapInterface": "false",
    "soapNameSpace": "",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "false",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "false",
    "includeDocumentFields": "false",
    "includeCertificateOfCompletion": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Sent",
        "includeDocuments": null
      },
      {
        "envelopeEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ],
    "recipientEvents": [
      {
        "recipientEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ]
  },
  "compositeTemplates": [
    {
      "compositeTemplateId": "1",
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just a bunch of text tabs, radio group, etc"
                }
              },
              {
                "clientUserId": "2",
                "recipientId": "2",
                "email": "testemail@test.com",
                "name": "Owner Name",
                "roleName": "Owner",
                "tabs": null
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId_1",
                "required": "True",
                "show": "False",
                "value": "77",
                "listItems": null
              },
              {
                "name": "OpportunityId_1",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "TemplateIDNumber1"
        }
      ]
    },
    {
      "compositeTemplateId": "2",
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just another bunch of text tabs, radio group tab, etc"
                }
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId_2",
                "required": "True",
                "show": "False",
                "value": "88",
                "listItems": null
              },
              {
                "name": "OpportunityId_2",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "2",
          "templateId": "TemplateIDNumber2"
        }
      ]
    }
  ]
}

Now, when you will receive WebHook response, you will be able to know which custom fields below to which composite template. I have one more suggestion, since you are not using any dropdowns, then it is better to use TextCustomFields instead of ListCustomFields.


问:
Android: Not able to access storage to save image
I have an imageview which is loaded using a url.
I want to download the image in the view and store it in internal/external drive of mobile. But i tried all possible method on Stackoverflow couldn't access the drive even with the premission given on the mobile to access read and write in the external memory. Nothing seems to work i don't know why?

This is my Code, can you please tell me where I am going wrong?

```<code>BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
    Bitmap bitmap = drawable.getBitmap();

    File sdCardDirectory = Environment.getDataDirectory();
    File image = new File(sdCardDirectory, "test.png");
    boolean success = false;

    // Encode the file as a PNG image.
    FileOutputStream outStream;
    try {

        outStream = new FileOutputStream(image);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
    /* 100 to keep full quality of the image */

        outStream.flush();
        outStream.close();
        success = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (success) {
        Toast.makeText(getApplicationContext(), "Image saved with success",
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(),
                "Error during image saving", Toast.LENGTH_LONG).show();
    }
</code>```

Manifest permissions

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

答:
```<code>File sdCardDirectory = Environment.getDataDirectory();
</code>```

That is not the sd card directory.

```<code>Environment.getDataDirectory().getAbsolutePath() == /data
</code>```

You have no write permission there. Better use

```<code>File sdCardDirectory = Environment.getExternalStorageDirectory();
</code>```

That will work if you got your permissions right.

But it will not save to the SD card!

Body:
I have an imageview which is loaded using a url.
I want to download the image in the view and store it in internal/external drive of mobile. But i tried all possible method on Stackoverflow couldn't access the drive even with the premission given on the mobile to access read and write in the external memory. Nothing seems to work i don't know why?

This is my Code, can you please tell me where I am going wrong?

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
    Bitmap bitmap = drawable.getBitmap();

    File sdCardDirectory = Environment.getDataDirectory();
    File image = new File(sdCardDirectory, "test.png");
    boolean success = false;

    // Encode the file as a PNG image.
    FileOutputStream outStream;
    try {

        outStream = new FileOutputStream(image);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
    /* 100 to keep full quality of the image */

        outStream.flush();
        outStream.close();
        success = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (success) {
        Toast.makeText(getApplicationContext(), "Image saved with success",
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(),
                "Error during image saving", Toast.LENGTH_LONG).show();
    }

Manifest permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Body:
File sdCardDirectory = Environment.getDataDirectory();

That is not the sd card directory.

Environment.getDataDirectory().getAbsolutePath() == /data

You have no write permission there. Better use

File sdCardDirectory = Environment.getExternalStorageDirectory();

That will work if you got your permissions right.

But it will not save to the SD card!


问:
Changing status code from 502 to 503 in fallback route
I'm using nginx as proxy server for my project. In case my app is offline for maintenance I'd like to show a fallback page. This works fine so far. The only problem is, that the server response with a 502 error code - which makes sense. How do I change it to a 503 route in my fallback though?</p>
```<code>server {
    listen 80;
    error_page 500 502 503 504 @fallback;

   location / {
     proxy_pass http://0.0.0.0:3000;
   }

   location @fallback {
       // I need this to answer with a status of 503 instead of a 502
       root /srv/my-project/static;
       try_files /fallback.html;
   }

}
</code>```

答:
you can set a error page nginx error page

and set somethig like

error_page 502 =503 /maintenance.html

or something like

```<code>    location / {
        error_page 502 =503 /maintenance.html;
        include proxy_params;
        proxy_pass http://unix:/var/run/my.sock;
    }
    location /maintenance.html {
        return 503;
    }
</code>```

source : How can I make Nginx return HTTP 503 when my proxied app server is down?

ContentLicense: CC BY-SA 4.0

Body:
I'm using nginx as proxy server for my project. In case my app is offline for maintenance I'd like to show a fallback page. This works fine so far. The only problem is, that the server response with a 502 error code - which makes sense. How do I change it to a 503 route in my fallback though?

server {
    listen 80;
    error_page 500 502 503 504 @fallback;

   location / {
     proxy_pass http://0.0.0.0:3000;
   }

   location @fallback {
       // I need this to answer with a status of 503 instead of a 502
       root /srv/my-project/static;
       try_files /fallback.html;
   }

}

Body:
you can set a error page nginx error page

and set somethig like

error_page 502 =503 /maintenance.html

or something like

    location / {
        error_page 502 =503 /maintenance.html;
        include proxy_params;
        proxy_pass http://unix:/var/run/my.sock;
    }
    location /maintenance.html {
        return 503;
    }

source : How can I make Nginx return HTTP 503 when my proxied app server is down?


问:
Callback is not a function error [Nodejs]
I have the following code

```<code>var getUrl = function(callback) {
  ref.once('value')
    .then(function(snap) {
      let article_url = snap.val();
      console.log(article_url);
      callback(null, article_url); // I dont want to throw an error, so I pass null for the error argument
    });
};

var getImage = function(err, data, callback) {
  //if (err) throw err; // Check for the error and throw if it exists.
  textapi.extract({
    url: data,
    best_image: true
  }, function(error, response) {
    if (error === null) {
      //console.log(response.image);
      if (response.image == null || response.image == "") {
        image = "https://www.wefornews.com/wp-content/uploads/2017/01/news-3.jpg"
      } else {
        image = response.image;
      }
    }
  });
  callback(null, image); // Otherwise proceed as usual.
};

var updateDatabase = function(err, data) {
  //if (err) throw err; // Check for the error and throw if it exists.
  refupdate.update ({
    "Article_Image_URL": data
  });
  console.log('success'); // Otherwise proceed as usual
};

getUrl(getImage);
getImage(updateDatabase);
</code>```

However I get an error callback is not a function at the line callback(null, image);

The thing is if I remove the updateDatabase function then I get no errors. However when it is within the code I get the error mentioned above.
Can someone please tell me what can be causing this error?

答:
When you call getUrl(getImage), the getImage function is passed as the callback parameter to getUrl. getUrl then calls this callback parameter, passing two parameters.

callback(null, article_url)

but getImage expects three parameters

var getImage = function(err, data, callback)

so callback inside the getImage function is undefined, and when you try to call undefined as a function

callback(null, image)

... you get your callback is not a function error.

Solution

You need to nest your callbacks so the functions are called in the correct order, with the correct parameters.

```<code>getUrl(function (err, article_url) {
  getImage(err, article_url, function (err, image) {
    updateDatabase(err, image);
  });
});
</code>```

This could also be simplified since you want to call updateDatabase directly after getImage completes.

```<code>getUrl(function (err, article_url) {
  getImage(err, article_url, updateDatabase);
});
</code>```

Also, in your getImage function, the callback is called before your textapi.extract function completes, which is probably not want you want.

Before

```<code>var getImage = function(err, data, callback) {
  textapi.extract({
    url: data,
    best_image: true
  }, function(error, response) {
    /* code */
  });
  callback(null, image); // This will get called immediately, without waiting for textapi.extract
};
</code>```

After

```<code>var getImage = function(err, data, callback) {
  textapi.extract({
    url: data,
    best_image: true
  }, function(error, response) {
    /* code */
    callback(null, image); // Callback moved here, so it gets called after textapi.extract completes
  });
};
</code>```

Body:
I have the following code

var getUrl = function(callback) {
  ref.once('value')
    .then(function(snap) {
      let article_url = snap.val();
      console.log(article_url);
      callback(null, article_url); // I dont want to throw an error, so I pass null for the error argument
    });
};

var getImage = function(err, data, callback) {
  //if (err) throw err; // Check for the error and throw if it exists.
  textapi.extract({
    url: data,
    best_image: true
  }, function(error, response) {
    if (error === null) {
      //console.log(response.image);
      if (response.image == null || response.image == "") {
        image = "https://www.wefornews.com/wp-content/uploads/2017/01/news-3.jpg"
      } else {
        image = response.image;
      }
    }
  });
  callback(null, image); // Otherwise proceed as usual.
};

var updateDatabase = function(err, data) {
  //if (err) throw err; // Check for the error and throw if it exists.
  refupdate.update ({
    "Article_Image_URL": data
  });
  console.log('success'); // Otherwise proceed as usual
};

getUrl(getImage);
getImage(updateDatabase);

However I get an error callback is not a function at the line callback(null, image);

The thing is if I remove the updateDatabase function then I get no errors. However when it is within the code I get the error mentioned above.
Can someone please tell me what can be causing this error?

Body:
When you call getUrl(getImage), the getImage function is passed as the callback parameter to getUrl. getUrl then calls this callback parameter, passing two parameters.

callback(null, article_url)

but getImage expects three parameters

var getImage = function(err, data, callback)

so callback inside the getImage function is undefined, and when you try to call undefined as a function

callback(null, image)

... you get your callback is not a function error.

Solution

You need to nest your callbacks so the functions are called in the correct order, with the correct parameters.

getUrl(function (err, article_url) {
  getImage(err, article_url, function (err, image) {
    updateDatabase(err, image);
  });
});

This could also be simplified since you want to call updateDatabase directly after getImage completes.

getUrl(function (err, article_url) {
  getImage(err, article_url, updateDatabase);
});

Also, in your getImage function, the callback is called before your textapi.extract function completes, which is probably not want you want.

Before

var getImage = function(err, data, callback) {
  textapi.extract({
    url: data,
    best_image: true
  }, function(error, response) {
    /* code */
  });
  callback(null, image); // This will get called immediately, without waiting for textapi.extract
};

After

var getImage = function(err, data, callback) {
  textapi.extract({
    url: data,
    best_image: true
  }, function(error, response) {
    /* code */
    callback(null, image); // Callback moved here, so it gets called after textapi.extract completes
  });
};


问:
Handling push notification while application is on background
I am trying to fire a procedure or service when receiving a push notification, however I want to do this while the application is running in the background.

I have already tested that it works with the application on foreground, but also need it to do some work when in background if receiving the notification.

I have asked around and have been told that cannot be done, however i would like to ask here to confirm it, thanks in advance.

答:
yes, You can achieve this. You need to send push message with data payload and without notification payload.
Check the doc</p>


问:
Nested if failure - Pseudo code sample
For the past days I've been trying to understand why a script I have is failing, and execution all refers, in the error, to this part of the code (pseudo-code for this post):

```<code>if [ -z "${removed-unset}" ]; then
    ABC
    else
        if [ "$(date +%u)" == 4 ];  then
            if test `find "ABC" -cmin +2880` then
                if [ ! -f /tmp/ABC ]; then
                    CODE HERE
                        if [[ -s ABC ]]; then
                            CODE HERE
                                if [ -z "${ABC-unset}" ]; then
                                     CODE HERE
                                else
                                     CODE HERE
                                fi
                         else
                             rm ABC
                         fi
                 else
                     CODE HERE
                 fi
             else
                 CODE HERE
             fi
    else
        CODE HERE
    fi
fi
</code>```

I was wondering if I could have some pointers as to what it is I'm doing wrong here. I apologize for the lack of actual code and the syntax.

答:
ShellCheck points out that you're missing a semicolon:

```<code>if test `find "ABC" -cmin +2880` then
                                 ^-- SC1010: Use semicolon or linefeed before 'then'
                                             (or quote to make it literal).
</code>```

Just insert it as suggested:

```<code>if test `find "ABC" -cmin +2880`; then
</code>```

This is required because then is only special at the start of a command.

Title: Nested if failure - Pseudo code sample

Body:
For the past days I've been trying to understand why a script I have is failing, and execution all refers, in the error, to this part of the code (pseudo-code for this post):

if [ -z "${removed-unset}" ]; then
    ABC
    else
        if [ "$(date +%u)" == 4 ];  then
            if test `find "ABC" -cmin +2880` then
                if [ ! -f /tmp/ABC ]; then
                    CODE HERE
                        if [[ -s ABC ]]; then
                            CODE HERE
                                if [ -z "${ABC-unset}" ]; then
                                     CODE HERE
                                else
                                     CODE HERE
                                fi
                         else
                             rm ABC
                         fi
                 else
                     CODE HERE
                 fi
             else
                 CODE HERE
             fi
    else
        CODE HERE
    fi
fi

I was wondering if I could have some pointers as to what it is I'm doing wrong here. I apologize for the lack of actual code and the syntax.

Body:
ShellCheck points out that you're missing a semicolon:

if test `find "ABC" -cmin +2880` then
                                 ^-- SC1010: Use semicolon or linefeed before 'then'
                                             (or quote to make it literal).

Just insert it as suggested:

if test `find "ABC" -cmin +2880`; then

This is required because then is only special at the start of a command.


问:
How to pass progress reports from inner function to main function?
I am currently trying to pass progress (Using Iprogress and Progress) from a inner function to the main function. Everything works after the inner function completes. However, I am retrieving/downloading some data using EBay's API's (EBay's finding service which is an rest service that returns data in XML format) and need to pass progress reports from the inner function to the main one during the download of the XML data retrieved/data processing.

Here's the main function's code (A little starting to get overloaded but you get whats going on. commented for sanity.):

```<code> Private Property a As Integer
        Get
            Return a_value
        End Get
        Set(value As Integer)
            a_value = value
            ' ReportProgress(value, Nothing)
        End Set
    End Property
    Private a_value As Integer
Public Async Function EvaluateItem(item As List(Of ItemInfo), evalprogress As IProgress(Of Integer), Optional ManualEvaluation As Boolean = False) As Task(Of List(Of EvaluationInfo))
    Dim notevaluatedcount As Integer = 0
    Dim iteminfo1 As ItemInfo = New ItemInfo
    Dim tmpiteminfo As List(Of ItemInfo) = New List(Of ItemInfo)
    Dim tmpiteminfo2 As List(Of ItemInfo) = New List(Of ItemInfo)
    Dim pricefunctions As ItemValuation = New ItemValuation
    Dim tmpevalinfo As EvaluationInfo = New EvaluationInfo
    Dim itemevalresultarr As List(Of EvaluationInfo) = New List(Of EvaluationInfo)
    Dim mode As Double
    Dim avg As Double
    Dim min As Double
    Dim max As Double
    Dim standarddev As Double
    Dim pricearr() As Double
    Dim autoitem As List(Of EvaluationInfo) = New List(Of EvaluationInfo)
    Dim itemse As New ItemInformation
    ' Dim itemsnoteval As New ItemInformation
    ' itemseval.itemsevaluated = New List(Of String)
    ' itemsnoteval.notevaluated = New List(Of String)
    Dim tmpnoteval As List(Of ItemInfo) = New List(Of ItemInfo)

    Dim ran As Boolean
    'sort and store item condition information in evaluation table in database or by item.sort
    If item.Count > 1 And ManualEvaluation = True Then
        tmpiteminfo = SortByName(item)
        Await ClearEvalTable()
        tmpiteminfo2 = SortByCondition(tmpiteminfo)
        If CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess Then
            Await Task.Run(Function()

                               'Await Task.Delay(1000)
                               If evalprogress IsNot Nothing Then
                                   'ReportProgress(4, Nothing)
                                   evalprogress.Report(4)
                                   evalprogress.Report(5)
                               End If
                               ' tempCount += 1

                               Return 5
                           End Function)
        ElseIf CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess = False Then
            Await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Function()

                                                                                'Await Task.Delay(1000)
                                                                                If evalprogress IsNot Nothing Then
                                                                                evalprogress.Report(4)
                                                                                evalprogress.Report(5)
                                                                                End If
                                                                                ' tempCount += 1

                                                                                Return 5
                                                                                End Function)

        End If
        'evalprogress.Report(5)
        ' MsgBox("condition count:" + tmpiteminfo2.Count.ToString)
    ElseIf item.Count > 1 And ManualEvaluation = False Then
        'do nothing
    ElseIf item.Count = 1 And ManualEvaluation = True Then
        'change this code to perform manual evaluation on one item.
        'tmpiteminfo.Add(item.Item(0))
    End If
    ReDim pricearr(item.Count)

    If ManualEvaluation Then
        If ran = False Then
            Dim count As Integer
            For Each d As ItemInfo In tmpiteminfo
                count = count + 1
                If ItemValidation.ContainsValidCharacters(d.name) And ItemValidation.IsDouble(d.price) Then
                    'decide whether to manually evaluate the item or automatically evaluate it.
                    Log("Item name: " + d.name + " price #: " + d.price.ToString)
                Else
                    Log("Item: " + d.name + " has invalid characters in its name. It will not be evaluated. Please remove the invalid characters to have the item evaluated." + "The item price may not be an integer. please fix this too (if applicable)")
                    iteminfo1.name = d.name
                    iteminfo1.price = 0
                    iteminfo1.evaluationSource = d.evaluationSource
                    iteminfo1.damaged = "NO"
                    iteminfo1.aquisitiondate = "1/1/1111"
                    iteminfo1.itempicture = Nothing
                    ' tmpnoteval.Add(iteminfo1)
                    tmpevalinfo.currentItem = iteminfo1.name
                    tmpevalinfo.evaluated = False
                    tmpevalinfo.evaluationcondition = d.itemcondition
                    itemevalresultarr.Add(tmpevalinfo)
                    '  tmpnoteval.Add(iteminfo1)
                    notevaluatedcount += 1
                End If
                Select Case d.itemcondition
                    Case Is = ItemCondition.Broken
                        broken.Add(d.price)
                    Case Is = ItemCondition.LooksLikeNew
                        Lookslikenew.Add(d.price)
                        'MsgBox("Looks like new price:" + d.price.ToString)
                    Case Is = ItemCondition.SomewhatUsed
                        somewhatused.Add(d.price)
                        '  MsgBox("Somewhat Used price:" + d.price.ToString)
                    Case Is = ItemCondition.SomeDamage
                        damaged.Add(d.price)
                End Select
            Next
            ran = True
        End If

    Else
        'Automatically evaluate item using different retailers i.e. Amazon, E-Bay, etc.
        'use grabfromonlinesource multiple times to grab from each evaluation source used.
        Dim tmpevalitem As Task(Of List(Of EvaluationInfo))

        For i = 0 To item.Count - 1
            'does once for each item
            'need to split it into conditions inside of grabfromonlinesource
            If ItemValidation.ContainsValidCharacters(item.Item(i).name) Then

                '  evalprogress = New Progress(Of Integer)(Function(value) InlineAssignHelper(value, a))
                If CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess Then
                    Await Task.Run(Function()

                                       'Await Task.Delay(1000)
                                       If evalprogress IsNot Nothing Then
                                           ' ReportProgress(10, Nothing)
                                           evalprogress.Report(10)
                                           ReportProgress(10, Nothing)
                                       End If
                                       ' tempCount += 1

                                       Return 10
                                   End Function)
                ElseIf CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess = False Then
                    Await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Function()

                                                                                'Await Task.Delay(1000)
                                                                                If evalprogress IsNot Nothing Then
                                                                                evalprogress.Report(10)
                                                                                End If
                                                                                ' tempCount += 1

                                                                                Return 10
                                                                                End Function)

                End If

                tmpevalitem = GrabFromOnlineSource(item.Item(i).name, item.Item(i).evaluationSource, New Progress(Of Integer)(Function(value) InlineAssignHelper(a, value)))
                tmpevalitem.Wait()
                If CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess Then
                    Await Task.Run(Function()

                                       'Await Task.Delay(1000)
                                       If evalprogress IsNot Nothing Then
                                           ' ReportProgress(70, Nothing)
                                           evalprogress.Report(70)
                                       End If
                                       ' tempCount += 1

                                       Return 70
                                   End Function)
                ElseIf CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess = False Then
                    Await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Function()

                                                                                'Await Task.Delay(1000)
                                                                                If evalprogress IsNot Nothing Then
                                                                                'evalprogress.Report(70)
                                                                                End If
                                                                                ' tempCount += 1

                                                                                Return 70
                                                                                End Function)

                End If
                ' ItemValuation.tmpProgressIndicator.Report(60)

                If tmpevalitem.Result IsNot Nothing Then
                    autoitem.AddRange(tmpevalitem.Result)
                Else
                    Continue For
                End If
            Else
                Dim tmpevalinfoauto As EvaluationInfo
                tmpevalinfoauto.currentItem = item.Item(i).name
                tmpevalinfoauto.evaluationcondition = item.Item(i).itemcondition
                autoitem.Add(tmpevalinfoauto)
            End If
        Next i
        autoitem.Add(Nothing) 'use nothing as an indicator of a new item.
    End If

    If ManualEvaluation Then
        Dim done(4) As Boolean
        done(0) = False
        done(1) = False
        done(2) = False
        done(3) = False
        'MsgBox("item information count: " + tmpiteminfo2.Count.ToString)
        For f = 0 To tmpiteminfo2.Count - 1
            'MsgBox(tmpiteminfo2.Item(f).evaluationSource)
            Select Case tmpiteminfo2.Item(f).evaluationSource
                Case Is = "Gamestop"
                    tmpevalinfo.valuationsourceid = 1
                Case Is = "Amazon"
                    tmpevalinfo.valuationsourceid = 2
                Case Is = "Ebay"
                    tmpevalinfo.valuationsourceid = 3
                    'add more sources here later
            End Select
            Select Case tmpiteminfo2.Item(f).itemcondition
                Case Is = ItemCondition.Broken
                    'If done(0) = False Then
                    mode = pricefunctions.Mode(broken.ToArray)
                    max = pricefunctions.MaxValue(broken.ToArray)
                    min = pricefunctions.MinValue(broken.ToArray)
                    avg = pricefunctions.AveragePrice(broken.ToArray)
                    standarddev = pricefunctions.standarddeviation(broken.ToArray)
                    done(0) = True
                   ' End If
                Case Is = ItemCondition.LooksLikeNew
                    'If done(1) = False Then
                    mode = pricefunctions.Mode(Lookslikenew.ToArray)
                    max = pricefunctions.MaxValue(Lookslikenew.ToArray)
                    min = pricefunctions.MinValue(Lookslikenew.ToArray)
                    avg = pricefunctions.AveragePrice(Lookslikenew.ToArray)
                    standarddev = pricefunctions.standarddeviation(Lookslikenew.ToArray)
                    done(1) = True
                   ' End If
                Case Is = ItemCondition.SomeDamage
                    ' If done(2) = False Then
                    mode = pricefunctions.Mode(damaged.ToArray)
                    max = pricefunctions.MaxValue(damaged.ToArray)
                    min = pricefunctions.MinValue(damaged.ToArray)
                    avg = pricefunctions.AveragePrice(damaged.ToArray)
                    standarddev = pricefunctions.standarddeviation(damaged.ToArray)
                    done(2) = True
                   ' End If
                Case Is = ItemCondition.SomewhatUsed
                    'If done(3) = False Then
                    mode = pricefunctions.Mode(somewhatused.ToArray)
                    max = pricefunctions.MaxValue(somewhatused.ToArray)
                    min = pricefunctions.MinValue(somewhatused.ToArray)
                    avg = pricefunctions.AveragePrice(somewhatused.ToArray)
                    standarddev = pricefunctions.standarddeviation(somewhatused.ToArray)
                    done(3) = True
                    ' End If

            End Select

            'assign values to minimum price, maximum price, and the other prices.
            If min > 0 Then
                tmpevalinfo.MinimumPrice = min
            End If
            If mode > 0 Then
                tmpevalinfo.ReoccuringPrice = mode
            End If
            If avg > 0 Then
                tmpevalinfo.avgprice = avg
            End If
            If max > 0 Then
                tmpevalinfo.MaximumPrice = max
            End If
            If standarddev > 0 Then  'And standarddev < 1 Then
                tmpevalinfo.avgdeviation = standarddev
            End If
            min = 0
            max = 0
            mode = 0
            avg = 0
            tmpevalinfo.currentItem = tmpiteminfo2.Item(f).name
            tmpevalinfo.evaluationcondition = tmpiteminfo2.Item(f).itemcondition
            'MsgBox(tmpiteminfo2.Item(f).itemcondition)
            tmpevalinfo.evaluated = True
            itemevalresultarr.Add(tmpevalinfo)

        Next f
        'Dim iteminfoc As New ItemInformation
        'For s = 0 To tmpiteminfo.Count - 1
        '    iteminfoc.itemsevaluate.Add(tmpiteminfo.Item(s).name)
        '    'add other item information and change to iteminfo type once I get information to display correctly on findquote form
        'Next s
        Dim itemval As New ItemValuation
        Dim tmpevalsource As New EvaluationSource
        Using uie As New DataAccess.SQLiteDb
            For h = 0 To tmpiteminfo.Count - 1
                tmpevalsource.EvaluationSourceName = tmpiteminfo.Item(h).evaluationSource
                tmpevalsource.EvaluationWebAddress = (From EvalWeb In uie.ValuationSources Where EvalWeb.ValuationSourceName = tmpevalsource.EvaluationSourceName Select EvalWeb).ToString
                Await itemval.archiveitem(tmpiteminfo.Item(h).name, tmpiteminfo.Item(h).name, tmpevalsource)
            Next
        End Using
        'delete all the evaluated items from the database for next evaluation

        Await ClearEvalTable()
        'return regular results
        Return itemevalresultarr
    Else
        'return automated evaluation results
        'results are archived as they are retrieved so delete data from the table below
        'delete all the evaluated items from the database for next evaluation
        Return autoitem
    End If

End Function
</code>```

Here's the inner function's signature:

```<code>Private Async Function GrabFromOnlineSource(itemname As String, WebsiteSource As String, progress As IProgress(Of Integer)) As Task(Of List(Of EvaluationInfo))
</code>```

Here's what I have tried so far (updated):

first try:

```<code>  tmpevalitem = Await GrabFromOnlineSource(item.Item(i).name, item.Item(i).evaluationSource, New Progress(Of Integer)(Function(value) InlineAssignHelper(totalprogress, value))). 'replace totalprogress with the a integer I mentioned in the comments.
                  tmpevalitem.Wait()
</code>```

second try:

```<code>   tmpevalitem = GrabFromOnlineSource(item.Item(i).name, item.Item(i).evaluationSource, New Progress(Of IProgress(Of Integer))(Function(value) InlineAssignHelper(evalprogress, value)))
                        tmpevalitem.Wait()
</code>```

The above code though ends up in an error about data type progress not being correct. I really need to pass my progress from GrabFromOnlineSource to the evalprogress variable or otherwise I will have differing values sent to the main program.

Note: I technically could have GrabFromOnlineSource called for each evaluation source used (4 total possible as of this moment). In addition, each evaluation source sent to GrabFromOnlineSource has its own progress reported counted toward the current evaluation source (i.e. ebay has its own progress, amazon its own, etc).

The EvaluationInfo and ItemInfo Structures:

```<code>     Public Structure EvaluationInfo
        Dim ReoccuringPrice As Double
        Dim MinimumPrice As Double
        Dim MaximumPrice As Double
        Dim avgprice As Double
        Dim avgdeviation As Double
        Dim currentItem As String
        Dim valuationsourceid As Integer
        Dim evaluationcondition As ItemCondition 'i.e. used,new,broken enum
        Dim evaluated As Boolean
    End Structure

 Public Structure ItemInfo
            Public Property name As String
            Public Property price As Double
            Public Property damaged As String
            Public Property aquisitiondate As Date
            Public Property evaluationSource As String
            Public Property itemcondition As ItemCondition
            Public Property itempicture As Byte()
            Public Property itemid As Integer

        End Structure
</code>```

More Information:

One thing I forgot to mention progress reporting does work with task.run from evaluateitem function but I prefer to modularize my code a bit to prevent one action from taking too much space and that's why I have not moved the code from GrabFromOnlineSource into evaluateitem.

答:
Sorry for the delay in answering my own question but here goes (I am not perfect at formatting code so an editor or admin can pretty it up):

This is the class test code I used separately from my projects dll to test this was working (aka I created a new project to test my theory):

```<code>Imports Windows.ApplicationModel.Core
Imports Windows.UI.Core

Public Class Progresstestclass
    Private Shared Property totalprogress As Integer
    Public Shared Async Function MainFunction(progress As IProgress(Of Integer)) As Task(Of Boolean)

        totalprogress = 5
        progress.Report(totalprogress)
        Dim a As New String("")
        Do While totalprogress > 0 And totalprogress < 70 And a <> "Success"
            Await InnerFunction(New Progress(Of Integer)(Function(value) InlineAssignHelper(totalprogress, value)))
            progress.Report(totalprogress - 5)
            Await System.Threading.Tasks.Task.Delay(1000)
            progress.Report(totalprogress)

        Loop
        Return True
    End Function
    Private Shared Async Function InnerFunction(progress2 As IProgress(Of Integer)) As Task(Of String)
    progress2.report(30)
            Await System.Threading.Tasks.Task.Delay(1000)
            progress2.Report(40)
          Await System.Threading.Tasks.Task.Delay(1000)

        Return "Success"
    End Function
    Public Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
        target = value
        Return value
    End Function

End Class
</code>```

Another thing that changed inside my main function was my while loop was a little wrong. I needed put in delays in-between passing progress reports back or else it did not pass it back or showed it at 100% at the end making my progress report useless. Anyone can still comment on best how to do this. Its a crazy thing that forgoting delays can mess up a program!

Everything else is pretty much the same. Except I put delays as above to have it stop passing progress long enough for the natural eye to see the progress happening.

Body:
I am currently trying to pass progress (Using Iprogress and Progress) from a inner function to the main function. Everything works after the inner function completes. However, I am retrieving/downloading some data using EBay's API's (EBay's finding service which is an rest service that returns data in XML format) and need to pass progress reports from the inner function to the main one during the download of the XML data retrieved/data processing.

Here's the main function's code (A little starting to get overloaded but you get whats going on. commented for sanity.):

 Private Property a As Integer
        Get
            Return a_value
        End Get
        Set(value As Integer)
            a_value = value
            ' ReportProgress(value, Nothing)
        End Set
    End Property
    Private a_value As Integer
Public Async Function EvaluateItem(item As List(Of ItemInfo), evalprogress As IProgress(Of Integer), Optional ManualEvaluation As Boolean = False) As Task(Of List(Of EvaluationInfo))
    Dim notevaluatedcount As Integer = 0
    Dim iteminfo1 As ItemInfo = New ItemInfo
    Dim tmpiteminfo As List(Of ItemInfo) = New List(Of ItemInfo)
    Dim tmpiteminfo2 As List(Of ItemInfo) = New List(Of ItemInfo)
    Dim pricefunctions As ItemValuation = New ItemValuation
    Dim tmpevalinfo As EvaluationInfo = New EvaluationInfo
    Dim itemevalresultarr As List(Of EvaluationInfo) = New List(Of EvaluationInfo)
    Dim mode As Double
    Dim avg As Double
    Dim min As Double
    Dim max As Double
    Dim standarddev As Double
    Dim pricearr() As Double
    Dim autoitem As List(Of EvaluationInfo) = New List(Of EvaluationInfo)
    Dim itemse As New ItemInformation
    ' Dim itemsnoteval As New ItemInformation
    ' itemseval.itemsevaluated = New List(Of String)
    ' itemsnoteval.notevaluated = New List(Of String)
    Dim tmpnoteval As List(Of ItemInfo) = New List(Of ItemInfo)

    Dim ran As Boolean
    'sort and store item condition information in evaluation table in database or by item.sort
    If item.Count > 1 And ManualEvaluation = True Then
        tmpiteminfo = SortByName(item)
        Await ClearEvalTable()
        tmpiteminfo2 = SortByCondition(tmpiteminfo)
        If CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess Then
            Await Task.Run(Function()

                               'Await Task.Delay(1000)
                               If evalprogress IsNot Nothing Then
                                   'ReportProgress(4, Nothing)
                                   evalprogress.Report(4)
                                   evalprogress.Report(5)
                               End If
                               ' tempCount += 1

                               Return 5
                           End Function)
        ElseIf CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess = False Then
            Await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Function()

                                                                                'Await Task.Delay(1000)
                                                                                If evalprogress IsNot Nothing Then
                                                                                evalprogress.Report(4)
                                                                                evalprogress.Report(5)
                                                                                End If
                                                                                ' tempCount += 1

                                                                                Return 5
                                                                                End Function)

        End If
        'evalprogress.Report(5)
        ' MsgBox("condition count:" + tmpiteminfo2.Count.ToString)
    ElseIf item.Count > 1 And ManualEvaluation = False Then
        'do nothing
    ElseIf item.Count = 1 And ManualEvaluation = True Then
        'change this code to perform manual evaluation on one item.
        'tmpiteminfo.Add(item.Item(0))
    End If
    ReDim pricearr(item.Count)

    If ManualEvaluation Then
        If ran = False Then
            Dim count As Integer
            For Each d As ItemInfo In tmpiteminfo
                count = count + 1
                If ItemValidation.ContainsValidCharacters(d.name) And ItemValidation.IsDouble(d.price) Then
                    'decide whether to manually evaluate the item or automatically evaluate it.
                    Log("Item name: " + d.name + " price #: " + d.price.ToString)
                Else
                    Log("Item: " + d.name + " has invalid characters in its name. It will not be evaluated. Please remove the invalid characters to have the item evaluated." + "The item price may not be an integer. please fix this too (if applicable)")
                    iteminfo1.name = d.name
                    iteminfo1.price = 0
                    iteminfo1.evaluationSource = d.evaluationSource
                    iteminfo1.damaged = "NO"
                    iteminfo1.aquisitiondate = "1/1/1111"
                    iteminfo1.itempicture = Nothing
                    ' tmpnoteval.Add(iteminfo1)
                    tmpevalinfo.currentItem = iteminfo1.name
                    tmpevalinfo.evaluated = False
                    tmpevalinfo.evaluationcondition = d.itemcondition
                    itemevalresultarr.Add(tmpevalinfo)
                    '  tmpnoteval.Add(iteminfo1)
                    notevaluatedcount += 1
                End If
                Select Case d.itemcondition
                    Case Is = ItemCondition.Broken
                        broken.Add(d.price)
                    Case Is = ItemCondition.LooksLikeNew
                        Lookslikenew.Add(d.price)
                        'MsgBox("Looks like new price:" + d.price.ToString)
                    Case Is = ItemCondition.SomewhatUsed
                        somewhatused.Add(d.price)
                        '  MsgBox("Somewhat Used price:" + d.price.ToString)
                    Case Is = ItemCondition.SomeDamage
                        damaged.Add(d.price)
                End Select
            Next
            ran = True
        End If

    Else
        'Automatically evaluate item using different retailers i.e. Amazon, E-Bay, etc.
        'use grabfromonlinesource multiple times to grab from each evaluation source used.
        Dim tmpevalitem As Task(Of List(Of EvaluationInfo))

        For i = 0 To item.Count - 1
            'does once for each item
            'need to split it into conditions inside of grabfromonlinesource
            If ItemValidation.ContainsValidCharacters(item.Item(i).name) Then

                '  evalprogress = New Progress(Of Integer)(Function(value) InlineAssignHelper(value, a))
                If CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess Then
                    Await Task.Run(Function()

                                       'Await Task.Delay(1000)
                                       If evalprogress IsNot Nothing Then
                                           ' ReportProgress(10, Nothing)
                                           evalprogress.Report(10)
                                           ReportProgress(10, Nothing)
                                       End If
                                       ' tempCount += 1

                                       Return 10
                                   End Function)
                ElseIf CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess = False Then
                    Await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Function()

                                                                                'Await Task.Delay(1000)
                                                                                If evalprogress IsNot Nothing Then
                                                                                evalprogress.Report(10)
                                                                                End If
                                                                                ' tempCount += 1

                                                                                Return 10
                                                                                End Function)

                End If

                tmpevalitem = GrabFromOnlineSource(item.Item(i).name, item.Item(i).evaluationSource, New Progress(Of Integer)(Function(value) InlineAssignHelper(a, value)))
                tmpevalitem.Wait()
                If CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess Then
                    Await Task.Run(Function()

                                       'Await Task.Delay(1000)
                                       If evalprogress IsNot Nothing Then
                                           ' ReportProgress(70, Nothing)
                                           evalprogress.Report(70)
                                       End If
                                       ' tempCount += 1

                                       Return 70
                                   End Function)
                ElseIf CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess = False Then
                    Await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Function()

                                                                                'Await Task.Delay(1000)
                                                                                If evalprogress IsNot Nothing Then
                                                                                'evalprogress.Report(70)
                                                                                End If
                                                                                ' tempCount += 1

                                                                                Return 70
                                                                                End Function)

                End If
                ' ItemValuation.tmpProgressIndicator.Report(60)

                If tmpevalitem.Result IsNot Nothing Then
                    autoitem.AddRange(tmpevalitem.Result)
                Else
                    Continue For
                End If
            Else
                Dim tmpevalinfoauto As EvaluationInfo
                tmpevalinfoauto.currentItem = item.Item(i).name
                tmpevalinfoauto.evaluationcondition = item.Item(i).itemcondition
                autoitem.Add(tmpevalinfoauto)
            End If
        Next i
        autoitem.Add(Nothing) 'use nothing as an indicator of a new item.
    End If

    If ManualEvaluation Then
        Dim done(4) As Boolean
        done(0) = False
        done(1) = False
        done(2) = False
        done(3) = False
        'MsgBox("item information count: " + tmpiteminfo2.Count.ToString)
        For f = 0 To tmpiteminfo2.Count - 1
            'MsgBox(tmpiteminfo2.Item(f).evaluationSource)
            Select Case tmpiteminfo2.Item(f).evaluationSource
                Case Is = "Gamestop"
                    tmpevalinfo.valuationsourceid = 1
                Case Is = "Amazon"
                    tmpevalinfo.valuationsourceid = 2
                Case Is = "Ebay"
                    tmpevalinfo.valuationsourceid = 3
                    'add more sources here later
            End Select
            Select Case tmpiteminfo2.Item(f).itemcondition
                Case Is = ItemCondition.Broken
                    'If done(0) = False Then
                    mode = pricefunctions.Mode(broken.ToArray)
                    max = pricefunctions.MaxValue(broken.ToArray)
                    min = pricefunctions.MinValue(broken.ToArray)
                    avg = pricefunctions.AveragePrice(broken.ToArray)
                    standarddev = pricefunctions.standarddeviation(broken.ToArray)
                    done(0) = True
                   ' End If
                Case Is = ItemCondition.LooksLikeNew
                    'If done(1) = False Then
                    mode = pricefunctions.Mode(Lookslikenew.ToArray)
                    max = pricefunctions.MaxValue(Lookslikenew.ToArray)
                    min = pricefunctions.MinValue(Lookslikenew.ToArray)
                    avg = pricefunctions.AveragePrice(Lookslikenew.ToArray)
                    standarddev = pricefunctions.standarddeviation(Lookslikenew.ToArray)
                    done(1) = True
                   ' End If
                Case Is = ItemCondition.SomeDamage
                    ' If done(2) = False Then
                    mode = pricefunctions.Mode(damaged.ToArray)
                    max = pricefunctions.MaxValue(damaged.ToArray)
                    min = pricefunctions.MinValue(damaged.ToArray)
                    avg = pricefunctions.AveragePrice(damaged.ToArray)
                    standarddev = pricefunctions.standarddeviation(damaged.ToArray)
                    done(2) = True
                   ' End If
                Case Is = ItemCondition.SomewhatUsed
                    'If done(3) = False Then
                    mode = pricefunctions.Mode(somewhatused.ToArray)
                    max = pricefunctions.MaxValue(somewhatused.ToArray)
                    min = pricefunctions.MinValue(somewhatused.ToArray)
                    avg = pricefunctions.AveragePrice(somewhatused.ToArray)
                    standarddev = pricefunctions.standarddeviation(somewhatused.ToArray)
                    done(3) = True
                    ' End If

            End Select

            'assign values to minimum price, maximum price, and the other prices.
            If min > 0 Then
                tmpevalinfo.MinimumPrice = min
            End If
            If mode > 0 Then
                tmpevalinfo.ReoccuringPrice = mode
            End If
            If avg > 0 Then
                tmpevalinfo.avgprice = avg
            End If
            If max > 0 Then
                tmpevalinfo.MaximumPrice = max
            End If
            If standarddev > 0 Then  'And standarddev < 1 Then
                tmpevalinfo.avgdeviation = standarddev
            End If
            min = 0
            max = 0
            mode = 0
            avg = 0
            tmpevalinfo.currentItem = tmpiteminfo2.Item(f).name
            tmpevalinfo.evaluationcondition = tmpiteminfo2.Item(f).itemcondition
            'MsgBox(tmpiteminfo2.Item(f).itemcondition)
            tmpevalinfo.evaluated = True
            itemevalresultarr.Add(tmpevalinfo)

        Next f
        'Dim iteminfoc As New ItemInformation
        'For s = 0 To tmpiteminfo.Count - 1
        '    iteminfoc.itemsevaluate.Add(tmpiteminfo.Item(s).name)
        '    'add other item information and change to iteminfo type once I get information to display correctly on findquote form
        'Next s
        Dim itemval As New ItemValuation
        Dim tmpevalsource As New EvaluationSource
        Using uie As New DataAccess.SQLiteDb
            For h = 0 To tmpiteminfo.Count - 1
                tmpevalsource.EvaluationSourceName = tmpiteminfo.Item(h).evaluationSource
                tmpevalsource.EvaluationWebAddress = (From EvalWeb In uie.ValuationSources Where EvalWeb.ValuationSourceName = tmpevalsource.EvaluationSourceName Select EvalWeb).ToString
                Await itemval.archiveitem(tmpiteminfo.Item(h).name, tmpiteminfo.Item(h).name, tmpevalsource)
            Next
        End Using
        'delete all the evaluated items from the database for next evaluation

        Await ClearEvalTable()
        'return regular results
        Return itemevalresultarr
    Else
        'return automated evaluation results
        'results are archived as they are retrieved so delete data from the table below
        'delete all the evaluated items from the database for next evaluation
        Return autoitem
    End If

End Function

Here's the inner function's signature:

Private Async Function GrabFromOnlineSource(itemname As String, WebsiteSource As String, progress As IProgress(Of Integer)) As Task(Of List(Of EvaluationInfo))

Here's what I have tried so far (updated):

first try:

  tmpevalitem = Await GrabFromOnlineSource(item.Item(i).name, item.Item(i).evaluationSource, New Progress(Of Integer)(Function(value) InlineAssignHelper(totalprogress, value))). 'replace totalprogress with the a integer I mentioned in the comments.
                  tmpevalitem.Wait()

second try:

   tmpevalitem = GrabFromOnlineSource(item.Item(i).name, item.Item(i).evaluationSource, New Progress(Of IProgress(Of Integer))(Function(value) InlineAssignHelper(evalprogress, value)))
                        tmpevalitem.Wait()

The above code though ends up in an error about data type progress not being correct. I really need to pass my progress from GrabFromOnlineSource to the evalprogress variable or otherwise I will have differing values sent to the main program.

Note: I technically could have GrabFromOnlineSource called for each evaluation source used (4 total possible as of this moment). In addition, each evaluation source sent to GrabFromOnlineSource has its own progress reported counted toward the current evaluation source (i.e. ebay has its own progress, amazon its own, etc).

The EvaluationInfo and ItemInfo Structures:

     Public Structure EvaluationInfo
        Dim ReoccuringPrice As Double
        Dim MinimumPrice As Double
        Dim MaximumPrice As Double
        Dim avgprice As Double
        Dim avgdeviation As Double
        Dim currentItem As String
        Dim valuationsourceid As Integer
        Dim evaluationcondition As ItemCondition 'i.e. used,new,broken enum
        Dim evaluated As Boolean
    End Structure

 Public Structure ItemInfo
            Public Property name As String
            Public Property price As Double
            Public Property damaged As String
            Public Property aquisitiondate As Date
            Public Property evaluationSource As String
            Public Property itemcondition As ItemCondition
            Public Property itempicture As Byte()
            Public Property itemid As Integer

        End Structure

More Information:

One thing I forgot to mention progress reporting does work with task.run from evaluateitem function but I prefer to modularize my code a bit to prevent one action from taking too much space and that's why I have not moved the code from GrabFromOnlineSource into evaluateitem.

Body:
Sorry for the delay in answering my own question but here goes (I am not perfect at formatting code so an editor or admin can pretty it up):

This is the class test code I used separately from my projects dll to test this was working (aka I created a new project to test my theory):

Imports Windows.ApplicationModel.Core
Imports Windows.UI.Core

Public Class Progresstestclass
    Private Shared Property totalprogress As Integer
    Public Shared Async Function MainFunction(progress As IProgress(Of Integer)) As Task(Of Boolean)

        totalprogress = 5
        progress.Report(totalprogress)
        Dim a As New String("")
        Do While totalprogress > 0 And totalprogress < 70 And a <> "Success"
            Await InnerFunction(New Progress(Of Integer)(Function(value) InlineAssignHelper(totalprogress, value)))
            progress.Report(totalprogress - 5)
            Await System.Threading.Tasks.Task.Delay(1000)
            progress.Report(totalprogress)

        Loop
        Return True
    End Function
    Private Shared Async Function InnerFunction(progress2 As IProgress(Of Integer)) As Task(Of String)
    progress2.report(30)
            Await System.Threading.Tasks.Task.Delay(1000)
            progress2.Report(40)
          Await System.Threading.Tasks.Task.Delay(1000)

        Return "Success"
    End Function
    Public Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
        target = value
        Return value
    End Function

End Class

Another thing that changed inside my main function was my while loop was a little wrong. I needed put in delays in-between passing progress reports back or else it did not pass it back or showed it at 100% at the end making my progress report useless. Anyone can still comment on best how to do this. Its a crazy thing that forgoting delays can mess up a program!

Everything else is pretty much the same. Except I put delays as above to have it stop passing progress long enough for the natural eye to see the progress happening.


问:
Deprecated function: require_once()
Recently, I started converting my Drupal 6 module on PHP 5.2.x to Drupal 7 on PHP 5.3.x, and now I get following warning

Deprecated function: Assigning the
  return value of new by reference is
  deprecated in require_once() (line
  27 of
  C:\Users\ajinkya\Desktop\xampp\php\PEAR\SOAP\WSDL.php).

Line 27 of WSDL.php is : require_once 'HTTP/Request.php';

I am not able to figure out what is the cause of this warning.  Has the behavior of require_once() changed in PHP 5.3.x?

file.inc in Drupal 7 has a line : require_once DRUPAL_ROOT . '/includes/stream_wrappers.inc; and it does not throw any warning. Why?

If I put error_reporting(E_ALL & ~E_DEPRECATED); in a setting.php of Drupal 7, the warning goes away. Is it good to suppress a warning like that?

答:
It is good to suppress an error like that?

Depends. Ignoring errors is never a good idea. Keeping strict reporting enabled is a good idea for the development stage. However, once PHP advises you with a debug message like that, you evaluate it and base an informed decision on that.

You can either work around the mentioned issue, fix it, or ignore it if it's not an actual problem.

Assigning an object by reference is unneeded and henceforth deprecated. It's however not a problem that will lead to errors, and it will never be semantically forbidden. Removing the syntax construct in future versions would break compatibility, so won't happen. The informed choice in this case is either to acknowledge and ignore the syntax hint, or remove the & since it's unneeded and its removal in this particular instance is mostly unlikely to break the behaviour.

Title: Deprecated function: require_once()


问:
Python Pandas Set Value in DataFrame where Index has Multiple Identical Label Values
I want to set a value in a row in a pandas dataframe where the row index has duplicate values and the value of a date column is the max value for the selected index value.

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
</code>```

so I want to set the End_Date for index value 'B' where the Start_Date is the Max for 'B'

What is the best way to do this?

EDIT:

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
  D      2017-11-01    np.Nat
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat
</code>```

Through separate processes I come to learn that the End_Date corresponding to row #3 (Index == 'B', Start_Date == '2017-10-18 is 2017-10-25.  I also separately find that row #5(Index == 'D', Start_Date == '2017-11-01'  is 2017-11-03.  So I want to fill those values into End_Date one at a time.  Since I don't have an End_Date value for the last row (Index = 'E', Start_Date == '2017-11-13') that will stay empty.

Note that 'D' is unique while 'B' is not.

Output:

My dataframe:

```<code>Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18   2017-10-25
  C      2017-10-09   2017-10-30
  D      2017-11-01   2017-11-03
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat
</code>```

Not that the values 2017-10-25 in row 3 and 2017-11-03 came from another process and we can assume they are stored in variables - that can then be used to populate the initial dataframe to obtain the output.

答:
Figured it out:

df = df.reset_index() removes the label as index and gives me a numerical index with unique values

```<code>Index     Item       Start_Date   End_Date

  0          A      2017-10-01   2017-10-13
  1          B      2017-10-07   2017-10-15
  2          B      2017-10-18    np.Nat
  3          C      2017-10-09   2017-10-30
  4          D      2017-11-01    np.Nat
  5          E      2017-11-03   2017-11-09
  6          E      2017-11-13    np.Nat
</code>```

idx_val = df[df['Item'] == item][-1:].index.values[0]

gives me the index value of the item I provide with the maximum Start_Date.

So if I have an End_Date value of '2017-10-25' for item 'B' coming from my other process, I get the index of the row with the max Start_Date for item B by using the above line of code.  If item == B, idx_val will equal 2.

I then simply set End_Date for the row where idx_val == 2:

df.loc[idx_val, 'End_Date'] = pd.to_datetime('2017-10-25')

and the result is:

```<code>Index     Item       Start_Date   End_Date

  0          A      2017-10-01   2017-10-13
  1          B      2017-10-07   2017-10-15
  2          B      2017-10-18   2017-10-25
  3          C      2017-10-09   2017-10-30
  4          D      2017-11-01    np.Nat
  5          E      2017-11-03   2017-11-09
  6          E      2017-11-13    np.Nat
</code>```

Body:
I want to set a value in a row in a pandas dataframe where the row index has duplicate values and the value of a date column is the max value for the selected index value.

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30

so I want to set the End_Date for index value 'B' where the Start_Date is the Max for 'B'

What is the best way to do this?

EDIT:

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18    np.Nat
  C      2017-10-09   2017-10-30
  D      2017-11-01    np.Nat
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat

Through separate processes I come to learn that the End_Date corresponding to row #3 (Index == 'B', Start_Date == '2017-10-18 is 2017-10-25.  I also separately find that row #5(Index == 'D', Start_Date == '2017-11-01'  is 2017-11-03.  So I want to fill those values into End_Date one at a time.  Since I don't have an End_Date value for the last row (Index = 'E', Start_Date == '2017-11-13') that will stay empty.

Note that 'D' is unique while 'B' is not.

Output:

My dataframe:

Index  Start_Date   End_Date

  A      2017-10-01   2017-10-13
  B      2017-10-07   2017-10-15
  B      2017-10-18   2017-10-25
  C      2017-10-09   2017-10-30
  D      2017-11-01   2017-11-03
  E      2017-11-03   2017-11-09
  E      2017-11-13    np.Nat

Not that the values 2017-10-25 in row 3 and 2017-11-03 came from another process and we can assume they are stored in variables - that can then be used to populate the initial dataframe to obtain the output.

Body:
Figured it out:

df = df.reset_index() removes the label as index and gives me a numerical index with unique values

Index     Item       Start_Date   End_Date

  0          A      2017-10-01   2017-10-13
  1          B      2017-10-07   2017-10-15
  2          B      2017-10-18    np.Nat
  3          C      2017-10-09   2017-10-30
  4          D      2017-11-01    np.Nat
  5          E      2017-11-03   2017-11-09
  6          E      2017-11-13    np.Nat

idx_val = df[df['Item'] == item][-1:].index.values[0]

gives me the index value of the item I provide with the maximum Start_Date.

So if I have an End_Date value of '2017-10-25' for item 'B' coming from my other process, I get the index of the row with the max Start_Date for item B by using the above line of code.  If item == B, idx_val will equal 2.

I then simply set End_Date for the row where idx_val == 2:

df.loc[idx_val, 'End_Date'] = pd.to_datetime('2017-10-25')

and the result is:

Index     Item       Start_Date   End_Date

  0          A      2017-10-01   2017-10-13
  1          B      2017-10-07   2017-10-15
  2          B      2017-10-18   2017-10-25
  3          C      2017-10-09   2017-10-30
  4          D      2017-11-01    np.Nat
  5          E      2017-11-03   2017-11-09
  6          E      2017-11-13    np.Nat


问:
Adding column to sheet with GAS

In my google sheet the last column with data is "S" . I'm trying to create a script which will loop through the rows and place 'test' in column T if the value in S starts with "FIN"

```<code>function daysSinceContact() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mainSheet = ss.getSheetByName("test_sheet");
  var main_rows = mainSheet.getDataRange().getValues();

  var updated = [];
  for (i in main_rows) {
    var row = main_rows[i]
       if ((row[18].substring(0, 3) == 'FIN') ) {
         Logger.log(row[18])
           row[19]=='test'
       }

    updated.push(row);
  }
  var main_range = mainSheet.getDataRange();
  mainSheet.getDataRange().setValues(updated);

}
</code>```

However when I run this I see nothing in column T. What am I doing wrong?

答:
How about this modifications?

Modification points :

When it substitutes 'test' for row[19], it uses row[19]='test'.

This is pointed out by @Crazy Ivan

For the rows without 'FIN', '' is added to row[19].

By this, the length of each element in 2 dimensional array becomes the same.

The range retrieved by getDataRange() is different from that of the current data. Because one column was added.

So getRange(1, 1, updated.length, updated[0].length) is used.

The modified script which was reflected above points is as follows.

Modified script :

```<code>function daysSinceContact() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mainSheet = ss.getSheetByName("test_sheet");
  var main_rows = mainSheet.getDataRange().getValues();

  var updated = [];
  for (i in main_rows) {
    var row = main_rows[i]
       if ((row[18].substring(0, 3) == 'FIN') ) {
         Logger.log(row[18])
           row[19] = 'test'
       } else {
         row[19] = ''; // Added
       }

    updated.push(row);
  }
  // var main_range = mainSheet.getDataRange(); // This is not used.
  mainSheet.getRange(1, 1, updated.length, updated[0].length).setValues(updated); // Modified

}
</code>```

If I misunderstand your question, please tell me. I would like to modify it.

Title: Adding column to sheet with GAS

Body:
In my google sheet the last column with data is "S" . I'm trying to create a script which will loop through the rows and place 'test' in column T if the value in S starts with "FIN"

function daysSinceContact() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mainSheet = ss.getSheetByName("test_sheet");
  var main_rows = mainSheet.getDataRange().getValues();

  var updated = [];
  for (i in main_rows) {
    var row = main_rows[i]
       if ((row[18].substring(0, 3) == 'FIN') ) {
         Logger.log(row[18])
           row[19]=='test'
       }

    updated.push(row);
  }
  var main_range = mainSheet.getDataRange();
  mainSheet.getDataRange().setValues(updated);

}

However when I run this I see nothing in column T. What am I doing wrong?

Body:
How about this modifications?

Modification points :

When it substitutes 'test' for row[19], it uses row[19]='test'.

This is pointed out by @Crazy Ivan

For the rows without 'FIN', '' is added to row[19].

By this, the length of each element in 2 dimensional array becomes the same.

The range retrieved by getDataRange() is different from that of the current data. Because one column was added.

So getRange(1, 1, updated.length, updated[0].length) is used.

The modified script which was reflected above points is as follows.

Modified script :

function daysSinceContact() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mainSheet = ss.getSheetByName("test_sheet");
  var main_rows = mainSheet.getDataRange().getValues();

  var updated = [];
  for (i in main_rows) {
    var row = main_rows[i]
       if ((row[18].substring(0, 3) == 'FIN') ) {
         Logger.log(row[18])
           row[19] = 'test'
       } else {
         row[19] = ''; // Added
       }

    updated.push(row);
  }
  // var main_range = mainSheet.getDataRange(); // This is not used.
  mainSheet.getRange(1, 1, updated.length, updated[0].length).setValues(updated); // Modified

}

If I misunderstand your question, please tell me. I would like to modify it.


问:
Getting all children of collection with has_many relationship
If I have a collection of Posts, is there anyway to get all Comments for all of those posts using method chaining or scopes?

For example:

```<code>posts = Post.where(published: true)
comments = posts.comments

# vs
comments = []
posts.each do |post|
  comments.push(post.comments)
end
</code>```

答:
Best way:

```<code>Comment.joins(:post).where(post: {published: true})
</code>```

or if you have a posts variable that is a ActiveRecord Relation:

```<code>Comment.joins(:post).where(post: posts)
</code>```

Body:
If I have a collection of Posts, is there anyway to get all Comments for all of those posts using method chaining or scopes?

For example:

posts = Post.where(published: true)
comments = posts.comments

# vs
comments = []
posts.each do |post|
  comments.push(post.comments)
end

Body:
Best way:

Comment.joins(:post).where(post: {published: true})

or if you have a posts variable that is a ActiveRecord Relation:

Comment.joins(:post).where(post: posts)