问:
How to send a SOAP headers in Progress 4GL
Hello Progress 4GL Developers,

I would like to consume the UPS Tracking API in an ABL session.

I have ran the WSDLAnalyser for the UPS WSDL and have followed the documentation.

Here is an example of the request in XML that I wish to send (including header):

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" xmlns:v2="http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0" xmlns:v11="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
<soapenv:Header>
   <v1:UPSSecurity>
      <v1:UsernameToken>
         <v1:Username>MYUSERNAME</v1:Username>
         <v1:Password>MYPASSWORD</v1:Password>
      </v1:UsernameToken>
      <v1:ServiceAccessToken>
         <v1:AccessLicenseNumber>MYLICENSENUMBER</v1:AccessLicenseNumber>
      </v1:ServiceAccessToken>
   </v1:UPSSecurity>
</soapenv:Header>
<soapenv:Body>
   <v2:TrackRequest>
      <v2:ReferenceNumber>
         <v2:Code>MYCODE</v2:Code>
         <v2:Value>MYORDERNUM</v2:Value>
      </v2:ReferenceNumber>
   </v2:TrackRequest>
</soapenv:Body>
</soapenv:Envelope>
</code>```

This request works as expected when sent using SOAPUI to test the request.
Here is my Progress4GL code so far to try and make the same request:

```<code>{us/mf/mfdtitle.i}
{/qond/apps/mfgpro/customizations/mfg/work/src/us/xx/xxwhsxml.i}

define variable hs as handle no-undo.
define variable hp as handle no-undo.
DEFINE VARIABLE cBody  AS LONGCHAR NO-UNDO.
DEFINE VARIABLE cBody2 AS LONGCHAR NO-UNDO.

cBody = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" xmlns:v2="http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0" xmlns:v11="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
<soapenv:Header>
   <v1:UPSSecurity>
      <v1:UsernameToken>
         <v1:Username>MYUSERNAME</v1:Username>
         <v1:Password>MYPASSWORD</v1:Password>
      </v1:UsernameToken>
      <v1:ServiceAccessToken>
         <v1:AccessLicenseNumber>MYLICENSENUMBER</v1:AccessLicenseNumber>
      </v1:ServiceAccessToken>
   </v1:UPSSecurity>
</soapenv:Header>
<soapenv:Body>
   <v2:TrackRequest>
      <v2:ReferenceNumber>
         <v2:Code>MYCODE</v2:Code>
         <v2:Value>MYORDERNUM</v2:Value>
      </v2:ReferenceNumber>
   </v2:TrackRequest>
</soapenv:Body>
</soapenv:Envelope>'.

create server hs.
hs:connect( "-WSDL /home/jbetts/track/Track.wsdl -Port TrackPort -TargetNamespace http://www.ups.com/WSDL/XOLTWS/Track/v2.0 -nohostverify -nosessionreuse" ).

run TrackPortType set hp on server hs.
run ProcessTrack in hp ( input cBody, output cBody2 ).

delete procedure hp.
hs:disconnect().
delete object hs.
</code>```

I think the problem is that I need to send the header in a certain way when I run the ProcessTrack procedure (using SET-CALLBACK-PROCEDURE) but I'm not sure how.

Thanks in advance!

答:
SET-CALLBACK-PROCEDURE is the way.

You need to do something like this (setRequestSessionHandler is the name of the procedure so it can be whatever you want) before you RUN the SOAP-call:

```<code>hp:SET-CALLBACK-PROCEDURE("REQUEST-HEADER", "setRequestSessionHeader").
</code>```

The request-callback has two input and two output parameters (names taken from the documentation, they can be called anything as long as input/output and datatype is correct):

```<code>DEFINE OUTPUT PARAMETER hSOAPHeader         AS HANDLE    NO-UNDO.
DEFINE INPUT  PARAMETER cOperationNamespace AS CHARACTER NO-UNDO.
DEFINE INPUT  PARAMETER cOperationLocalName AS CHARACTER NO-UNDO.
DEFINE OUTPUT PARAMETER plDeleteOnDone AS LOGICAL   NO-UNDO.
</code>```

hSOAPHeader — A handle to a SOAP header object that encapsulates the header of the SOAP message
  that is about to be sent (request header) or that has just been received (response header). In a response
  header handler, the SOAP header object has no content if the NUM-HEADER-ENTRIES attribute on the
  object handle returns the value 0; otherwise it contains one or more SOAP header entries. In a request
  header handler, this is an OUTPUT parameter, therefore if the outgoing SOAP message requires a SOAP
  header, you must either build a SOAP header for this parameter to reference or provide an existing SOAP
  header saved from a previous response callback.

cOperationNamespace — Contains the namespace portion of the operation's qualified name. Use this
  parameter together with the cOperationLocalName parameter if you need to identify the operation for
  which the SOAP message is being sent or received.

cOperationLocalName — Contains the local-name portion of the operation's qualified name. Use this
  parameter together with the cOperationNamespace parameter if you need to identify the operation for
  which the SOAP message is being sent or received.

lDeleteOnDone — (Request callback only) Tells OpenEdge to delete the SOAP header object and all of
  the parsed XML after the SOAP header has been inserted into the out-bound SOAP message

This is what I do to mimic WS-Security, not exactly what you need and also quite a lot of code. You should be able to "mine it" for whatever you need.

```<code>PROCEDURE setRequestSessionHeader :
/*------------------------------------------------------------------------------
  Purpose:
  Parameters:  <none>
  Notes:
------------------------------------------------------------------------------*/

DEFINE OUTPUT PARAMETER phHeader       AS HANDLE    NO-UNDO.
DEFINE INPUT  PARAMETER pcNamespace    AS CHARACTER NO-UNDO.
DEFINE INPUT  PARAMETER pcLocalNS      AS CHARACTER NO-UNDO.
DEFINE OUTPUT PARAMETER plDeleteOnDone AS LOGICAL   NO-UNDO.

DEFINE VARIABLE hSoapHeaderEntryref1    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hSoapHeaderEntryref2    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hSoapHeaderEntryref3    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hSoapHeaderEntryref4    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hSoapHeaderEntryref5    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hXDocument              AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASSecurity            AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASUsernameToken       AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASUserName            AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASPassword            AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASPasswordType        AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASNonce               AS HANDLE      NO-UNDO.
DEFINE VARIABLE hWSUCreated             AS HANDLE      NO-UNDO.
DEFINE VARIABLE hADDMessageID           AS HANDLE      NO-UNDO.
DEFINE VARIABLE hADDTo                  AS HANDLE      NO-UNDO.
DEFINE VARIABLE hADDAction              AS HANDLE      NO-UNDO.
DEFINE VARIABLE hAMA_SecurityHostedUser AS HANDLE      NO-UNDO.
DEFINE VARIABLE hUserId                 AS HANDLE      NO-UNDO.
DEFINE VARIABLE hTxt                    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hAttr                   AS HANDLE      NO-UNDO.
DEFINE VARIABLE hRootNode               AS HANDLE      NO-UNDO.

/* Namespaces */
DEFINE VARIABLE cNSAddressing           AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cNSSecurity             AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cNSSecurityUtils        AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cNSAmaSec               AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cMessageId              AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cUserName               AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cPasswordClear          AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cPasswordDigest         AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cCreated                AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cAction                 AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cTo                     AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cNonceB64               AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cOfficeId               AS CHARACTER   NO-UNDO.
DEFINE VARIABLE mNonce                  AS MEMPTR      NO-UNDO.

ASSIGN
    cNSAddressing     = "http://www.w3.org/2005/08/addressing"
    cNSSecurity       = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    cNSSecurityUtils  = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    cNSAmaSec         = "http://illkeepthisasecret..."
    cAction           = "http://illkeepthisasecret..."
    cTo               = "https://noded1.production.webservices.amadeus.com/1ASIWIBNAIT".

ASSIGN
    cUserName         = "usernamegoeshere"
    cOfficeId         = "anothersettinggoeshere"
    cPasswordClear    = "passwordgoeshere".

/* Delete header when done! */
ASSIGN
    plDeleteOnDone = TRUE.

CREATE SOAP-HEADER ghSoapHeader.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref1.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref2.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref3.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref4.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref5.

CREATE X-DOCUMENT hXDocument.
CREATE X-NODEREF hRootNode.
CREATE X-NODEREF hOASSecurity.
CREATE X-NODEREF hTxt.
CREATE X-NODEREF hOASUsernameToken.
CREATE X-NODEREF hOASPassword.
CREATE X-NODEREF hOASUserName.
CREATE X-NODEREF hOASNonce.
CREATE X-NODEREF hADDMessageID.
CREATE X-NODEREF hADDTo.
CREATE X-NODEREF hADDAction.
CREATE X-NODEREF hWSUCreated.
CREATE X-NODEREF hAMA_SecurityHostedUser.
CREATE X-NODEREF hUserId.

/* Not DATETIME-TZ! */
DEFINE VARIABLE dtZuluNow AS DATETIME    NO-UNDO.

/* Genereate a random key and base64-encode it */
SET-SIZE(mNonce) = 16.

mNonce = GENERATE-RANDOM-KEY.

cNonceB64 = BASE64-ENCODE(mNonce).

/* Get time in UTC/GMT/ZULU/Timezone 0 */
dtZuluNow = DATETIME-TZ(NOW,0).

/* Manipulate the date string to fit specs... */
ASSIGN
    cMessageId = LC(SUBSTRING(STRING(GENERATE-UUID), 8, 20))
    cCreated = STRING(dtZuluNow, "9999-99-99THH:MM:SS") + ":000Z".
/* This is internal stuff for generating a digest... */
RUN generatePasswordDigest( mNonce, cCreated, cPasswordClear, OUTPUT cPasswordDigest).

/* Root node */
hXDocument:CREATE-NODE-NAMESPACE(hRootNode, "", "root", "element").
hXDocument:INSERT-BEFORE(hRootNode, ?).

/**** Addressing ****/
/* MessageID */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref1).
hXDocument:CREATE-NODE-NAMESPACE(hADDMessageID, cNSAddressing, "MessageID", "ELEMENT").
hRootNode:APPEND-CHILD(hAddMessageID).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cMessageId.
hADDMessageId:APPEND-CHILD(hTxt).
hSoapHeaderEntryref1:SET-NODE(hADDMessageID).

/* Action */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref2).
hXDocument:CREATE-NODE-NAMESPACE(hADDAction, cNSAddressing, "Action", "ELEMENT").
hRootNode:APPEND-CHILD(hADDAction).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cAction.
hADDAction:APPEND-CHILD(hTxt).
hSoapHeaderEntryref2:SET-NODE(hADDAction).

/* To */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref3).
hXDocument:CREATE-NODE-NAMESPACE(hADDTo, cNSAddressing, "To", "ELEMENT").
hRootNode:APPEND-CHILD(hADDTo).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cTo.
hADDTo:APPEND-CHILD(hTxt).
hSoapHeaderEntryref3:SET-NODE(hADDTo).

/**** Security ****/
/* Root node */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref4).
hXDocument:CREATE-NODE-NAMESPACE(hOASSecurity, cNSSecurity, "Security", "ELEMENT").
hRootNode:APPEND-CHILD(hOASSecurity).

/* UserNameToken node */
hXDocument:CREATE-NODE-NAMESPACE(hOASUsernameToken, cNSSecurity, "UsernameToken", "ELEMENT").
hOASUsernameToken:SET-ATTRIBUTE("Id", "UsernameToken-1").
hOASSecurity:INSERT-BEFORE(hOASUsernameToken, ?).

/* Username */
hXDocument:CREATE-NODE-NAMESPACE(hOASUserName, cNSSecurity, "Username", "ELEMENT").
hRootNode:APPEND-CHILD(hOASUserName).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cUserName.
hOASUserName:APPEND-CHILD(hTxt).
hOASUsernameToken:APPEND-CHILD(hOASUserName).

/* Nonce */
hXDocument:CREATE-NODE-NAMESPACE(hOASNonce, cNSSecurity, "Nonce", "ELEMENT").
hOASNonce:SET-ATTRIBUTE("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary").
hOASUsernameToken:APPEND-CHILD(hOASNonce).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cNonceB64.
hOASNonce:APPEND-CHILD(hTxt).

/* Password hash */
hXDocument:CREATE-NODE-NAMESPACE(hOASPassword, cNSSecurity, "Password", "ELEMENT").
hOASPassword:SET-ATTRIBUTE("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest").
hOASUsernameToken:APPEND-CHILD(hOASPassword).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cPasswordDigest.
hOASPassword:APPEND-CHILD(hTxt).

/* Created - timestamp */
hXDocument:CREATE-NODE-NAMESPACE(hWSUCreated, cNSSecurityUtils, "Created", "ELEMENT").
hOASUsernameToken:APPEND-CHILD(hWSUCreated).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cCreated.
hWSUCreated:APPEND-CHILD(hTxt).
hSoapHeaderEntryref4:SET-NODE(hOASSecurity).

/**** AMA_SecurityHostedUser ****/
/* Root node */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref5).
hXDocument:CREATE-NODE-NAMESPACE(hAMA_SecurityHostedUser, cNSAMASec, "AMA_SecurityHostedUser", "ELEMENT").
hRootNode:APPEND-CHILD(hAMA_SecurityHostedUser).

/* UserID */
hXDocument:CREATE-NODE-NAMESPACE(hUserID, cNSAMASec, "UserID", "ELEMENT").

hUserID:SET-ATTRIBUTE("AgentDutyCode", "SU").
hUserID:SET-ATTRIBUTE("RequestorType", "U").
hUserID:SET-ATTRIBUTE("PseudoCityCode", cOfficeId).
hUserID:SET-ATTRIBUTE("POS_Type", "1").

hAMA_SecurityHostedUser:APPEND-CHILD(hUserID).
hSoapHeaderEntryref5:SET-NODE(hAMA_SecurityHostedUser).

/* Output the header */
phHeader = ghSoapHeader.

/* Cleanup */
IF VALID-HANDLE(hOASSecurity) THEN
    DELETE OBJECT hOASSecurity.
IF VALID-HANDLE(hOASUsernameToken) THEN
    DELETE OBJECT hOASUsernameToken.
IF VALID-HANDLE(hOASUserName) THEN
    DELETE OBJECT hOASUserName.
IF VALID-HANDLE(hOASPassword) THEN
    DELETE OBJECT hOASPassword.
IF VALID-HANDLE(hADDMessageID) THEN
    DELETE OBJECT hADDMessageID.
IF VALID-HANDLE(hOASNonce) THEN
    DELETE OBJECT hOASNonce.
IF VALID-HANDLE(hTxt) THEN
    DELETE OBJECT hTxt.
IF VALID-HANDLE(hADDTo) THEN
    DELETE OBJECT hADDTo.
IF VALID-HANDLE(hWSUCreated) THEN
    DELETE OBJECT hWSUCreated.
IF VALID-HANDLE(hADDAction) THEN
    DELETE OBJECT hADDAction.
IF VALID-HANDLE(hXDocument) THEN
    DELETE OBJECT hXDocument.
IF VALID-HANDLE(hRootNode) THEN
    DELETE OBJECT hRootNode.
IF VALID-HANDLE(hSoapHeaderEntryRef1) THEN
    DELETE OBJECT hSoapHeaderEntryRef1.
IF VALID-HANDLE(hSoapHeaderEntryRef2) THEN
    DELETE OBJECT hSoapHeaderEntryRef2.
IF VALID-HANDLE(hSoapHeaderEntryRef3) THEN
    DELETE OBJECT hSoapHeaderEntryRef3.
IF VALID-HANDLE(hSoapHeaderEntryRef4) THEN
    DELETE OBJECT hSoapHeaderEntryRef4.
IF VALID-HANDLE(hSoapHeaderEntryRef5) THEN
    DELETE OBJECT hSoapHeaderEntryRef5.
IF VALID-HANDLE(hAMA_SecurityHostedUser) THEN
    DELETE OBJECT hAMA_SecurityHostedUser.
IF VALID-HANDLE(hUserId) THEN
    DELETE OBJECT hUserId.

END.
</code>```

Body:
Hello Progress 4GL Developers,

I would like to consume the UPS Tracking API in an ABL session.

I have ran the WSDLAnalyser for the UPS WSDL and have followed the documentation.

Here is an example of the request in XML that I wish to send (including header):

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" xmlns:v2="http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0" xmlns:v11="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
<soapenv:Header>
   <v1:UPSSecurity>
      <v1:UsernameToken>
         <v1:Username>MYUSERNAME</v1:Username>
         <v1:Password>MYPASSWORD</v1:Password>
      </v1:UsernameToken>
      <v1:ServiceAccessToken>
         <v1:AccessLicenseNumber>MYLICENSENUMBER</v1:AccessLicenseNumber>
      </v1:ServiceAccessToken>
   </v1:UPSSecurity>
</soapenv:Header>
<soapenv:Body>
   <v2:TrackRequest>
      <v2:ReferenceNumber>
         <v2:Code>MYCODE</v2:Code>
         <v2:Value>MYORDERNUM</v2:Value>
      </v2:ReferenceNumber>
   </v2:TrackRequest>
</soapenv:Body>
</soapenv:Envelope>

This request works as expected when sent using SOAPUI to test the request.
Here is my Progress4GL code so far to try and make the same request:

{us/mf/mfdtitle.i}
{/qond/apps/mfgpro/customizations/mfg/work/src/us/xx/xxwhsxml.i}

define variable hs as handle no-undo.
define variable hp as handle no-undo.
DEFINE VARIABLE cBody  AS LONGCHAR NO-UNDO.
DEFINE VARIABLE cBody2 AS LONGCHAR NO-UNDO.

cBody = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" xmlns:v2="http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0" xmlns:v11="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
<soapenv:Header>
   <v1:UPSSecurity>
      <v1:UsernameToken>
         <v1:Username>MYUSERNAME</v1:Username>
         <v1:Password>MYPASSWORD</v1:Password>
      </v1:UsernameToken>
      <v1:ServiceAccessToken>
         <v1:AccessLicenseNumber>MYLICENSENUMBER</v1:AccessLicenseNumber>
      </v1:ServiceAccessToken>
   </v1:UPSSecurity>
</soapenv:Header>
<soapenv:Body>
   <v2:TrackRequest>
      <v2:ReferenceNumber>
         <v2:Code>MYCODE</v2:Code>
         <v2:Value>MYORDERNUM</v2:Value>
      </v2:ReferenceNumber>
   </v2:TrackRequest>
</soapenv:Body>
</soapenv:Envelope>'.

create server hs.
hs:connect( "-WSDL /home/jbetts/track/Track.wsdl -Port TrackPort -TargetNamespace http://www.ups.com/WSDL/XOLTWS/Track/v2.0 -nohostverify -nosessionreuse" ).

run TrackPortType set hp on server hs.
run ProcessTrack in hp ( input cBody, output cBody2 ).

delete procedure hp.
hs:disconnect().
delete object hs.

I think the problem is that I need to send the header in a certain way when I run the ProcessTrack procedure (using SET-CALLBACK-PROCEDURE) but I'm not sure how.

Thanks in advance!

Body:
SET-CALLBACK-PROCEDURE is the way.

You need to do something like this (setRequestSessionHandler is the name of the procedure so it can be whatever you want) before you RUN the SOAP-call:

hp:SET-CALLBACK-PROCEDURE("REQUEST-HEADER", "setRequestSessionHeader").

The request-callback has two input and two output parameters (names taken from the documentation, they can be called anything as long as input/output and datatype is correct):

DEFINE OUTPUT PARAMETER hSOAPHeader         AS HANDLE    NO-UNDO.
DEFINE INPUT  PARAMETER cOperationNamespace AS CHARACTER NO-UNDO.
DEFINE INPUT  PARAMETER cOperationLocalName AS CHARACTER NO-UNDO.
DEFINE OUTPUT PARAMETER plDeleteOnDone AS LOGICAL   NO-UNDO.

hSOAPHeader — A handle to a SOAP header object that encapsulates the header of the SOAP message
  that is about to be sent (request header) or that has just been received (response header). In a response
  header handler, the SOAP header object has no content if the NUM-HEADER-ENTRIES attribute on the
  object handle returns the value 0; otherwise it contains one or more SOAP header entries. In a request
  header handler, this is an OUTPUT parameter, therefore if the outgoing SOAP message requires a SOAP
  header, you must either build a SOAP header for this parameter to reference or provide an existing SOAP
  header saved from a previous response callback.

cOperationNamespace — Contains the namespace portion of the operation's qualified name. Use this
  parameter together with the cOperationLocalName parameter if you need to identify the operation for
  which the SOAP message is being sent or received.

cOperationLocalName — Contains the local-name portion of the operation's qualified name. Use this
  parameter together with the cOperationNamespace parameter if you need to identify the operation for
  which the SOAP message is being sent or received.

lDeleteOnDone — (Request callback only) Tells OpenEdge to delete the SOAP header object and all of
  the parsed XML after the SOAP header has been inserted into the out-bound SOAP message

This is what I do to mimic WS-Security, not exactly what you need and also quite a lot of code. You should be able to "mine it" for whatever you need.

PROCEDURE setRequestSessionHeader :
/*------------------------------------------------------------------------------
  Purpose:
  Parameters:  <none>
  Notes:
------------------------------------------------------------------------------*/

DEFINE OUTPUT PARAMETER phHeader       AS HANDLE    NO-UNDO.
DEFINE INPUT  PARAMETER pcNamespace    AS CHARACTER NO-UNDO.
DEFINE INPUT  PARAMETER pcLocalNS      AS CHARACTER NO-UNDO.
DEFINE OUTPUT PARAMETER plDeleteOnDone AS LOGICAL   NO-UNDO.

DEFINE VARIABLE hSoapHeaderEntryref1    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hSoapHeaderEntryref2    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hSoapHeaderEntryref3    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hSoapHeaderEntryref4    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hSoapHeaderEntryref5    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hXDocument              AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASSecurity            AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASUsernameToken       AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASUserName            AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASPassword            AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASPasswordType        AS HANDLE      NO-UNDO.
DEFINE VARIABLE hOASNonce               AS HANDLE      NO-UNDO.
DEFINE VARIABLE hWSUCreated             AS HANDLE      NO-UNDO.
DEFINE VARIABLE hADDMessageID           AS HANDLE      NO-UNDO.
DEFINE VARIABLE hADDTo                  AS HANDLE      NO-UNDO.
DEFINE VARIABLE hADDAction              AS HANDLE      NO-UNDO.
DEFINE VARIABLE hAMA_SecurityHostedUser AS HANDLE      NO-UNDO.
DEFINE VARIABLE hUserId                 AS HANDLE      NO-UNDO.
DEFINE VARIABLE hTxt                    AS HANDLE      NO-UNDO.
DEFINE VARIABLE hAttr                   AS HANDLE      NO-UNDO.
DEFINE VARIABLE hRootNode               AS HANDLE      NO-UNDO.

/* Namespaces */
DEFINE VARIABLE cNSAddressing           AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cNSSecurity             AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cNSSecurityUtils        AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cNSAmaSec               AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cMessageId              AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cUserName               AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cPasswordClear          AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cPasswordDigest         AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cCreated                AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cAction                 AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cTo                     AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cNonceB64               AS CHARACTER   NO-UNDO.
DEFINE VARIABLE cOfficeId               AS CHARACTER   NO-UNDO.
DEFINE VARIABLE mNonce                  AS MEMPTR      NO-UNDO.

ASSIGN
    cNSAddressing     = "http://www.w3.org/2005/08/addressing"
    cNSSecurity       = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    cNSSecurityUtils  = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    cNSAmaSec         = "http://illkeepthisasecret..."
    cAction           = "http://illkeepthisasecret..."
    cTo               = "https://noded1.production.webservices.amadeus.com/1ASIWIBNAIT".

ASSIGN
    cUserName         = "usernamegoeshere"
    cOfficeId         = "anothersettinggoeshere"
    cPasswordClear    = "passwordgoeshere".

/* Delete header when done! */
ASSIGN
    plDeleteOnDone = TRUE.

CREATE SOAP-HEADER ghSoapHeader.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref1.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref2.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref3.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref4.
CREATE SOAP-HEADER-ENTRYREF hSoapHeaderEntryref5.

CREATE X-DOCUMENT hXDocument.
CREATE X-NODEREF hRootNode.
CREATE X-NODEREF hOASSecurity.
CREATE X-NODEREF hTxt.
CREATE X-NODEREF hOASUsernameToken.
CREATE X-NODEREF hOASPassword.
CREATE X-NODEREF hOASUserName.
CREATE X-NODEREF hOASNonce.
CREATE X-NODEREF hADDMessageID.
CREATE X-NODEREF hADDTo.
CREATE X-NODEREF hADDAction.
CREATE X-NODEREF hWSUCreated.
CREATE X-NODEREF hAMA_SecurityHostedUser.
CREATE X-NODEREF hUserId.

/* Not DATETIME-TZ! */
DEFINE VARIABLE dtZuluNow AS DATETIME    NO-UNDO.

/* Genereate a random key and base64-encode it */
SET-SIZE(mNonce) = 16.

mNonce = GENERATE-RANDOM-KEY.

cNonceB64 = BASE64-ENCODE(mNonce).

/* Get time in UTC/GMT/ZULU/Timezone 0 */
dtZuluNow = DATETIME-TZ(NOW,0).

/* Manipulate the date string to fit specs... */
ASSIGN
    cMessageId = LC(SUBSTRING(STRING(GENERATE-UUID), 8, 20))
    cCreated = STRING(dtZuluNow, "9999-99-99THH:MM:SS") + ":000Z".
/* This is internal stuff for generating a digest... */
RUN generatePasswordDigest( mNonce, cCreated, cPasswordClear, OUTPUT cPasswordDigest).

/* Root node */
hXDocument:CREATE-NODE-NAMESPACE(hRootNode, "", "root", "element").
hXDocument:INSERT-BEFORE(hRootNode, ?).

/**** Addressing ****/
/* MessageID */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref1).
hXDocument:CREATE-NODE-NAMESPACE(hADDMessageID, cNSAddressing, "MessageID", "ELEMENT").
hRootNode:APPEND-CHILD(hAddMessageID).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cMessageId.
hADDMessageId:APPEND-CHILD(hTxt).
hSoapHeaderEntryref1:SET-NODE(hADDMessageID).

/* Action */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref2).
hXDocument:CREATE-NODE-NAMESPACE(hADDAction, cNSAddressing, "Action", "ELEMENT").
hRootNode:APPEND-CHILD(hADDAction).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cAction.
hADDAction:APPEND-CHILD(hTxt).
hSoapHeaderEntryref2:SET-NODE(hADDAction).

/* To */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref3).
hXDocument:CREATE-NODE-NAMESPACE(hADDTo, cNSAddressing, "To", "ELEMENT").
hRootNode:APPEND-CHILD(hADDTo).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cTo.
hADDTo:APPEND-CHILD(hTxt).
hSoapHeaderEntryref3:SET-NODE(hADDTo).

/**** Security ****/
/* Root node */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref4).
hXDocument:CREATE-NODE-NAMESPACE(hOASSecurity, cNSSecurity, "Security", "ELEMENT").
hRootNode:APPEND-CHILD(hOASSecurity).

/* UserNameToken node */
hXDocument:CREATE-NODE-NAMESPACE(hOASUsernameToken, cNSSecurity, "UsernameToken", "ELEMENT").
hOASUsernameToken:SET-ATTRIBUTE("Id", "UsernameToken-1").
hOASSecurity:INSERT-BEFORE(hOASUsernameToken, ?).

/* Username */
hXDocument:CREATE-NODE-NAMESPACE(hOASUserName, cNSSecurity, "Username", "ELEMENT").
hRootNode:APPEND-CHILD(hOASUserName).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cUserName.
hOASUserName:APPEND-CHILD(hTxt).
hOASUsernameToken:APPEND-CHILD(hOASUserName).

/* Nonce */
hXDocument:CREATE-NODE-NAMESPACE(hOASNonce, cNSSecurity, "Nonce", "ELEMENT").
hOASNonce:SET-ATTRIBUTE("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary").
hOASUsernameToken:APPEND-CHILD(hOASNonce).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cNonceB64.
hOASNonce:APPEND-CHILD(hTxt).

/* Password hash */
hXDocument:CREATE-NODE-NAMESPACE(hOASPassword, cNSSecurity, "Password", "ELEMENT").
hOASPassword:SET-ATTRIBUTE("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest").
hOASUsernameToken:APPEND-CHILD(hOASPassword).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cPasswordDigest.
hOASPassword:APPEND-CHILD(hTxt).

/* Created - timestamp */
hXDocument:CREATE-NODE-NAMESPACE(hWSUCreated, cNSSecurityUtils, "Created", "ELEMENT").
hOASUsernameToken:APPEND-CHILD(hWSUCreated).
hXDocument:CREATE-NODE(hTxt, "", "TEXT").
hTxt:NODE-VALUE = cCreated.
hWSUCreated:APPEND-CHILD(hTxt).
hSoapHeaderEntryref4:SET-NODE(hOASSecurity).

/**** AMA_SecurityHostedUser ****/
/* Root node */
ghSoapHeader:ADD-HEADER-ENTRY(hSoapHeaderEntryref5).
hXDocument:CREATE-NODE-NAMESPACE(hAMA_SecurityHostedUser, cNSAMASec, "AMA_SecurityHostedUser", "ELEMENT").
hRootNode:APPEND-CHILD(hAMA_SecurityHostedUser).

/* UserID */
hXDocument:CREATE-NODE-NAMESPACE(hUserID, cNSAMASec, "UserID", "ELEMENT").

hUserID:SET-ATTRIBUTE("AgentDutyCode", "SU").
hUserID:SET-ATTRIBUTE("RequestorType", "U").
hUserID:SET-ATTRIBUTE("PseudoCityCode", cOfficeId).
hUserID:SET-ATTRIBUTE("POS_Type", "1").

hAMA_SecurityHostedUser:APPEND-CHILD(hUserID).
hSoapHeaderEntryref5:SET-NODE(hAMA_SecurityHostedUser).

/* Output the header */
phHeader = ghSoapHeader.

/* Cleanup */
IF VALID-HANDLE(hOASSecurity) THEN
    DELETE OBJECT hOASSecurity.
IF VALID-HANDLE(hOASUsernameToken) THEN
    DELETE OBJECT hOASUsernameToken.
IF VALID-HANDLE(hOASUserName) THEN
    DELETE OBJECT hOASUserName.
IF VALID-HANDLE(hOASPassword) THEN
    DELETE OBJECT hOASPassword.
IF VALID-HANDLE(hADDMessageID) THEN
    DELETE OBJECT hADDMessageID.
IF VALID-HANDLE(hOASNonce) THEN
    DELETE OBJECT hOASNonce.
IF VALID-HANDLE(hTxt) THEN
    DELETE OBJECT hTxt.
IF VALID-HANDLE(hADDTo) THEN
    DELETE OBJECT hADDTo.
IF VALID-HANDLE(hWSUCreated) THEN
    DELETE OBJECT hWSUCreated.
IF VALID-HANDLE(hADDAction) THEN
    DELETE OBJECT hADDAction.
IF VALID-HANDLE(hXDocument) THEN
    DELETE OBJECT hXDocument.
IF VALID-HANDLE(hRootNode) THEN
    DELETE OBJECT hRootNode.
IF VALID-HANDLE(hSoapHeaderEntryRef1) THEN
    DELETE OBJECT hSoapHeaderEntryRef1.
IF VALID-HANDLE(hSoapHeaderEntryRef2) THEN
    DELETE OBJECT hSoapHeaderEntryRef2.
IF VALID-HANDLE(hSoapHeaderEntryRef3) THEN
    DELETE OBJECT hSoapHeaderEntryRef3.
IF VALID-HANDLE(hSoapHeaderEntryRef4) THEN
    DELETE OBJECT hSoapHeaderEntryRef4.
IF VALID-HANDLE(hSoapHeaderEntryRef5) THEN
    DELETE OBJECT hSoapHeaderEntryRef5.
IF VALID-HANDLE(hAMA_SecurityHostedUser) THEN
    DELETE OBJECT hAMA_SecurityHostedUser.
IF VALID-HANDLE(hUserId) THEN
    DELETE OBJECT hUserId.

END.


来源: stackexchange

问:
In MongoDB search in an array and sort by number of matches
The question is the next one:

Get documents with tags in list, ordered by total number of matches

But they say that is possible using Aggregation Framework, it's possible?

答:
Using $size and $setIntersection will solve this efficiently, without causing memory multiplication.

```<code>tagList = ['shirt', 'cotton', 'black']

db.test_col.aggregate(
    {$match: {tags: {$in: ["shirt","cotton","black"]}}},
    {$project:
        {"title":1,"tags":1},
        {$order:
            {"$size":
                {"$setIntersection": [ tagList, "$tags" ]}},
    {$sort:{order:-1}}
    );
</code>```

First we match the documents which have at least one element matching.

Then we project Keys/Columns we need along with a new order key/column. Order is generated by taking the count of intersected elements between 'tags in db' and 'tags from query'.

Then we do a simple sort in descending order.
This worked for me.
Similar Question answered here

ContentLicense: CC BY-SA 3.0

Body:
Using $size and $setIntersection will solve this efficiently, without causing memory multiplication.

tagList = ['shirt', 'cotton', 'black']

db.test_col.aggregate(
    {$match: {tags: {$in: ["shirt","cotton","black"]}}},
    {$project:
        {"title":1,"tags":1},
        {$order:
            {"$size":
                {"$setIntersection": [ tagList, "$tags" ]}},
    {$sort:{order:-1}}
    );

First we match the documents which have at least one element matching.

Then we project Keys/Columns we need along with a new order key/column. Order is generated by taking the count of intersected elements between 'tags in db' and 'tags from query'.

Then we do a simple sort in descending order.
This worked for me.
Similar Question answered here

ContentLicense: CC BY-SA 4.0


问:
Conditional Union in T-SQL
Currently I've a query as follows:

```<code>-- Query 1
SELECT
    acc_code, acc_name, alias, LAmt, coalesce(LAmt,0) AS amt
FROM
    (SELECT
        acc_code, acc_name, alias,
        (SELECT
            (SUM(cr_amt)-SUM(dr_amt))
        FROM
            ledger_mcg l
        WHERE
            (l.acc_code LIKE a.acc_code + '.%' OR l.acc_code=a.acc_code)
        AND
            fy_id=1
        AND
            posted_date BETWEEN '2010-01-01' AND '2011-06-02') AS LAmt
    FROM
        acc_head_mcg AS a
    WHERE
    (acc_type='4')) AS T1
WHERE
    coalesce(LAmt,0)<>0
</code>```

Query 2 is same as Query 1 except that acc_type = '5'  in Query 2.  Query 2 always returns a resultset with a single row. Now, I need the union of the two queries i.e

```<code>Query 1
UNION
Query 2
</code>```

only when the amt returned by Query 2 is less than 0. Else, I don't need a union but only the resulset from Query 1.

The best way I can think of is to create a parameterised scalar function. How best can I do this?

答:
You could store the result of the first query into a temporary table, then, if the table wasn't empty, execute the other query.</p>

```<code>IF OBJECT_ID('tempdb..#MultipleQueriesResults') IS NOT NULL
  DROP TABLE #MultipleQueriesResults;

SELECT
    acc_code, acc_name, alias, LAmt, coalesce(LAmt,0) AS amt
INTO #MultipleQueriesResults
FROM
    (SELECT
        acc_code, acc_name, alias,
        (SELECT
            (SUM(cr_amt)-SUM(dr_amt))
        FROM
            ledger_mcg l
        WHERE
            (l.acc_code LIKE a.acc_code + '.%' OR l.acc_code=a.acc_code)
        AND
            fy_id=1
        AND
            posted_date BETWEEN '2010-01-01' AND '2011-06-02') AS LAmt
    FROM
        acc_head_mcg AS a
    WHERE
    (acc_type='4')) AS T1
WHERE
    coalesce(LAmt,0)<>0;

IF NOT EXISTS (SELECT * FROM #MultipleQueriesResults)
  … /* run Query 2 */
</code>```

Title: Conditional Union in T-SQL

Body:
Currently I've a query as follows:

-- Query 1
SELECT
    acc_code, acc_name, alias, LAmt, coalesce(LAmt,0) AS amt
FROM
    (SELECT
        acc_code, acc_name, alias,
        (SELECT
            (SUM(cr_amt)-SUM(dr_amt))
        FROM
            ledger_mcg l
        WHERE
            (l.acc_code LIKE a.acc_code + '.%' OR l.acc_code=a.acc_code)
        AND
            fy_id=1
        AND
            posted_date BETWEEN '2010-01-01' AND '2011-06-02') AS LAmt
    FROM
        acc_head_mcg AS a
    WHERE
    (acc_type='4')) AS T1
WHERE
    coalesce(LAmt,0)<>0

Query 2 is same as Query 1 except that acc_type = '5'  in Query 2.  Query 2 always returns a resultset with a single row. Now, I need the union of the two queries i.e

Query 1
UNION
Query 2

only when the amt returned by Query 2 is less than 0. Else, I don't need a union but only the resulset from Query 1.

The best way I can think of is to create a parameterised scalar function. How best can I do this?

Body:
You could store the result of the first query into a temporary table, then, if the table wasn't empty, execute the other query.

IF OBJECT_ID('tempdb..#MultipleQueriesResults') IS NOT NULL
  DROP TABLE #MultipleQueriesResults;

SELECT
    acc_code, acc_name, alias, LAmt, coalesce(LAmt,0) AS amt
INTO #MultipleQueriesResults
FROM
    (SELECT
        acc_code, acc_name, alias,
        (SELECT
            (SUM(cr_amt)-SUM(dr_amt))
        FROM
            ledger_mcg l
        WHERE
            (l.acc_code LIKE a.acc_code + '.%' OR l.acc_code=a.acc_code)
        AND
            fy_id=1
        AND
            posted_date BETWEEN '2010-01-01' AND '2011-06-02') AS LAmt
    FROM
        acc_head_mcg AS a
    WHERE
    (acc_type='4')) AS T1
WHERE
    coalesce(LAmt,0)<>0;

IF NOT EXISTS (SELECT * FROM #MultipleQueriesResults)
  … /* run Query 2 */


答:
You can create an auxiliary column of x$YEAR + x$MONTH/12 which helps bringing December for last year to current year. And then simply use aggregate of PPT over CENTROID_ID, floor(aux) and floor(aux %% 1 * 4). Then reshape to bring the seasons in the same row.

```<code>x$aux <- x$YEAR + x$MONTH/12
y <- aggregate(PPT ~ CENTROID_ID + cbind(YEAR=floor(aux)) + cbind(SEASON=c("WINT",
 "SPR", "SUM", "FALL")[1+floor(aux %% 1 * 4)]), x, mean)
reshape(do.call(data.frame, y), v.names = "PPT", timevar = "SEASON", idvar =
 c("CENTROID_ID", "YEAR"), direction = "wide")
#   CENTROID_ID YEAR PPT.FALL  PPT.SPR  PPT.SUM PPT.WINT
#1      c1763_1 1910 39.97033 10.75133 38.13233 36.75450
#2      c1763_1 1911 45.08467 17.09667 44.60067 56.32500
#3      c1763_1 1912 47.02533 34.40600 35.85467 15.59233
#4      c1763_1 1913 43.11800  8.98800 29.09867 33.05667
#17     c1763_1 1914       NA       NA       NA 55.98433
</code>```

Title: How to find the average, max, and min based on multiple sets of criteria

Body:
I have found a few options from other posts but I am having trouble reproducing the code for my specific needs.

I have climate data that I would like to find the average based on season from 1910-2015 for specific locations.

Here is an example of what I need: the average PPT for CENTROID_ID c1763_1 in 1911 for Winter (Month 12 of the preceding year [1910], month 1 and 2 of year in question [1911]), Spring (months 3,4,5 in 1911), Summer (months 6,7,8 in 1911) and Fall (months 9,10,11 in 1911). This would then need to be done for all individual centroid IDs for every year. I have over 400 unique CENTROID_IDs covering years 1910-2015.

I envision the new dataframe to have the columns CENTROID_ID, YEAR, WINT_PPT, SPR_PPT, SUM_PPT, FALL_PPT.

 CENTROID_ID    YEAR MONTH  PPT
1       c1763_1 1910     1  52.639
2       c1763_1 1910     2  20.870
3       c1763_1 1910     3  21.706
4       c1763_1 1910     4   9.347
5       c1763_1 1910     5   1.201
6       c1763_1 1910     6  11.267
7       c1763_1 1910     7  41.870
8       c1763_1 1910     8  61.260
9       c1763_1 1910     9  27.815
10      c1763_1 1910    10  67.377
11      c1763_1 1910    11  24.719
12      c1763_1 1910    12  30.212
13      c1763_1 1911     1  88.728
14      c1763_1 1911     2  50.035
15      c1763_1 1911     3  37.720
16      c1763_1 1911     4  12.831
17      c1763_1 1911     5   0.739
18      c1763_1 1911     6  18.198
19      c1763_1 1911     7  74.731
20      c1763_1 1911     8  40.873
21      c1763_1 1911     9  86.340
22      c1763_1 1911    10  36.423
23      c1763_1 1911    11  12.491
24      c1763_1 1911    12  19.428
25      c1763_1 1912     1  11.010
26      c1763_1 1912     2  16.339
27      c1763_1 1912     3  72.017
28      c1763_1 1912     4  25.887
29      c1763_1 1912     5   5.314
30      c1763_1 1912     6   8.595
31      c1763_1 1912     7  47.781
32      c1763_1 1912     8  51.188
33      c1763_1 1912     9  10.931
34      c1763_1 1912    10 119.725
35      c1763_1 1912    11  10.420
36      c1763_1 1912    12   8.777
37      c1763_1 1913     1  27.771
38      c1763_1 1913     2  62.622
39      c1763_1 1913     3  17.533
40      c1763_1 1913     4   8.008
41      c1763_1 1913     5   1.423
42      c1763_1 1913     6   3.773
43      c1763_1 1913     7  42.982
44      c1763_1 1913     8  40.541
45      c1763_1 1913     9  58.495
46      c1763_1 1913    10  22.729
47      c1763_1 1913    11  48.130
48      c1763_1 1913    12  32.049
49      c1763_1 1914     1 104.197
50      c1763_1 1914     2  31.707

Body:
You can create an auxiliary column of x$YEAR + x$MONTH/12 which helps bringing December for last year to current year. And then simply use aggregate of PPT over CENTROID_ID, floor(aux) and floor(aux %% 1 * 4). Then reshape to bring the seasons in the same row.

x$aux <- x$YEAR + x$MONTH/12
y <- aggregate(PPT ~ CENTROID_ID + cbind(YEAR=floor(aux)) + cbind(SEASON=c("WINT",
 "SPR", "SUM", "FALL")[1+floor(aux %% 1 * 4)]), x, mean)
reshape(do.call(data.frame, y), v.names = "PPT", timevar = "SEASON", idvar =
 c("CENTROID_ID", "YEAR"), direction = "wide")
#   CENTROID_ID YEAR PPT.FALL  PPT.SPR  PPT.SUM PPT.WINT
#1      c1763_1 1910 39.97033 10.75133 38.13233 36.75450
#2      c1763_1 1911 45.08467 17.09667 44.60067 56.32500
#3      c1763_1 1912 47.02533 34.40600 35.85467 15.59233
#4      c1763_1 1913 43.11800  8.98800 29.09867 33.05667
#17     c1763_1 1914       NA       NA       NA 55.98433


问:
Using Admin site layout and front site layout angular 8
I am working on application which includes front site layout and admin site layout both of them have different JS and CSS files. I want to keep them a part not to conflict with each other. Here is my index.html page code

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Couaff</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

 <!--[if lt IE 9]>
        <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <!--[if lte IE 8]>
        <script type="text/javascript" src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script>
    <![endif]-->

    <!-- **Favicon** -->
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

    <!-- **CSS - stylesheets** -->
    <link id="default-css" href="assets/style.css" rel="stylesheet" media="all">
    <link href="assets/css/shortcode.css" rel="stylesheet" type="text/css">

    <!-- **Additional - stylesheets** -->
    <link rel="stylesheet" href="assets/css/responsive.css" type="text/css" media="all">
    <link href="assets/css/animations.css" rel="stylesheet" media="all">
    <link id="skin-css" href="assets/skins/red/style.css" rel="stylesheet" media="all">
    <link rel="stylesheet" href="assets/css/meanmenu.css" type="text/css" media="all">
    <link rel="stylesheet" type="text/css" href="assets/css/pace-theme-loading-bar.css">

    <!-- **Font Awesome** -->
    <link rel="stylesheet" href="assets/css/font-awesome.min.css">

    <!-- **Google - Fonts** -->
    <link href='http://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto:400,500,300,700,900' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=PT+Serif:400,700' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

    <!--[if IE 7]>
    <link rel="stylesheet" href="css/font-awesome-ie7.min.css" />
    <![endif]-->

    <!-- jQuery -->
    <script src="assets/js/modernizr.custom.js"></script>

</head>
<body>
  <app-root></app-root>

  <!-- **jQuery** -->
<script src="assets/js/jquery-1.11.3.min.js"></script>
<script src="assets/js/jquery.parallax-1.1.3.js" type="text/javascript"></script>
<script type="text/javascript" src="assets/js/jquery.sticky.min.js"></script>
<script src="assets/js/jquery.inview.js" type="text/javascript"></script>
<script src="assets/js/jsplugins.js" type="text/javascript"></script>
<script src="assets/js/jquery.meanmenu.min.js" type="text/javascript"></script>
<script src="assets/js/custom.js"></script>

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

Currently I have kept only front site layout JS and CSS files. Here is the architecture and site layout component. For reference see below image.

Angular-Web

答:
From my understanding you want to have 2 code bases for 2 different entries in a single Angular project. If so you can do these steps

1. Create a new project for your admin entry

```<code>ng g application admin --routing=true
</code>```

Change admin to any name you wanted.

By doing this a new directory projects/admin will be created under your base directory (couaff-angular-web)

2. Configure outputPath

Assuming you want to have your admin entry under https://{host}/admin/ then you will need to either configure your host to target to dist/admin directory

Or you can open angular.json.Then locate projects.admin.architect.build.options.outputPath and change it to whatever path you prefered

```<code>"outputPath": "../admin",
</code>```

Where admin is the name of of the path of your choice (pick anything you like)

3. Configure your base path in index.html

(NOTE: this is depends on your host configuration like if you have dedicated host configured for admin page then this step is not required)

Open index.html for admin project, locate <base> tag. You will need to update it to something like this

```<code><!-- NOTE the original value is "/" - which will cause admin project to fetch assets in your base project -->
<base href="/admin/">
</code>```

4. Run your application like you normally do

```<code>ng serve|build
# or
ng serve|build --project=admin
</code>```

Depend on what you wanted you can either

Run ng serve|build without any param. Your default (base) project will be runing

Run ng serve|build with --project=admin param. Your child project will be running

Reference: ng-cli doc

EDIT: I make a mistake in step 4. Added param --project=admin for the command lines - and fixed the answer

Body:
I am working on application which includes front site layout and admin site layout both of them have different JS and CSS files. I want to keep them a part not to conflict with each other. Here is my index.html page code

<!doctype html>

  <meta charset="utf-8">
  <title>Couaff</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

    <link id="default-css" href="assets/style.css" rel="stylesheet" media="all">
    <link href="assets/css/shortcode.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" href="assets/css/responsive.css" type="text/css" media="all">
    <link href="assets/css/animations.css" rel="stylesheet" media="all">
    <link id="skin-css" href="assets/skins/red/style.css" rel="stylesheet" media="all">
    <link rel="stylesheet" href="assets/css/meanmenu.css" type="text/css" media="all">
    <link rel="stylesheet" type="text/css" href="assets/css/pace-theme-loading-bar.css">

    <link rel="stylesheet" href="assets/css/font-awesome.min.css">

    <link href='http://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto:400,500,300,700,900' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=PT+Serif:400,700' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

  <app-root></app-root>

Currently I have kept only front site layout JS and CSS files. Here is the architecture and site layout component. For reference see below image.

Angular-Web

Body:
From my understanding you want to have 2 code bases for 2 different entries in a single Angular project. If so you can do these steps

1. Create a new project for your admin entry

ng g application admin --routing=true

Change admin to any name you wanted.

By doing this a new directory projects/admin will be created under your base directory (couaff-angular-web)

2. Configure outputPath

Assuming you want to have your admin entry under https://{host}/admin/ then you will need to either configure your host to target to dist/admin directory

Or you can open angular.json.Then locate projects.admin.architect.build.options.outputPath and change it to whatever path you prefered

"outputPath": "../admin",

Where admin is the name of of the path of your choice (pick anything you like)

3. Configure your base path in index.html

(NOTE: this is depends on your host configuration like if you have dedicated host configured for admin page then this step is not required)

Open index.html for admin project, locate <base> tag. You will need to update it to something like this

<!-- NOTE the original value is "/" - which will cause admin project to fetch assets in your base project -->
<base href="/admin/">

4. Run your application like you normally do

ng serve|build
# or
ng serve|build --project=admin

Depend on what you wanted you can either

Run ng serve|build without any param. Your default (base) project will be runing

Run ng serve|build with --project=admin param. Your child project will be running

Reference: ng-cli doc

EDIT: I make a mistake in step 4. Added param --project=admin for the command lines - and fixed the answer


问:
two ternary condition inside JSX block?
I have 2 useState, one for show activity indicator, another state is to check whether it has data or not.

```<code>  const [isLoading, setIsLoading] = useState(false);
  const [isData, setIsData] = useState(false);
</code>```

what i want to do is,
if i have data then, it should show the activity indicator for the loading time, then it should show the data in the screen. If i don't have the data, it should display simply "No Data Found."

This is my current code, it's only checking activity indicator.

```<code>{isLoading ? (<ActivityIndicator size="large" /> ) : ( <Component data = {data} /> )
</code>```

How can i check the other isData check here?

答:
If you don't want to do multiple ternaries (which is generally not recommended), you could do something like:

```<code>{(isData && (isLoading ? (<ActivityIndicator size="large" /> ) : (<Component data = {data} />))) || <NoDataFound />}
</code>```

This way when data is present, you are looking at the isLoading state indicator.
When data is not fulfilled, you are defaulting to the <NoDataFound />.

If you simplify this code, you are effectively looking at ((a && b) || c). So if a is true, then the code goes on to b, which in your case is just a ternary, so it's again a condition. If a is not true, then there is the "or" operator, which just executes c.

So if we write this code with if, it would look like as follows:

```<code>if (a) {
  b
} else {
  c
}
</code>```

Again, in your case b is a ternary, but as you can see it doesn't really matter as far as the if is concerned.

This pattern is useful when you're getting rid of nesting ternaries, just makes the code easier to follow.

Hope this helps.

Title: two ternary condition inside JSX block?

Body:
I have 2 useState, one for show activity indicator, another state is to check whether it has data or not.

  const [isLoading, setIsLoading] = useState(false);
  const [isData, setIsData] = useState(false);

what i want to do is,
if i have data then, it should show the activity indicator for the loading time, then it should show the data in the screen. If i don't have the data, it should display simply "No Data Found."

This is my current code, it's only checking activity indicator.

{isLoading ? (<ActivityIndicator size="large" /> ) : ( <Component data = {data} /> )

How can i check the other isData check here?

Body:
If you don't want to do multiple ternaries (which is generally not recommended), you could do something like:

{(isData && (isLoading ? (<ActivityIndicator size="large" /> ) : (<Component data = {data} />))) || <NoDataFound />}

This way when data is present, you are looking at the isLoading state indicator.
When data is not fulfilled, you are defaulting to the <NoDataFound />.

If you simplify this code, you are effectively looking at ((a && b) || c). So if a is true, then the code goes on to b, which in your case is just a ternary, so it's again a condition. If a is not true, then there is the "or" operator, which just executes c.

So if we write this code with if, it would look like as follows:

if (a) {
  b
} else {
  c
}

Again, in your case b is a ternary, but as you can see it doesn't really matter as far as the if is concerned.

This pattern is useful when you're getting rid of nesting ternaries, just makes the code easier to follow.

Hope this helps.


问:
Php writes XML file with no values
I have a script that reads values from a mysql database. With the values received i want to make a XML file.

The file is written but with no values.
I can't figure it out. Here is the complete source code:
http://www.segasiauto.ro/tmp/writexml.txt

Can someone help?

Thanks,
Sebastian

EDIT

Solved. There was a problem with the array. I added the data directly to createNodeText

答:
Look carefully what you're doing:

```<code>  $product[] = array(
  'id' => $id,
  'name' => $tip,
  'category' => $tip_produs,
  'model' => $tip_imp,
  'keywords' => $keywords,
  'price' => $pret,
  'available' => "1",
  'canBeOrderedOnline' => "0",
  'details' => $details,
  'pictures' => "picture",
  'currency' => $valuta,
  );
</code>```

and then

```<code>$doc->createTextNode( $product['id'] ));
</code>```

will never get you want you want.
Of course it is empty. There is nothing in there.

Title: Php writes XML file with no values

Body:
Look carefully what you're doing:

  $product[] = array(
  'id' => $id,
  'name' => $tip,
  'category' => $tip_produs,
  'model' => $tip_imp,
  'keywords' => $keywords,
  'price' => $pret,
  'available' => "1",
  'canBeOrderedOnline' => "0",
  'details' => $details,
  'pictures' => "picture",
  'currency' => $valuta,
  );

and then

$doc->createTextNode( $product['id'] ));

will never get you want you want.
Of course it is empty. There is nothing in there.


答:
You can use window function sum with partitioning:

```<code>select acc_num, user_id, date, is_valid,
       sum(case when is_valid then 1 end) over(partition by acc_num, user_id, date)
from FunkyUsers
</code>```

Title: SQL Windowing Aggregation and Counts

Body:
I am using Redshift/Postgres DB. Consider the following table:

    +---------------------------------------+
    |              FunkyUsers               |
    +-------+---------+----------+----------+
    |acc_num| user_id |   date   | is_valid |
    +-------+---------+----------+----------+
    |   a1  |    u1   | 20200201 |    true  |
    |   a1  |    u1   | 20200201 |    true  |
    |   a1  |    u1   | 20200311 |    true  |
    |   a1  |    u2   | 20200201 |   false  |
    |   a1  |    u2   | 20200201 |   false  |
    |   a1  |    u2   | 20200201 |   false  |
    |   a1  |    u3   | 20111201 |    true  |
    |   a1  |    u3   | 20111201 |    true  |
    |   a1  |    u3   | 20111201 |    true  |
    +-------+---------+----------+----------+

I like to have the following output:

    +--------------------------------------------------+
    |                  FunkyUsers                      |
    +-------+---------+----------+----------+----------+
    |acc_num| user_id |   date   | is_valid |  count   |
    +-------+---------+----------+----------+----------+
    |   a1  |    u1   | 20200201 |    true  |    2     |
    |   a1  |    u1   | 20200201 |    true  |    2     |
    +-------+---------+----------+----------+----------+
    |   a1  |    u1   | 20200311 |    true  |    2     |
    +-------+---------+----------+----------+----------+
    |   a1  |    u2   | 20200201 |   false  |    0     |
    |   a1  |    u2   | 20200201 |   false  |    0     |
    |   a1  |    u2   | 20200201 |   false  |    0     |
    +-------+---------+----------+----------+----------+
    |   a1  |    u2   | 20111201 |    true  |    1     |
    |   a1  |    u2   | 20111201 |    true  |    1     |
    |   a1  |    u2   | 20111201 |    true  |    1     |
    +-------+---------+----------+----------+----------+

Description:

Please note the partition acc_num, user_id

Please note the subpartition within the above partition which is the date

When is_valid is true for a (partition, subpartition) increment the count for that (partition)

Finally the is_valid will have the same value for each row within the same (partition, subpartition)

Body:
You can use window function sum with partitioning:

select acc_num, user_id, date, is_valid,
       sum(case when is_valid then 1 end) over(partition by acc_num, user_id, date)
from FunkyUsers


问:
Can you explain this JavaScript function for me?
```<code> function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
</code>```

Could you guys please explain to me how this function works and when the variable "countArray" would push the elements to the array.

答:
It is a recursive function that puts all numbers from 1 to n into an array. Lets look at the example with n = 5:

you enter the function and check if n is smaller than 1, as this is not the case, you jump into the else statement, where the array countArray is initialized with the value of countup(n - 1), therefore you start from the beginning of the function, but with n = 4.

This happens multiple times, until n is 0, as in that case, the first if statement is true. By this exit condition, the function returns an empty array, which is assigned to the variable countArray in the function call in the previous 'layer' of recursion. After that, the variable n which equals 1 on that 'layer' is pushed into the array. These last steps also happen multiple times, as countArray is returned to the next call of the recursive function, in the same way as the empty array was returned.

After all recursive function calls were executed the resulting array [1,2,3,4,5] is returned

Body:
 function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]

Could you guys please explain to me how this function works and when the variable "countArray" would push the elements to the array.


问:
Finding a way to append query params to link opening in flutter InAppWebView
What I want is that whenever a link is opened in webview, it should be appended with client param.
eg www.google.com?client=android or www.google.com?client=iphone
Things I have tried:
1. cancel al request in shouldOverrideUrlLoading and request a new loadUrl on InAppWebViewController (App crashes on ios as soon as webview loads in this approach)</p>

答:
I have updated my plugin flutter_inappwebview! The latest release is 3.3.0+3 at the time of this writing.

You can achieve what you are asking through the shouldOverrideUrlLoading event (set the useShouldOverrideUrlLoading: true option) in this way:

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                  child: InAppWebView(
                    initialUrl: "https://github.com/flutter?client=" + (Platform.isAndroid ? 'android': 'ios'),
                    initialHeaders: {},
                    initialOptions: InAppWebViewGroupOptions(
                      crossPlatform: InAppWebViewOptions(
                        debuggingEnabled: true,
                        useShouldOverrideUrlLoading: true
                      ),
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) {
                      print(url);
                    },
                    shouldOverrideUrlLoading: (InAppWebViewController controller, ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) async {
                      if (Platform.isAndroid || shouldOverrideUrlLoadingRequest.iosWKNavigationType == IOSWKNavigationType.LINK_ACTIVATED) {
                        var url = Uri.parse(shouldOverrideUrlLoadingRequest.url);
                        var queryParams = ((url.hasQuery) ? '&' : '?') + "client=" + (Platform.isAndroid ? 'android': 'ios');
                        var newUrl = shouldOverrideUrlLoadingRequest.url + queryParams;
                        await controller.loadUrl(url: newUrl);
                        return ShouldOverrideUrlLoadingAction.CANCEL;
                      }
                      return ShouldOverrideUrlLoadingAction.ALLOW;
                    },
                  ))
            ])),
      ),
    );
  }
}
```


答:
If you use function you can do like that</p>

```<code>const function nameComponent() {
  const [isLoading, setIsLoading] = useState(false);
  const [isData, setIsData] = useState(false);

  useEffect(() => {
  // Load data here
  }, [])

  if(isLoading) {
     return (<ActivityIndicator size="large" />)
  }
  if (isData) {
     return (<Component data = {data} />)
  }
  // Return view if don't have data
  return <View />
}
</code>```

Title: two ternary condition inside JSX block?

Body:
If you use function you can do like that

const function nameComponent() {
  const [isLoading, setIsLoading] = useState(false);
  const [isData, setIsData] = useState(false);

  useEffect(() => {
  // Load data here
  }, [])

  if(isLoading) {
     return (<ActivityIndicator size="large" />)
  }
  if (isData) {
     return (<Component data = {data} />)
  }
  // Return view if don't have data
  return <View />
}


问:
How to write a custom-attribute (directive) in React 16.9?
Is it possible to use React just for writing a custom-attribute for existing HTML tags?

for example, I want to add float-label to an input HTML tag like the following code:

  <input type="text" id="lname" name="lname" float-label="LastName">

```

and call float-labels.js behind the scene. I want to just extend the regular HTML input tag no more.

Is it possible to use React to extend current HTML tags without writing a new component/tag (like float-input)?

答:
You can write aria-label which will increase your code accessibility</p>

```<code><input type="text" id="lname" name="lname" aria-label="LastName">

</code>```

Body:
Is it possible to use React just for writing a custom-attribute for existing HTML tags?

for example, I want to add float-label to an input HTML tag like the following code:

  <input type="text" id="lname" name="lname" float-label="LastName">

and call float-labels.js behind the scene. I want to just extend the regular HTML input tag no more.

Is it possible to use React to extend current HTML tags without writing a new component/tag (like float-input)?

Body:
You can write aria-label which will increase your code accessibility

<input type="text" id="lname" name="lname" aria-label="LastName">


问:
Issue with moving rigidbody using mouse in Unity
I have a rigidbody that I want to move with a mouse using Input.GetAxisRaw.

I know that Input.GetAxis is framerate independent but in my case it starts to move a lot faster at lower framerates. I have a suspicion that it is so because of the Rigidbody.MovePosition because it doesn't occur when I set the position directly. Dividing the mouse input by Time.DeltaTime does fix it but I'm not sure whether that's a good solution. Also I'm not sure whether that's related the input starts to get really jerky when the framerate is very high (~1000) and input sensitivity can get drastically different on different pc's.

My game is 2d with top down view.

Here's my code:

private void Update()
{
    mouse_movement = GetMouseMovement();
}

private void FixedUpdate()
{
    Vector3 new_position = transform.position + mouse_movement;
    rigidbody.MovePosition(new_position);
}

public Vector3 GetMouseMovement()
{
    Vector3 mouse_movement = new Vector3(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
    return mouse_movement * MouseSensitivity;
}
```

Thanks in advance.

答:
If you struggling from too high FPS, you can set target framerate

you get your input in update, and apply it in fixed update. It means, mouse position sampled once per frame, but then applied several times between frames - on FixedUpdate. So you ARE framerate dependant. To be really framerate independant, do input check in FixedUpdate too. Or move your object in Update, multiplying value by Time.deltaTime. Just do not mix Update and FixedUpdate.

You get mouse position on screen. It means, you are also resolution-dependant. There are two ways to fix: convert mouse position into world space, or calculate mouse movement as a percentage from screen size:

movementX = Input.GetAxisRaw("Mouse X") / Screent.width;

Body:
I have a rigidbody that I want to move with a mouse using Input.GetAxisRaw.

I know that Input.GetAxis is framerate independent but in my case it starts to move a lot faster at lower framerates. I have a suspicion that it is so because of the Rigidbody.MovePosition because it doesn't occur when I set the position directly. Dividing the mouse input by Time.DeltaTime does fix it but I'm not sure whether that's a good solution. Also I'm not sure whether that's related the input starts to get really jerky when the framerate is very high (~1000) and input sensitivity can get drastically different on different pc's.

My game is 2d with top down view.

Here's my code:

private void Update()
{
    mouse_movement = GetMouseMovement();
}

private void FixedUpdate()
{
    Vector3 new_position = transform.position + mouse_movement;
    rigidbody.MovePosition(new_position);
}

public Vector3 GetMouseMovement()
{
    Vector3 mouse_movement = new Vector3(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
    return mouse_movement * MouseSensitivity;
}

Thanks in advance.


问:
C# how to log file inside a DLL?
I'm developing a DLL and I want to log some data it generates.

I wanted to use "Log4Net", but I found the problem that in a DLL I don't have an "App.config" file where I can write the XML code, so I don't know how to implement this (I'm new in this matters).

I read about "Singleton" but I saw it's better to avoid it since it has it's issues (i.e hide some visibility of the code, problems with unit tests, ...).

So my question is: How and what is the best way to create a log file for the data generated by my DLL?

答:
To log the application flow in the DLL,
Just create a Class that create and access the log text file.

In that class, declare the object LoggingClass loggingObject; and then use this instance to access the log file.

In creating object for it, you can use,

```<code>public static LoggingClass createOrGetObject()
{
  return (loggingObject == null)? new LoggingClass() : loggingObject;
}
</code>```

Now, just you can call this method to get the same instance that access the log file to write the log.
In this example, Log4Net is not used but works fine for logging.

Title: C# how to log file inside a DLL?

Body:
To log the application flow in the DLL,
Just create a Class that create and access the log text file.

In that class, declare the object LoggingClass loggingObject; and then use this instance to access the log file.

In creating object for it, you can use,

public static LoggingClass createOrGetObject()
{
  return (loggingObject == null)? new LoggingClass() : loggingObject;
}

Now, just you can call this method to get the same instance that access the log file to write the log.
In this example, Log4Net is not used but works fine for logging.


问:
How to split names with numbers from one common file into separate files by numbers (Names with identical numbers in one file and others in another)
```<code>student = ['Ted 904', 'John 904', 'Dan 905', 'Peter 905', 'Michael 906']
with open('a.txt', "w") as myfile:
        for c in student:
                myfile.write("%s\n" % c)
</code>```

I have a list of students with their numbers and I have written it in file and now I need to separate them on different txt files by their similar number.

答:
Filenames can be created by the numbers of the students and you can do this</p>

```<code>student = ['Ted 904', 'John 904', 'Dan 905', 'Peter 905', 'Michael 906']
for c in student:
    fileName= c[-3:]
    with open(fileName+'.txt', "a") as myfile:
        myfile.write("%s\n" % c)
</code>```

Body:
student = ['Ted 904', 'John 904', 'Dan 905', 'Peter 905', 'Michael 906']
with open('a.txt', "w") as myfile:
        for c in student:
                myfile.write("%s\n" % c)

I have a list of students with their numbers and I have written it in file and now I need to separate them on different txt files by their similar number.

Body:
Filenames can be created by the numbers of the students and you can do this

student = ['Ted 904', 'John 904', 'Dan 905', 'Peter 905', 'Michael 906']
for c in student:
    fileName= c[-3:]
    with open(fileName+'.txt', "a") as myfile:
        myfile.write("%s\n" % c)


问:
light up the mass storage's led
I have usb mass stroage with led

I am trying to light on and off the led

using usb packet sniffing tool USBlyzer,

I can get the raw data

55 53 42 43 58 66 93 88 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

whose Request info is Bulk or Interrupt Transfer and I/O is out

and in the USB properties section

I can get the info such as

Endpoint Descriptor 81 1 In, bulk, 512 bytes

```<code>bDescriptorType 05h Endpoint

bEndpointAddress 81h 1 In
</code>```

Endpoint Descriptor 02 2 In, bulk, 512 bytes

```<code>bDescriptorType 05h Endpoint

bEndpointAddress 02h 2 Out
</code>```

I made a python code with python 2.7, libusb-win32-bin-1.2.4.0, pyusb-1.0.0-a1

the full source is here

```<code>import usb.core
import usb.util

# find our device
dev = usb.core.find(idVendor=0x1516, idProduct=0x8628)

# was it found?
if dev is None:
    raise ValueError('Device not found')

dev.set_configuration()
# get an endpoint instance
cfg = dev.get_active_configuration()
interface_number = cfg[0].bInterfaceNumber
alternate_setting = usb.control.get_interface(interface_number)
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = \
                                ineterface_number, bAlternateSetting = alternate_setting)
ep = usb.util.find_descriptor(intf,custom_match = \
                                  lambda e: \
                                      usb.util.endpoint_direction(e.bEndpointAddress) == \
                                      usb.util.ENDPOINT_OUT)
# set the active configuration. With no arguments, the first
# configuration will be the active one

assert ep is not None

ep.write(0x2,0x55)
ep.write(0x2,0x53)
ep.write(0x2,0x42)
ep.write(0x2,0x43)
ep.write(0x2,0x58)
ep.write(0x2,0x66)
ep.write(0x2,0x93)
ep.write(0x2,0x88)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x06)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
</code>```

but when I try to execute it,

```<code>Traceback (most recent call last):
  File "C:\Documents and Settings\kty1104\Desktop\usb2.py", line 14, in <module>
    interface_number = cfg[0].bInterfaceNumber
  File "C:\Python27\lib\site-packages\usb\core.py", line 447, in __getitem__
    return Interface(self.device, index[0], index[1], self.index)
TypeError: 'int' object is not subscriptable
</code>```

arise

what's wrong with my code?

any if anything wrong concept is there, please let me know

thanks!

答:
I don't know anything about pyusb, but my interpretation of the error message is that, contra others' opinions, cfg is not an integer, but that it requires a non-integral index. I say this because the exception is thrown in a __getitem__ function, which could only be cfg's __getitem__, because that's the only place a __getitem__ call would be made in the line

```<code>interface_number = cfg[0].bInterfaceNumber
</code>```

Now if cfg were an int, it wouldn't have a __getitem__. The problem is that cfg's __getitem__ seems to expect to be able to subscript the index that it receives, as illustrated by the middle two arguments, index[0], index[1]. Since you passed cfg an integer, that's impossible.

From the tutorial:

You can also use the subscript
  operator to access the descriptors
  randomly, like that:

```<code>>>> # access the second configuration
>>> cfg = dev[1]
>>> # access the first interface
>>> intf = cfg[(0,0)]
>>> # third endpoint
>>> ep = intf[2]
</code>```

As you can see, the index is zero based. But wait! There
  is something weird in the way I access
  an interface... Yes, you are right,
  the subscript operator in the
  Configuration accepts a sequence of
  two items, with the first one being
  the index of the Interface and the
  second one, the alternate setting. So,
  to access the first interface, but its
  second alternate setting, we write
  cfg[(0,1)].

Title: light up the mass storage's led

Body:
I have usb mass stroage with led

I am trying to light on and off the led

using usb packet sniffing tool USBlyzer,

I can get the raw data

55 53 42 43 58 66 93 88 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

whose Request info is Bulk or Interrupt Transfer and I/O is out

and in the USB properties section

I can get the info such as

Endpoint Descriptor 81 1 In, bulk, 512 bytes

bDescriptorType 05h Endpoint

bEndpointAddress 81h 1 In

Endpoint Descriptor 02 2 In, bulk, 512 bytes

bDescriptorType 05h Endpoint

bEndpointAddress 02h 2 Out

I made a python code with python 2.7, libusb-win32-bin-1.2.4.0, pyusb-1.0.0-a1

the full source is here

import usb.core
import usb.util

# find our device
dev = usb.core.find(idVendor=0x1516, idProduct=0x8628)

# was it found?
if dev is None:
    raise ValueError('Device not found')

dev.set_configuration()
# get an endpoint instance
cfg = dev.get_active_configuration()
interface_number = cfg[0].bInterfaceNumber
alternate_setting = usb.control.get_interface(interface_number)
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = \
                                ineterface_number, bAlternateSetting = alternate_setting)
ep = usb.util.find_descriptor(intf,custom_match = \
                                  lambda e: \
                                      usb.util.endpoint_direction(e.bEndpointAddress) == \
                                      usb.util.ENDPOINT_OUT)
# set the active configuration. With no arguments, the first
# configuration will be the active one

assert ep is not None

ep.write(0x2,0x55)
ep.write(0x2,0x53)
ep.write(0x2,0x42)
ep.write(0x2,0x43)
ep.write(0x2,0x58)
ep.write(0x2,0x66)
ep.write(0x2,0x93)
ep.write(0x2,0x88)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x06)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)
ep.write(0x2,0x00)

but when I try to execute it,

Traceback (most recent call last):
  File "C:\Documents and Settings\kty1104\Desktop\usb2.py", line 14, in <module>
    interface_number = cfg[0].bInterfaceNumber
  File "C:\Python27\lib\site-packages\usb\core.py", line 447, in __getitem__
    return Interface(self.device, index[0], index[1], self.index)
TypeError: 'int' object is not subscriptable

arise

what's wrong with my code?

any if anything wrong concept is there, please let me know

thanks!

Body:
I don't know anything about pyusb, but my interpretation of the error message is that, contra others' opinions, cfg is not an integer, but that it requires a non-integral index. I say this because the exception is thrown in a __getitem__ function, which could only be cfg's __getitem__, because that's the only place a __getitem__ call would be made in the line

interface_number = cfg[0].bInterfaceNumber

Now if cfg were an int, it wouldn't have a __getitem__. The problem is that cfg's __getitem__ seems to expect to be able to subscript the index that it receives, as illustrated by the middle two arguments, index[0], index[1]. Since you passed cfg an integer, that's impossible.

From the tutorial:

You can also use the subscript
  operator to access the descriptors
  randomly, like that:

>>> # access the second configuration
>>> cfg = dev[1]
>>> # access the first interface
>>> intf = cfg[(0,0)]
>>> # third endpoint
>>> ep = intf[2]

As you can see, the index is zero based. But wait! There
  is something weird in the way I access
  an interface... Yes, you are right,
  the subscript operator in the
  Configuration accepts a sequence of
  two items, with the first one being
  the index of the Interface and the
  second one, the alternate setting. So,
  to access the first interface, but its
  second alternate setting, we write
  cfg[(0,1)].


答:
A DLL - a class library - should never be logging by itself. Even the ones that are there for output - like the one containing Console or even logger code - should never decide to write their own logfile. Logging work - all output work - that is not controllable or even fully controlled by the programmer using your DLL, is just going to be vexing behavior. And you should never write something with Vexing behavior.

Logging is the job of the person using your code, not of your code. If you are writing a Library or really anything else that usually has no output (like a Windows Service), it is customary to have a wrapper project for debugging and testing.

If it is important enough it warants an Exception. If it is not important enough for a Exception - it is propably not important enough at all. It is a daunting challenge to write good Exception handling, nevermind good Exception throwing code. But there are two articles on the mater that I link very often. And I really think would help you get you on the right paths:

https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/

https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

They really helped me get a handle on it. And thus far they helped countless others. And their ideas are not even tied to .NET only.

Title: C# how to log file inside a DLL?

Body:
I'm developing a DLL and I want to log some data it generates.

I wanted to use "Log4Net", but I found the problem that in a DLL I don't have an "App.config" file where I can write the XML code, so I don't know how to implement this (I'm new in this matters).

I read about "Singleton" but I saw it's better to avoid it since it has it's issues (i.e hide some visibility of the code, problems with unit tests, ...).

So my question is: How and what is the best way to create a log file for the data generated by my DLL?


问:
DBeaver Can't access non-default database
I'm using DBeaver 3.8.0 and trying to setup general connection to my local PostgreSQL database.

To view all the databases i have, I check the "Show non-default databases" checkbox. And when I try to access Schemas of one of my databases - I'm getting the error

org.jkiss.dbeaver.DBException: Can't access non-default database

答:
Right-click on the Db Connection in the database navigator (right-click on PostgreSQL)

Click on edit connection

Select PostgreSQL tab

Select Show all databases

Click ok to save

Note: I am using DBeaver Enterprise 7.0.0


问:
How to get the count of the selected nodes not the root
How to get the count of only the selected nodes(child nodes) not the root nodes in tree java-script ? </p>

答:
You can simply use this property childElementCount to get how many children in an element

but if you wanna only check if there are children or not you can use this method hasChildNodes(), it returns true or false

console.log(document.body.childElementCount);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div></code>```

Body:
You can simply use this property childElementCount to get how many children in an element

but if you wanna only check if there are children or not you can use this method hasChildNodes(), it returns true or false

console.log(document.body.childElementCount);

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>


问:
Conversion failed when converting varchar value 'N' to data type smallint
I'm just inserting some data from one table into another but I'm facing an error:

Conversion failed when converting varchar value 'N' to data type smallint.

It is because one of the column where I'm inserting is of smallint data type but the data is coming as 'N' so it is throwing an error.

```<code>Insert into target
(
ID
)
select
id
from source
</code>```

Data type of id from source is of varchar(10) and data type of ID from target is of smallint.

Can anyone suggest any answers? I tried with cast function but it is not working.

答:
As others have mentioned, you can't convert a VARCHAR(10) with a value of 'N' into a SMALLINT.

You need to decide what value, if any, to insert into the target table where the source value of [id] contains characters other than 0-9 or falls outside the range of a SMALLINT.

If you decide to null the value, you can use a TRY_CAST() function...

INSERT  INTO target ( [ID] )
SELECT  TRY_CAST ( [id] AS SMALLINT )
FROM    source ;
```

<p>This will insert a <code>NULL</code>, in the event the source value of <code>[id]</code> contains characters other than 0-9 or converts to an integer outside of the range of a SMALLINT.</p>

<p>If you decide, instead, to insert a pre-determined number (say, 0) on this condition, you can combine a <code>TRY_CAST()</code> with a <code>COALESCE()</code> functions...</p>

<pre class="lang-sql prettyprint-override"><code>INSERT  INTO target ( [ID] )
SELECT  COALESCE ( TRY_CAST ( [id] AS SMALLINT ), 0 )
FROM    source ;
</code>```

This will insert a 0, in the event the source value of [id] contains characters other than 0-9 or converts to an integer outside of the range of a SMALLINT.

Body:
I'm just inserting some data from one table into another but I'm facing an error:

Conversion failed when converting varchar value 'N' to data type smallint.

It is because one of the column where I'm inserting is of smallint data type but the data is coming as 'N' so it is throwing an error.

Insert into target
(
ID
)
select
id
from source

Data type of id from source is of varchar(10) and data type of ID from target is of smallint.

Can anyone suggest any answers? I tried with cast function but it is not working.

Body:
As others have mentioned, you can't convert a VARCHAR(10) with a value of 'N' into a SMALLINT.

You need to decide what value, if any, to insert into the target table where the source value of [id] contains characters other than 0-9 or falls outside the range of a SMALLINT.

If you decide to null the value, you can use a TRY_CAST() function...

INSERT  INTO target ( [ID] )
SELECT  TRY_CAST ( [id] AS SMALLINT )
FROM    source ;

This will insert a NULL, in the event the source value of [id] contains characters other than 0-9 or converts to an integer outside of the range of a SMALLINT.

If you decide, instead, to insert a pre-determined number (say, 0) on this condition, you can combine a TRY_CAST() with a COALESCE() functions...

INSERT  INTO target ( [ID] )
SELECT  COALESCE ( TRY_CAST ( [id] AS SMALLINT ), 0 )
FROM    source ;

This will insert a 0, in the event the source value of [id] contains characters other than 0-9 or converts to an integer outside of the range of a SMALLINT.


问:
mac os 10.6 server: crontab does not fire wget script
I am completely baffled by the behaviour of cron under Mac OS 10.6 Server. I am trying to run two scripts in a cronjob like this:

```<code>00 16 * * * /Users/myusername/script.sh
04 16 * * * /Users/myusername/crontest.sh
</code>```

While 'script.sh' contains a wget command:

```<code>#!/bin/sh
wget -r -l3 --no-parent -nc -A ".shtml" 'http://some.url/somethingelse/'
</code>```

'crontest.sh' contains just a test script:

```<code>echo "hi" >> /Users/myusername/crontest.txt
</code>```

Problem is, 'script.sh' does not fire, but 'crontest.sh' does. What could be the cause of the wget script not firing? Do the scripts require a specific encoding? Does cron write a log file somewhere?

(I tested the wget command by itself in the shell, where it works fine.)

答:
cron runs scripts with a very minimal environment.  In particular, its PATH doesn't contain all of the usual binaries directories, just /usr/bin and /bin, so any commands in other binaries directories (like wget) will not be available.

There are several ways to fix this.  One option is to have your script give the complete path of wget:

```<code>#!/bin/sh
/usr/local/bin/wget -r -l3 --no-parent -nc -A ".shtml" 'http://some.url/somethingelse/'
</code>```

(or whatever its actual path is -- use which wget to find out.)

Another is to explicitly set PATH in the script:

```<code>#!/bin/sh
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
wget -r -l3 --no-parent -nc -A ".shtml" 'http://some.url/somethingelse/'
</code>```

(or whatever PATH you normally use; be sure it includes wget's location.)

Or you can set the PATH in your crontab:

```<code>PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
00 16 * * * /Users/myusername/script.sh
04 16 * * * /Users/myusername/crontest.sh
</code>```

Body:
I am completely baffled by the behaviour of cron under Mac OS 10.6 Server. I am trying to run two scripts in a cronjob like this:

00 16 * * * /Users/myusername/script.sh
04 16 * * * /Users/myusername/crontest.sh

While 'script.sh' contains a wget command:

#!/bin/sh
wget -r -l3 --no-parent -nc -A ".shtml" 'http://some.url/somethingelse/'

'crontest.sh' contains just a test script:

echo "hi" >> /Users/myusername/crontest.txt

Problem is, 'script.sh' does not fire, but 'crontest.sh' does. What could be the cause of the wget script not firing? Do the scripts require a specific encoding? Does cron write a log file somewhere?

(I tested the wget command by itself in the shell, where it works fine.)

Body:
cron runs scripts with a very minimal environment.  In particular, its PATH doesn't contain all of the usual binaries directories, just /usr/bin and /bin, so any commands in other binaries directories (like wget) will not be available.

There are several ways to fix this.  One option is to have your script give the complete path of wget:

#!/bin/sh
/usr/local/bin/wget -r -l3 --no-parent -nc -A ".shtml" 'http://some.url/somethingelse/'

(or whatever its actual path is -- use which wget to find out.)

Another is to explicitly set PATH in the script:

#!/bin/sh
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
wget -r -l3 --no-parent -nc -A ".shtml" 'http://some.url/somethingelse/'

(or whatever PATH you normally use; be sure it includes wget's location.)

Or you can set the PATH in your crontab:

PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
00 16 * * * /Users/myusername/script.sh
04 16 * * * /Users/myusername/crontest.sh


问:
Aptana 3 error on Catalina - legacy Java Runtime 6 required
I installed Aptana Studio 3 on my MAC which I updated to the Newest OS Catalina. That is what outdated all my adobe applications and Dreamweaver was a favourite program. Installing Aptana Studio 3 I can't open it because it says I need to instal Legacy Java SE Runtime 6. But I can't install that because Catalina has a higher version of Java that is already installed. So I can't open Aptana Studio 3.

Any suggestions?

答: In my case I simply added to installation (requires a free account) the latest jdk-8u251-macosx-x64.dmg JDK from Oracle and everything turned out fine.</p>


问:
How to get multiple answers from the context using BertForQuestionAnswering
How do I get multiple answers from the text using BertForQuestionAnswering, just like for the below question there are two possible answers

a nice puppet

a software engineer

Below is the code snippet for the same:

```<code>from transformers import BertTokenizer, BertForQuestionAnswering
import torch

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')

question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet.Jim Henson was a software engineer."
input_ids = tokenizer.encode(question, text)
token_type_ids = [0 if i <= input_ids.index(102) else 1 for i in range(len(input_ids))]
start_scores, end_scores = model(torch.tensor([input_ids]), token_type_ids=torch.tensor([token_type_ids]))

all_tokens = tokenizer.convert_ids_to_tokens(input_ids)
answer = ' '.join(all_tokens[torch.argmax(start_scores) : torch.argmax(end_scores)+1])
print(answer)

'a software engineer' ```

Thanks in advance!!
```

答:
You are simply outputting the most likely answer according to BERT. If you want multiple answers, you will need to actually select multiple answers. In this case that would be the first and second most likely answer. To do this, create a new answer variable and select the second most likely start and answer word from the start_scores and end_scores variable. I recommend you use at torch.topk()

```<code>answer1_start, answer2_start = torch.topk(start_scores)
answer2_end, answer2_end = torch.topk(end_scores)

answer1 = ' '.join(all_tokens[answer1_start : answer1_end + 1])
answer2 = ' '.join(all_tokens[answer2_start : answer2_end + 1])

print(answer1, answer2)
</code>```

Let me know how this works.

Body:
How do I get multiple answers from the text using BertForQuestionAnswering, just like for the below question there are two possible answers

a nice puppet

a software engineer

Below is the code snippet for the same:

from transformers import BertTokenizer, BertForQuestionAnswering
import torch

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')

question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet.Jim Henson was a software engineer."
input_ids = tokenizer.encode(question, text)
token_type_ids = [0 if i <= input_ids.index(102) else 1 for i in range(len(input_ids))]
start_scores, end_scores = model(torch.tensor([input_ids]), token_type_ids=torch.tensor([token_type_ids]))

all_tokens = tokenizer.convert_ids_to_tokens(input_ids)
answer = ' '.join(all_tokens[torch.argmax(start_scores) : torch.argmax(end_scores)+1])
print(answer)

'a software engineer' ```

Thanks in advance!!

Body:
You are simply outputting the most likely answer according to BERT. If you want multiple answers, you will need to actually select multiple answers. In this case that would be the first and second most likely answer. To do this, create a new answer variable and select the second most likely start and answer word from the start_scores and end_scores variable. I recommend you use at torch.topk()

answer1_start, answer2_start = torch.topk(start_scores)
answer2_end, answer2_end = torch.topk(end_scores)

answer1 = ' '.join(all_tokens[answer1_start : answer1_end + 1])
answer2 = ' '.join(all_tokens[answer2_start : answer2_end + 1])

print(answer1, answer2)

Let me know how this works.


问:
No visible @interface for 'GIDSignIn' declares the selector 'handleURL:
I implemented the delegate method of Google SignIn in objective C. But I am getting the below error Error - No visible @interface for 'GIDSignIn'

```<code>- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *, id> *)options{

    return [[GIDSignIn sharedInstance] handleURL:url];

}
</code>```

答:
change from:

```<code>[[GIDSignIn sharedInstance] handleURL:url
                sourceApplication:sourceApplication
                       annotation:annotation];
</code>```

to:

```<code>[[GIDSignIn sharedInstance] handleURL:url];
</code>```

go to: https://developers.google.com/identity/sign-in/ios/quick-migration-guide#objective-c

Body:
I implemented the delegate method of Google SignIn in objective C. But I am getting the below error Error - No visible @interface for 'GIDSignIn'

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *, id> *)options{

    return [[GIDSignIn sharedInstance] handleURL:url];

}

Body:
change from:

[[GIDSignIn sharedInstance] handleURL:url
                sourceApplication:sourceApplication
                       annotation:annotation];

to:

[[GIDSignIn sharedInstance] handleURL:url];

go to: https://developers.google.com/identity/sign-in/ios/quick-migration-guide#objective-c


问:
Firestore returns invalid-argument while adding new data in react native ios
Im using firebase in React native which works fine on Android side but on IOS when i try to add item its show me this error.

[Error: [firestore/invalid-argument] Client specified an invalid argument. Note that this differs from failed-precondition. invalid-argument indicates arguments that are problematic regardless of the state of the system (e.g., an invalid field name).]

```<code> let story = firestore().collection('paidItems').doc();

        await story.set({
            id: story.id,
            name: title,
            url : image,
            passLink,
            password,
            createdAt: firestore.FieldValue.serverTimestamp(),
        });
</code>```

Already try new Object() Object.assign({}, data)

Thanks.

答:
```<code>let story = firestore().collection('paidItems').doc();
</code>```

Doc can't be empty, it expects parameter which you didn't provide.

However to add item, you can simply it like below.

```<code>let story = firestore().collection('paidItems');
let storyRes = await story.add({
            name: title,
            url : image,
            passLink,
            password,
            createdAt: firestore.FieldValue.serverTimestamp(),
        });
</code>```

Body:
Im using firebase in React native which works fine on Android side but on IOS when i try to add item its show me this error.

[Error: [firestore/invalid-argument] Client specified an invalid argument. Note that this differs from failed-precondition. invalid-argument indicates arguments that are problematic regardless of the state of the system (e.g., an invalid field name).]

 let story = firestore().collection('paidItems').doc();

        await story.set({
            id: story.id,
            name: title,
            url : image,
            passLink,
            password,
            createdAt: firestore.FieldValue.serverTimestamp(),
        });

Already try new Object() Object.assign({}, data)

Thanks.

Body:
let story = firestore().collection('paidItems').doc();

Doc can't be empty, it expects parameter which you didn't provide.

However to add item, you can simply it like below.

let story = firestore().collection('paidItems');
let storyRes = await story.add({
            name: title,
            url : image,
            passLink,
            password,
            createdAt: firestore.FieldValue.serverTimestamp(),
        });


问:
Oracle 11g Backward compatibility with older oracle releases
Our organization is planning to upgrade its most of the oracle servers & clients to 11g Release 2.

But one of our client system is still  using oracle 8i installation.

Can we able to access the objects of Oracle 8i from oracle 11g client?

Some blogs says that it should work and other say it won't.

Can anybody faced any issue with such configuration.

One of the senior dba told us that oracle only supports backward compatibility of 2 versions earlier to current version. Assuming this fact we shouldn't been able to access database objects running on oracle version 8.

Kindly help.

Thanks in advance.

答:
Oracle doesn't even list version 8 in any compatibility tables on their web site. We verified that current (11g R2) JDBC drivers from Oracle do not work with Oracle 8 database sources. It means that it is not possible to access Oracle 8 databases from the latest version of Oracle SQL Developer because it is using JDBC driver.

While there is a slim chance to be able to access Oracle 8 from some other Oracle 11g client, I would not bet my business on that.


问:
r: Error: replacement argument is zero length
I try to add the values of a vector by initializing as soon as there is a 0

ex: I have (0,1,1,1,1,0,1,1) and I am looking for that (0,1,2,3,4,0,1,2)

I extracted the column of my data.frame with my 0 and my 1

```<code>x <-as.numeric (as.array (base1 $ taring))
</code>```

I then apply the function to it:

```<code>for (i in 1: 3334) {
  if (x [i]! = 0)
    x [i] <- x [i] + x [i-1]
}
</code>```

But it returns the error to me:

```<code>Error in x [i] <- x [i] + x [i - 1]:
  replacement argument is zero length
</code>```

Please someone can tell me where this error came from, thank you.

答:
Array indices in R start at 1.  So, in your first iteration, when i = 1, i-1 is 0 and your code fails.  The fix is simple:

```<code>for (i in 2:3334){
  if(x[i]!=0)
    x[i]<-x[i]+x[i-1]
}
</code>```

To make your code a little more robust you might consider

```<code>if (length(x) > 2) {
  for (i in 2:length(x)){
    if(x[i]!=0)
      x[i]<-x[i]+x[i-1]
  }
}
</code>```

Body:
I try to add the values of a vector by initializing as soon as there is a 0

ex: I have (0,1,1,1,1,0,1,1) and I am looking for that (0,1,2,3,4,0,1,2)

I extracted the column of my data.frame with my 0 and my 1

x <-as.numeric (as.array (base1 $ taring))

I then apply the function to it:

for (i in 1: 3334) {
  if (x [i]! = 0)
    x [i] <- x [i] + x [i-1]
}

But it returns the error to me:

Error in x [i] <- x [i] + x [i - 1]:
  replacement argument is zero length

Please someone can tell me where this error came from, thank you.

Body:
Array indices in R start at 1.  So, in your first iteration, when i = 1, i-1 is 0 and your code fails.  The fix is simple:

for (i in 2:3334){
  if(x[i]!=0)
    x[i]<-x[i]+x[i-1]
}

To make your code a little more robust you might consider

if (length(x) > 2) {
  for (i in 2:length(x)){
    if(x[i]!=0)
      x[i]<-x[i]+x[i-1]
  }
}