问:
Get console Logger (or TaskListener) from Pipeline script method
If I have a Pipeline script method in Pipeline script (Jenkinsfile), my Global Pipeline Library's vars/ or in a src/ class, how can obtain the OutputStream for the console log? I want to write directly to the console log.

I know I can echo or println, but for this purpose I need to write without the extra output that yields. I also need to be able to pass the OutputStream to something else.

I know I can call TaskListener.getLogger() if I can get the  TaskListener (really hudson.util.StreamTaskListener) instance, but how?

I tried:

I've looked into manager.listener.logger (from the groovy postbuild plugin) and in the early-build context I'm calling from it doesn't yield an OutputStream that writes to the job's Console Log.

```<code>echo "listener is a ${manager.listener} - ${manager.listener.getClass().getName()} from ${manager} and has a ${manager.listener.logger} of class ${manager.listener.logger.getClass().getName()}"
</code>```

prints

```<code>listener is a hudson.util.LogTaskListener@420c55c4 - hudson.util.LogTaskListener from org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder$BadgeManager@58ac0c55 and has a java.io.PrintStream@715b9f99 of class java.io.PrintStream
</code>```

I know you can get it from a StepContext via context.get(TaskListener.class) but I'm not in a Step, I'm in a CpsScript (i.e. WorkflowScript i.e. Jenkinsfile).

Finding it from a CpsFlowExecution obtained from the DSL instance registered as the steps script-property, but I couldn't work out how to discover the TaskListener that's passed to it when it's created

How is it this hard? What am I missing? There's so much indirect magic I find it incredibly hard to navigate the system.

BTW, I'm aware direct access is blocked by Script Security, but I can create @Whitelisted methods, and anything in a global library's vars/ is always whitelisted anyway.

答:
You can access the build object from the Jenkins root object:

```<code>def listener = Jenkins.get()
    .getItemByFullName(env.JOB_NAME)
    .getBuildByNumber(Integer.parseInt(env.BUILD_NUMBER))
    .getListener()

def logger = listener.getLogger() as PrintStream

logger.println("Listener: ${listener} Logger: ${logger}")
</code>```

Result:

```<code>Listener: CloseableTaskListener[org.jenkinsci.plugins.workflow.log.BufferedBuildListener@6e9e6a16 / org.jenkinsci.plugins.workflow.log.BufferedBuildListener@6e9e6a16] Logger: java.io.PrintStream@423efc01
</code>```

Body:
If I have a Pipeline script method in Pipeline script (Jenkinsfile), my Global Pipeline Library's vars/ or in a src/ class, how can obtain the OutputStream for the console log? I want to write directly to the console log.

I know I can echo or println, but for this purpose I need to write without the extra output that yields. I also need to be able to pass the OutputStream to something else.

I know I can call TaskListener.getLogger() if I can get the  TaskListener (really hudson.util.StreamTaskListener) instance, but how?

I tried:

I've looked into manager.listener.logger (from the groovy postbuild plugin) and in the early-build context I'm calling from it doesn't yield an OutputStream that writes to the job's Console Log.

echo "listener is a ${manager.listener} - ${manager.listener.getClass().getName()} from ${manager} and has a ${manager.listener.logger} of class ${manager.listener.logger.getClass().getName()}"

prints

listener is a hudson.util.LogTaskListener@420c55c4 - hudson.util.LogTaskListener from org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder$BadgeManager@58ac0c55 and has a java.io.PrintStream@715b9f99 of class java.io.PrintStream

I know you can get it from a StepContext via context.get(TaskListener.class) but I'm not in a Step, I'm in a CpsScript (i.e. WorkflowScript i.e. Jenkinsfile).

Finding it from a CpsFlowExecution obtained from the DSL instance registered as the steps script-property, but I couldn't work out how to discover the TaskListener that's passed to it when it's created

How is it this hard? What am I missing? There's so much indirect magic I find it incredibly hard to navigate the system.

BTW, I'm aware direct access is blocked by Script Security, but I can create @Whitelisted methods, and anything in a global library's vars/ is always whitelisted anyway.

Body:
You can access the build object from the Jenkins root object:

def listener = Jenkins.get()
    .getItemByFullName(env.JOB_NAME)
    .getBuildByNumber(Integer.parseInt(env.BUILD_NUMBER))
    .getListener()

def logger = listener.getLogger() as PrintStream

logger.println("Listener: ${listener} Logger: ${logger}")

Result:

Listener: CloseableTaskListener[org.jenkinsci.plugins.workflow.log.BufferedBuildListener@6e9e6a16 / org.jenkinsci.plugins.workflow.log.BufferedBuildListener@6e9e6a16] Logger: java.io.PrintStream@423efc01


来源: stackexchange

问:
xcode wants to access key Xcode apple id in your keychain in xcode 9.1
#
I have tried my system password but there is no use.While opening skype also keychain popup window is coming.
I have gone through this link not working for me.
Repeated Popup: Xcode wants to access key "com.apple.dt.XcodeDeviceMonitor" in your keychain

答:
You can solve it pasting this on your terminal and restarting xcode:</p>

```<code>defaults write com.apple.dt.Xcode iCloudGaugeDisabled -bool YES
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can solve it pasting this on your terminal and restarting xcode:

defaults write com.apple.dt.Xcode iCloudGaugeDisabled -bool YES

ContentLicense: CC BY-SA 4.0


问:
Macro run time error
I have a peice of code that filters a column for zero values and returns the rowcount. I tried looping over different columns.this macro works well with small input.
But I have an excel sheet with 160106 rows. I want to run my macro on this . I am getting a run 1004 error.I found the following link which kind of explains the problem
http://support.microsoft.com/kb/210684

But I am not able to resolve it. Could anyone please help me. I am pasting my macro below

my sample file is in
http://rapidshare.com/files/457005707/data1.xlsx
it is a 96mb file

```<code>Option Explicit
Sub findrcn()
Dim wsStart As Worksheet
Dim sWord As String
Dim RowCount As Integer
Dim i As Long
Dim j As Long
Dim l As Long
Dim k As String
Dim Final As Integer
Dim lastrow As Integer
Dim rng As Range
Dim oBook As Workbook

Set wsStart = ActiveSheet
'this loop is to check if a sheet exists
    For j = 1 To Worksheets.Count
    k = Worksheets(j).Name
    If UCase(k) = UCase("Analysis") Then
        lastrow = ((Sheets("Analysis").Range("A" & Rows.Count).End(xlUp).Row) + 1)
    Else
        lastrow = 0
    End If

    Next j
    MsgBox "finished checking the sheets"
i = 1
For Each rng In Range("A1:B1").Columns
        sWord = Replace(rng.Address(RowAbsolute:=False), "$", "")   ''Now I am trying to loop over all the columns

    If lastrow = 0 Then
            Sheets.Add After:=Sheets(Sheets.Count) 'Adding a new sheet
            Sheets(Sheets.Count).Name = "Analysis"
            wsStart.AutoFilterMode = False

                With wsStart
                    .Range(sWord).AutoFilter Field:=i, Criteria1:="=0" 'if my column contains a 0 in it filter that

                        With .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
                        Final = .Count 'get the count of the number of rows after the filter
                        RowCount = Final - 1
                        End With

                       Sheets("Analysis").Range("A") = RowCount 'paste it in the analysis tab
                       Sheets("Analysis").Range("B") = (Range(sWord))

                End With
                wsStart.AutoFilterMode = False
                MsgBox "Trust in the Lord with all your heart and lean not on your own understanding; In all your ways acknowledge Him, and He will make your paths straight." & vbCrLf & "Proverbs 3:5" & vbCrLf & "                        SUCCESSFULLY     COMPLETED!!!"

    Else

        wsStart.AutoFilterMode = False

                lastrow = ((Sheets("Analysis").Range("A" & Rows.Count).End(xlUp).Row) + 1)
                With wsStart
                    .Range(sWord).AutoFilter Field:=i, Criteria1:="=0" 'if my column contains a 0 in it filter that
                        With .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
                        Final = .Count
                        RowCount = Final - 1 ' to account for column name
                        End With

                       Sheets("Analysis").Range("A" & lastrow) = RowCount 'paste it in the analysis tab
                       Sheets("Analysis").Range("B" & lastrow) = (Range(sWord))

                End With
                wsStart.AutoFilterMode = False

    End If
i = i + 1
Next rng
</code>```

答:
On first glance there seem to be a much simpler solution: use the CountIf function

eg assuming your data is on Sheet2, on your Analysis sheet put in a cell =COUNTIF(Sheet2!A:A,0)

this gives the count of cell = 0 in column A

If you need this in VBA for other reasons, you can use somthing like

```<code>Set r = ActiveSheet.Columns("A:A")
z = Application.WorksheetFunction.CountIf(r, "0")
</code>```

Title: Macro run time error

Body:
I have a peice of code that filters a column for zero values and returns the rowcount. I tried looping over different columns.this macro works well with small input.
But I have an excel sheet with 160106 rows. I want to run my macro on this . I am getting a run 1004 error.I found the following link which kind of explains the problem
http://support.microsoft.com/kb/210684

But I am not able to resolve it. Could anyone please help me. I am pasting my macro below

my sample file is in
http://rapidshare.com/files/457005707/data1.xlsx
it is a 96mb file

Option Explicit
Sub findrcn()
Dim wsStart As Worksheet
Dim sWord As String
Dim RowCount As Integer
Dim i As Long
Dim j As Long
Dim l As Long
Dim k As String
Dim Final As Integer
Dim lastrow As Integer
Dim rng As Range
Dim oBook As Workbook

Set wsStart = ActiveSheet
'this loop is to check if a sheet exists
    For j = 1 To Worksheets.Count
    k = Worksheets(j).Name
    If UCase(k) = UCase("Analysis") Then
        lastrow = ((Sheets("Analysis").Range("A" & Rows.Count).End(xlUp).Row) + 1)
    Else
        lastrow = 0
    End If

    Next j
    MsgBox "finished checking the sheets"
i = 1
For Each rng In Range("A1:B1").Columns
        sWord = Replace(rng.Address(RowAbsolute:=False), "$", "")   ''Now I am trying to loop over all the columns

    If lastrow = 0 Then
            Sheets.Add After:=Sheets(Sheets.Count) 'Adding a new sheet
            Sheets(Sheets.Count).Name = "Analysis"
            wsStart.AutoFilterMode = False

                With wsStart
                    .Range(sWord).AutoFilter Field:=i, Criteria1:="=0" 'if my column contains a 0 in it filter that

                        With .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
                        Final = .Count 'get the count of the number of rows after the filter
                        RowCount = Final - 1
                        End With

                       Sheets("Analysis").Range("A") = RowCount 'paste it in the analysis tab
                       Sheets("Analysis").Range("B") = (Range(sWord))

                End With
                wsStart.AutoFilterMode = False
                MsgBox "Trust in the Lord with all your heart and lean not on your own understanding; In all your ways acknowledge Him, and He will make your paths straight." & vbCrLf & "Proverbs 3:5" & vbCrLf & "                        SUCCESSFULLY     COMPLETED!!!"

    Else

        wsStart.AutoFilterMode = False

                lastrow = ((Sheets("Analysis").Range("A" & Rows.Count).End(xlUp).Row) + 1)
                With wsStart
                    .Range(sWord).AutoFilter Field:=i, Criteria1:="=0" 'if my column contains a 0 in it filter that
                        With .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
                        Final = .Count
                        RowCount = Final - 1 ' to account for column name
                        End With

                       Sheets("Analysis").Range("A" & lastrow) = RowCount 'paste it in the analysis tab
                       Sheets("Analysis").Range("B" & lastrow) = (Range(sWord))

                End With
                wsStart.AutoFilterMode = False

    End If
i = i + 1
Next rng

Body:
On first glance there seem to be a much simpler solution: use the CountIf function

eg assuming your data is on Sheet2, on your Analysis sheet put in a cell =COUNTIF(Sheet2!A:A,0)

this gives the count of cell = 0 in column A

If you need this in VBA for other reasons, you can use somthing like

Set r = ActiveSheet.Columns("A:A")
z = Application.WorksheetFunction.CountIf(r, "0")


问:
Closing tag missing in java soap xml
I'm trying to build a xml soap response in Java.
Every part of the message is ok except for a missing closing tag
    </ns1:receptorExpressResponse>

I searched at google and some books and all of them build the message the same way I did it. However in my message
    </ns1:receptorExpressResponse> tag doesn't appears

Below my code:

```<code>    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document mensajeNoFirmado3A = documentBuilder.newDocument();

    Element DestinatarioACHElement = mensajeNoFirmado3A.createElement("Destinatario_ACH");
    Element numOrdenOrgiginateElement = mensajeNoFirmado3A.createElement("num_orden_originante");
    numOrdenOrgiginateElement.setTextContent(mensaje2A.getNum_orden_originante());

    DestinatarioACHElement.appendChild(numOrdenOrgiginateElement);

    Element numOrdenAchElement = mensajeNoFirmado3A.createElement("num_orden_ach");
    numOrdenAchElement.setTextContent(mensaje2A.getNum_orden_ach());
    DestinatarioACHElement.appendChild(numOrdenAchElement);

    Element tipoOrdenElement = mensajeNoFirmado3A.createElement("tip_orden");
    tipoOrdenElement.setTextContent("250");
    DestinatarioACHElement.appendChild(tipoOrdenElement);

    Element codSucursalDestinatarioElement = mensajeNoFirmado3A.createElement("cod_sucursal_destinatario");
    codSucursalDestinatarioElement.setTextContent(mensaje2A.getCod_sucursal_destinatario());
    DestinatarioACHElement.appendChild(codSucursalDestinatarioElement);

    Element codPaisDestinatarioElement = mensajeNoFirmado3A.createElement("cod_pais_destinatario");
    codPaisDestinatarioElement.setTextContent(mensaje2A.getCod_pais_destinatario());
    DestinatarioACHElement.appendChild(codPaisDestinatarioElement);

    Element codRespuestaElement = mensajeNoFirmado3A.createElement("cod_respuesta");

    ...........................................

    codRespuestaElement.setTextContent(codRespuesta);
    DestinatarioACHElement.appendChild(codRespuestaElement);

    Element numOrdenDestElement = mensajeNoFirmado3A.createElement("num_orden_destinatario");

    ............................................

    DestinatarioACHElement.appendChild(numOrdenDestElement);
    Element titularDestinatarioElement = mensajeNoFirmado3A.createElement("titular_destinatario");

    if(isClienteBanco.get()){
        if ("CONFIRMACION DE APLICACION".equals(respuestaAbono.getEstado())) {
            titularDestinatarioElement.setTextContent(nombreCliente);
        } else{
            titularDestinatarioElement.setTextContent("XXX");
        }
    }
    else {
        titularDestinatarioElement.setTextContent("XXX");
    }

    DestinatarioACHElement.appendChild(titularDestinatarioElement);

    ....................

    mensajeNoFirmado3A.appendChild(DestinatarioACHElement);
    KeysFromPKCS12 keysFromPKCS12 = new KeysFromPKCS12(connections,parameterService);
    IKeys.KeyAndCert keyAndCert = keysFromPKCS12.getKeyAndCert();

    PrivateKey key = keyAndCert.getKey();
    document = documentBuilderFactory.newDocumentBuilder().newDocument();
    String keyname = parameterService.valueOf(XXXXXXXXXXXXXXXXXXXXX, XXXXXXXXXXXXX);
    //Node importedNode = document.importNode(mensajeNoFirmado3A.getDocumentElement(), true);
    //document.appendChild(importedNode);
    LOGGER.info("Firmamos el mensaje 3A...");
    XMLSigner.sign(document, null, document.importNode(mensajeNoFirmado3A.getDocumentElement(), true), key, keyname);

    try
    {
        MessageFactory mfactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = mfactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
        soapEnvelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");
        soapEnvelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        soapHeader.detachNode();

        SOAPBody soapBody = soapEnvelope.getBody();
        ////////soapBody = soapMessage.getSOAPBody();

        SOAPFactory soapFactory = SOAPFactory.newInstance();
        Name bodyName  = soapFactory.createName("receptorExpressResponse", "ns1", "http://tempuri.org/");
        //Name encName = soapFactory.createName("SOAP-ENV:encodingStyle");

        //SOAPBodyElement sbe = soapBody.addBodyElement(bodyName);
        //SOAPElement childElement = soapBody.addChildElement("receptorExpressResponse", "ns1");
        //sbe.addAttribute(encName, "http://schemas.xmlsoap.org/soap/encoding/");
        //
        SOAPElement child = soapBody.addBodyElement(bodyName);
        child.addNamespaceDeclaration("ns1", "http://tempuri.org/");
        child.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        soapBody.addDocument(document);

        soapMessage.saveChanges();

        LOGGER.info("Envelope added");
        LOGGER.info("SOAPMessage {}", soapMessage);

        document = toDocument(soapMessage);

        String soapMessageStr = soapMessageToString(soapMessage);
</code>```

The xml that I'm getting is the following:

```<code><SOAP-ENV:Envelope xmlns:SOAP- ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:receptorExpressResponse xmlns:ns1="http://tempuri.org/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

........................

</ds:Signature>

</SOAP-ENV:Body>
</SOAP-ENV:Envelope>"
</code>```

But I expect this:

```<code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:receptorExpressResponse xmlns:ns1="http://tempuri.org/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

 ..............................

</ds:Signature>
</ns1: receptorExpressResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

As you can see "/ns1:receptorExpressResponse" is missing at my response.

Please is somebody can help I will be very grateful

Thanks to Yuan, the final version:

```<code>try
    {
        MessageFactory mfactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = mfactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
        soapEnvelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");
        soapEnvelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        soapHeader.detachNode();

        SOAPBody soapBody = soapEnvelope.getBody();

        SOAPFactory soapFactory = SOAPFactory.newInstance();
        Name bodyName  = soapFactory.createName("receptorExpressResponse", "ns1", "http://tempuri.org/");

        SOAPElement child = soapBody.addBodyElement(bodyName);
        child.addNamespaceDeclaration("ns1", "http://tempuri.org/");
        child.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        Document childDoc = child.getOwnerDocument();
        Node signDocumentNode = childDoc.importNode(document.getFirstChild(), true);
        child.appendChild(signDocumentNode);
        soapMessage.saveChanges();

        LOGGER.info("Envelope added");
        LOGGER.info("SOAPMessage {}", soapMessage);

        document = toDocument(soapMessage);

        String soapMessageStr = soapMessageToString(soapMessage);

        LOGGER.info("SOAPMessageStr {}", soapMessageStr);
        LOGGER.info("Devolviendo Simple 3A");
        salida = nodeToString(document);
        LOGGER.info("Salida " + salida);
    } catch (SAXException e) {
        e.printStackTrace();
        LOGGER.info("SAXException {}", e);
    } catch(SOAPException ex) {
        ex.printStackTrace();
        LOGGER.info("SOPAException {}", ex);
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.info("IOException {}", e);
    }
</code>```

答:
Your output is correct.

<ns1:receptorExpressResponse xmlns:ns1="http://tempuri.org/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
```

Do you see the last / ? that means this xml element is complete.

So your problem is that make your other elements as children of this element (receptorExpressResponse)

Title: Closing tag missing in java soap xml

Body:
I'm trying to build a xml soap response in Java.
Every part of the message is ok except for a missing closing tag
    </ns1:receptorExpressResponse>

I searched at google and some books and all of them build the message the same way I did it. However in my message
    </ns1:receptorExpressResponse> tag doesn't appears

Below my code:

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document mensajeNoFirmado3A = documentBuilder.newDocument();

    Element DestinatarioACHElement = mensajeNoFirmado3A.createElement("Destinatario_ACH");
    Element numOrdenOrgiginateElement = mensajeNoFirmado3A.createElement("num_orden_originante");
    numOrdenOrgiginateElement.setTextContent(mensaje2A.getNum_orden_originante());

    DestinatarioACHElement.appendChild(numOrdenOrgiginateElement);

    Element numOrdenAchElement = mensajeNoFirmado3A.createElement("num_orden_ach");
    numOrdenAchElement.setTextContent(mensaje2A.getNum_orden_ach());
    DestinatarioACHElement.appendChild(numOrdenAchElement);

    Element tipoOrdenElement = mensajeNoFirmado3A.createElement("tip_orden");
    tipoOrdenElement.setTextContent("250");
    DestinatarioACHElement.appendChild(tipoOrdenElement);

    Element codSucursalDestinatarioElement = mensajeNoFirmado3A.createElement("cod_sucursal_destinatario");
    codSucursalDestinatarioElement.setTextContent(mensaje2A.getCod_sucursal_destinatario());
    DestinatarioACHElement.appendChild(codSucursalDestinatarioElement);

    Element codPaisDestinatarioElement = mensajeNoFirmado3A.createElement("cod_pais_destinatario");
    codPaisDestinatarioElement.setTextContent(mensaje2A.getCod_pais_destinatario());
    DestinatarioACHElement.appendChild(codPaisDestinatarioElement);

    Element codRespuestaElement = mensajeNoFirmado3A.createElement("cod_respuesta");

    ...........................................

    codRespuestaElement.setTextContent(codRespuesta);
    DestinatarioACHElement.appendChild(codRespuestaElement);

    Element numOrdenDestElement = mensajeNoFirmado3A.createElement("num_orden_destinatario");

    ............................................

    DestinatarioACHElement.appendChild(numOrdenDestElement);
    Element titularDestinatarioElement = mensajeNoFirmado3A.createElement("titular_destinatario");

    if(isClienteBanco.get()){
        if ("CONFIRMACION DE APLICACION".equals(respuestaAbono.getEstado())) {
            titularDestinatarioElement.setTextContent(nombreCliente);
        } else{
            titularDestinatarioElement.setTextContent("XXX");
        }
    }
    else {
        titularDestinatarioElement.setTextContent("XXX");
    }

    DestinatarioACHElement.appendChild(titularDestinatarioElement);

    ....................

    mensajeNoFirmado3A.appendChild(DestinatarioACHElement);
    KeysFromPKCS12 keysFromPKCS12 = new KeysFromPKCS12(connections,parameterService);
    IKeys.KeyAndCert keyAndCert = keysFromPKCS12.getKeyAndCert();

    PrivateKey key = keyAndCert.getKey();
    document = documentBuilderFactory.newDocumentBuilder().newDocument();
    String keyname = parameterService.valueOf(XXXXXXXXXXXXXXXXXXXXX, XXXXXXXXXXXXX);
    //Node importedNode = document.importNode(mensajeNoFirmado3A.getDocumentElement(), true);
    //document.appendChild(importedNode);
    LOGGER.info("Firmamos el mensaje 3A...");
    XMLSigner.sign(document, null, document.importNode(mensajeNoFirmado3A.getDocumentElement(), true), key, keyname);

    try
    {
        MessageFactory mfactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = mfactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
        soapEnvelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");
        soapEnvelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        soapHeader.detachNode();

        SOAPBody soapBody = soapEnvelope.getBody();
        ////////soapBody = soapMessage.getSOAPBody();

        SOAPFactory soapFactory = SOAPFactory.newInstance();
        Name bodyName  = soapFactory.createName("receptorExpressResponse", "ns1", "http://tempuri.org/");
        //Name encName = soapFactory.createName("SOAP-ENV:encodingStyle");

        //SOAPBodyElement sbe = soapBody.addBodyElement(bodyName);
        //SOAPElement childElement = soapBody.addChildElement("receptorExpressResponse", "ns1");
        //sbe.addAttribute(encName, "http://schemas.xmlsoap.org/soap/encoding/");
        //
        SOAPElement child = soapBody.addBodyElement(bodyName);
        child.addNamespaceDeclaration("ns1", "http://tempuri.org/");
        child.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        soapBody.addDocument(document);

        soapMessage.saveChanges();

        LOGGER.info("Envelope added");
        LOGGER.info("SOAPMessage {}", soapMessage);

        document = toDocument(soapMessage);

        String soapMessageStr = soapMessageToString(soapMessage);

The xml that I'm getting is the following:

<SOAP-ENV:Envelope xmlns:SOAP- ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:receptorExpressResponse xmlns:ns1="http://tempuri.org/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

........................

</ds:Signature>

</SOAP-ENV:Body>
</SOAP-ENV:Envelope>"

But I expect this:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:receptorExpressResponse xmlns:ns1="http://tempuri.org/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

 ..............................

</ds:Signature>
</ns1: receptorExpressResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

As you can see "/ns1:receptorExpressResponse" is missing at my response.

Please is somebody can help I will be very grateful

Thanks to Yuan, the final version:

try
    {
        MessageFactory mfactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = mfactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
        soapEnvelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");
        soapEnvelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        soapHeader.detachNode();

        SOAPBody soapBody = soapEnvelope.getBody();

        SOAPFactory soapFactory = SOAPFactory.newInstance();
        Name bodyName  = soapFactory.createName("receptorExpressResponse", "ns1", "http://tempuri.org/");

        SOAPElement child = soapBody.addBodyElement(bodyName);
        child.addNamespaceDeclaration("ns1", "http://tempuri.org/");
        child.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        Document childDoc = child.getOwnerDocument();
        Node signDocumentNode = childDoc.importNode(document.getFirstChild(), true);
        child.appendChild(signDocumentNode);
        soapMessage.saveChanges();

        LOGGER.info("Envelope added");
        LOGGER.info("SOAPMessage {}", soapMessage);

        document = toDocument(soapMessage);

        String soapMessageStr = soapMessageToString(soapMessage);

        LOGGER.info("SOAPMessageStr {}", soapMessageStr);
        LOGGER.info("Devolviendo Simple 3A");
        salida = nodeToString(document);
        LOGGER.info("Salida " + salida);
    } catch (SAXException e) {
        e.printStackTrace();
        LOGGER.info("SAXException {}", e);
    } catch(SOAPException ex) {
        ex.printStackTrace();
        LOGGER.info("SOPAException {}", ex);
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.info("IOException {}", e);
    }

Body:
Your output is correct.

<ns1:receptorExpressResponse xmlns:ns1="http://tempuri.org/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

Do you see the last / ? that means this xml element is complete.

So your problem is that make your other elements as children of this element (receptorExpressResponse)


问:
Must specify either an analyzer type, or a tokenizer
I am basically new to elastic search .I am trying to implement fuzzy search , synonym search ,edge ngram and autocomplete on "name_auto" field , but it seems like my index creation is failing.

another question can i implement all the analyzer for "name" field if so how can i do it.

```<code>  {
        "settings": {
            "index": {
                "analysis": {
                    "filter": {
                        "synonym": {
                            "ignore_case": "true",
                            "type": "synonym",
                            "format": "wordnet",
                            "synonyms_path": "analysis/wn_s.pl"
                        }
                    },
                    "analyzer": {
                        "synonym": {
                            "tokenizer": "whitespace",

                            "filter": [
                                "synonym"
                            ]
                        },

                        "keyword_analyzer": {
                            "filter": [
                                "lowercase",
                                "asciifolding",
                                "trim"
                            ],
                            "char_filter": [],
                            "type": "custom",
                            "tokenizer": "keyword"
                        },
                        "edge_ngram_analyzer": {
                            "filter": [
                                "lowercase"
                            ],
                            "tokenizer": "edge_ngram_tokenizer"
                        },
                        "edge_ngram_search_analyzer": {
                            "tokenizer": "lowercase"
                        },

                        "tokenizer": {
                            "edge_ngram_tokenizer": {
                                "type": "edge_ngram",
                                "min_gram": 1,
                                "max_gram": 25,
                                "token_chars": [
                                    "letter"
                                ]
                            }
                        }
                    },
                    "mappings": {
                        "properties": {
                            "firebaseId": {
                                "type": "text"
                            },
                            "name": {
                                "fielddata": true,
                                "type": "text",
                                "analyzer": "standard"
                            },
                            "name_auto": {
                                "type": "text",

                                "fields": {
                                    "keywordstring": {
                                        "type": "text",
                                        "analyzer": "keyword_analyzer"
                                    },
                                    "edgengram": {
                                        "type": "text",
                                        "analyzer": "edge_ngram_analyzer",
                                        "search_analyzer": "edge_ngram_search_analyzer"
                                    },
                                    "completion": {
                                        "type": "completion"
                                    },
                                    "synonym_analyzer": {
                                        "type": "synonym",
                                        "analyzer": "synonym"
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }
    }
</code>```

This is the output :

```<code>>   {
>         "error": {
>             "root_cause": [
>                 {
>                     "type": "illegal_argument_exception",
>                     "reason": "analyzer [tokenizer] must specify either an analyzer type, or a tokenizer"
>                 }
>             ],
>             "type": "illegal_argument_exception",
>             "reason": "analyzer [tokenizer] must specify either an analyzer type, or a tokenizer"
>         },
>         "status": 400
>     }
</code>```

where am i doing wrong please guide me through right direction.

答:
Your tokenizer section is located inside the analyzer section, which is not correct. Try with this instead, it should work:

```<code>{
  "settings": {
    "index": {
      "analysis": {
        "filter": {
          "synonym": {
            "ignore_case": "true",
            "type": "synonym",
            "format": "wordnet",
            "synonyms_path": "analysis/wn_s.pl"
          }
        },
        "analyzer": {
          "synonym": {
            "tokenizer": "whitespace",
            "filter": [
              "synonym"
            ]
          },
          "keyword_analyzer": {
            "filter": [
              "lowercase",
              "asciifolding",
              "trim"
            ],
            "char_filter": [],
            "type": "custom",
            "tokenizer": "keyword"
          },
          "edge_ngram_analyzer": {
            "filter": [
              "lowercase"
            ],
            "tokenizer": "edge_ngram_tokenizer"
          },
          "edge_ngram_search_analyzer": {
            "tokenizer": "lowercase"
          }
        },
        "tokenizer": {
          "edge_ngram_tokenizer": {
            "type": "edge_ngram",
            "min_gram": 1,
            "max_gram": 25,
            "token_chars": [
              "letter"
            ]
          }
        }
      },
      "mappings": {
        "properties": {
          "firebaseId": {
            "type": "text"
          },
          "name": {
            "fielddata": true,
            "type": "text",
            "analyzer": "standard"
          },
          "name_auto": {
            "type": "text",
            "fields": {
              "keywordstring": {
                "type": "text",
                "analyzer": "keyword_analyzer"
              },
              "edgengram": {
                "type": "text",
                "analyzer": "edge_ngram_analyzer",
                "search_analyzer": "edge_ngram_search_analyzer"
              },
              "completion": {
                "type": "completion"
              },
              "synonym_analyzer": {
                "type": "synonym",
                "analyzer": "synonym"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Body:
I am basically new to elastic search .I am trying to implement fuzzy search , synonym search ,edge ngram and autocomplete on "name_auto" field , but it seems like my index creation is failing.

another question can i implement all the analyzer for "name" field if so how can i do it.

  {
        "settings": {
            "index": {
                "analysis": {
                    "filter": {
                        "synonym": {
                            "ignore_case": "true",
                            "type": "synonym",
                            "format": "wordnet",
                            "synonyms_path": "analysis/wn_s.pl"
                        }
                    },
                    "analyzer": {
                        "synonym": {
                            "tokenizer": "whitespace",

                            "filter": [
                                "synonym"
                            ]
                        },

                        "keyword_analyzer": {
                            "filter": [
                                "lowercase",
                                "asciifolding",
                                "trim"
                            ],
                            "char_filter": [],
                            "type": "custom",
                            "tokenizer": "keyword"
                        },
                        "edge_ngram_analyzer": {
                            "filter": [
                                "lowercase"
                            ],
                            "tokenizer": "edge_ngram_tokenizer"
                        },
                        "edge_ngram_search_analyzer": {
                            "tokenizer": "lowercase"
                        },

                        "tokenizer": {
                            "edge_ngram_tokenizer": {
                                "type": "edge_ngram",
                                "min_gram": 1,
                                "max_gram": 25,
                                "token_chars": [
                                    "letter"
                                ]
                            }
                        }
                    },
                    "mappings": {
                        "properties": {
                            "firebaseId": {
                                "type": "text"
                            },
                            "name": {
                                "fielddata": true,
                                "type": "text",
                                "analyzer": "standard"
                            },
                            "name_auto": {
                                "type": "text",

                                "fields": {
                                    "keywordstring": {
                                        "type": "text",
                                        "analyzer": "keyword_analyzer"
                                    },
                                    "edgengram": {
                                        "type": "text",
                                        "analyzer": "edge_ngram_analyzer",
                                        "search_analyzer": "edge_ngram_search_analyzer"
                                    },
                                    "completion": {
                                        "type": "completion"
                                    },
                                    "synonym_analyzer": {
                                        "type": "synonym",
                                        "analyzer": "synonym"
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }
    }

This is the output :

>   {
>         "error": {
>             "root_cause": [
>                 {
>                     "type": "illegal_argument_exception",
>                     "reason": "analyzer [tokenizer] must specify either an analyzer type, or a tokenizer"
>                 }
>             ],
>             "type": "illegal_argument_exception",
>             "reason": "analyzer [tokenizer] must specify either an analyzer type, or a tokenizer"
>         },
>         "status": 400
>     }

where am i doing wrong please guide me through right direction.

Body:
Your tokenizer section is located inside the analyzer section, which is not correct. Try with this instead, it should work:

{
  "settings": {
    "index": {
      "analysis": {
        "filter": {
          "synonym": {
            "ignore_case": "true",
            "type": "synonym",
            "format": "wordnet",
            "synonyms_path": "analysis/wn_s.pl"
          }
        },
        "analyzer": {
          "synonym": {
            "tokenizer": "whitespace",
            "filter": [
              "synonym"
            ]
          },
          "keyword_analyzer": {
            "filter": [
              "lowercase",
              "asciifolding",
              "trim"
            ],
            "char_filter": [],
            "type": "custom",
            "tokenizer": "keyword"
          },
          "edge_ngram_analyzer": {
            "filter": [
              "lowercase"
            ],
            "tokenizer": "edge_ngram_tokenizer"
          },
          "edge_ngram_search_analyzer": {
            "tokenizer": "lowercase"
          }
        },
        "tokenizer": {
          "edge_ngram_tokenizer": {
            "type": "edge_ngram",
            "min_gram": 1,
            "max_gram": 25,
            "token_chars": [
              "letter"
            ]
          }
        }
      },
      "mappings": {
        "properties": {
          "firebaseId": {
            "type": "text"
          },
          "name": {
            "fielddata": true,
            "type": "text",
            "analyzer": "standard"
          },
          "name_auto": {
            "type": "text",
            "fields": {
              "keywordstring": {
                "type": "text",
                "analyzer": "keyword_analyzer"
              },
              "edgengram": {
                "type": "text",
                "analyzer": "edge_ngram_analyzer",
                "search_analyzer": "edge_ngram_search_analyzer"
              },
              "completion": {
                "type": "completion"
              },
              "synonym_analyzer": {
                "type": "synonym",
                "analyzer": "synonym"
              }
            }
          }
        }
      }
    }
  }
}


问:
How to delete text after a given constraint?
So, I have a SQL file with the following content in it:

```<code>createtab_stmt
CREATE EXTERNAL TABLE `table1`(
"  `name_id` bigint, "
"  `address_id` string, "
"  `full_name` bigint, "
  `insert_timestamp` timestamp)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
</code>```

**I am trying to delete all text that comes after the ) in the third to last sentence ( "timestamp)" ). So the output should be everything before row format serde:

```<code>createtab_stmt
    CREATE EXTERNAL TABLE `table1`(
    "  `name_id` bigint, "
    "  `address_id` string, "
    "  `full_name` bigint, "
      `insert_timestamp` timestamp)
</code>```

This is my existing code:

```<code>import re
f = open("/home/dir2/ddl", 'rt', encoding='latin-1')
words=f.readlines()

with open("/home/dir1/sampl7.sql","w") as output:
    for i in words:
        output.write(i.replace('"', ''))
</code>```

Any ideas or suggestions? I'm not sure if regex is the best option or if there's a better way. Thanks.

答:
My method would be something like this:

```<code>f = open("/home/dir2/ddl", 'rt', encoding='latin-1')
source=f.read()

with open("/home/dir1/sampl7.sql","w") as output:
    output.write(source[:source.find(')')+1].replace('"', ''))
</code>```

.find() will find the index of the character ')' and we will use it to get the string from character 0 to that index (+ 1 to include the ')' itself).

Body:
So, I have a SQL file with the following content in it:

createtab_stmt
CREATE EXTERNAL TABLE `table1`(
"  `name_id` bigint, "
"  `address_id` string, "
"  `full_name` bigint, "
  `insert_timestamp` timestamp)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'

**I am trying to delete all text that comes after the ) in the third to last sentence ( "timestamp)" ). So the output should be everything before row format serde:

createtab_stmt
    CREATE EXTERNAL TABLE `table1`(
    "  `name_id` bigint, "
    "  `address_id` string, "
    "  `full_name` bigint, "
      `insert_timestamp` timestamp)

This is my existing code:

import re
f = open("/home/dir2/ddl", 'rt', encoding='latin-1')
words=f.readlines()

with open("/home/dir1/sampl7.sql","w") as output:
    for i in words:
        output.write(i.replace('"', ''))

Any ideas or suggestions? I'm not sure if regex is the best option or if there's a better way. Thanks.

Body:
My method would be something like this:

f = open("/home/dir2/ddl", 'rt', encoding='latin-1')
source=f.read()

with open("/home/dir1/sampl7.sql","w") as output:
    output.write(source[:source.find(')')+1].replace('"', ''))

.find() will find the index of the character ')' and we will use it to get the string from character 0 to that index (+ 1 to include the ')' itself).


问:
Android On Touch
I have been trying to make a program draw circles as I touch the screen with no luck, can anyone please tell me how I can do this? or GOOD tutorial that shows me how... I keep getting errors in my code

```<code>import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.lang.Math;

public class GameView extends View{

        private final float x;
        private final float y;
        private final int r;
        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        public GameView(Context context, float x, float y, int r) {
            super(context);
            setFocusable(true);
            mPaint.setColor(0xFFFF0000);
            this.x = x;
            this.y = y;
            this.r = r;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawCircle(x, y, r, mPaint);
        }

}
</code>```

GameActivity.java

```<code>import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

public class GameActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        FrameLayout main = (FrameLayout) findViewById(R.id.my_view);

        main.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(final View v, MotionEvent e) {

                 final float x = e.getX();
                 final float y = e.getY();
                  final Handler handler = new Handler()
                  {
                    public void handleMessage(Message msg) {

                      }
                    };
                    Thread graphicThread = new Thread()
                    {
                        public void run() {

                            try {

                                //Do the drop
                                   FrameLayout flView = (FrameLayout) v;
                                 GameView gm = new GameView(getParent(), x,y,25);
                                  flView.addView(gm);

                                     Thread.sleep(1000);

                                     handler.sendMessage(handler.obtainMessage());
                                }
                             catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }
                        };
                         boolean isRunning=true;
                        graphicThread.start();
                        return true;

                        }

        });

      }
    }
</code>```

答: As the NPE question is already answered, I want to provide an answer for the tutorial question. I have written a series (which is partly updated) which you can find here: I have written a tutorial about 2d graphics for a game. Read this: http://www.droidnova.com/2d-tutorial-series</p>

Title: Android On Touch

Body:
I have been trying to make a program draw circles as I touch the screen with no luck, can anyone please tell me how I can do this? or GOOD tutorial that shows me how... I keep getting errors in my code

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.lang.Math;

public class GameView extends View{

        private final float x;
        private final float y;
        private final int r;
        private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        public GameView(Context context, float x, float y, int r) {
            super(context);
            setFocusable(true);
            mPaint.setColor(0xFFFF0000);
            this.x = x;
            this.y = y;
            this.r = r;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawCircle(x, y, r, mPaint);
        }

}

GameActivity.java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

public class GameActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        FrameLayout main = (FrameLayout) findViewById(R.id.my_view);

        main.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(final View v, MotionEvent e) {

                 final float x = e.getX();
                 final float y = e.getY();
                  final Handler handler = new Handler()
                  {
                    public void handleMessage(Message msg) {

                      }
                    };
                    Thread graphicThread = new Thread()
                    {
                        public void run() {

                            try {

                                //Do the drop
                                   FrameLayout flView = (FrameLayout) v;
                                 GameView gm = new GameView(getParent(), x,y,25);
                                  flView.addView(gm);

                                     Thread.sleep(1000);

                                     handler.sendMessage(handler.obtainMessage());
                                }
                             catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }
                        };
                         boolean isRunning=true;
                        graphicThread.start();
                        return true;

                        }

        });

      }
    }


问:
Google Sheets v4 .NET batch get A1 notation for first row then all rows starting from another row
Brand new to Google Sheets API and A1 notation syntax.

I want to make a batch get to get the first row alone, and then all rows after a specified row.

I'm pretty sure 'Sheetname'!1:1 will get me the first row alone (right?), but what's the A1 notation for "Row 7 and any rows after row 7"?

Keep in mind I am using the .NET Google Sheets v4 API, so I am doing something like:

SpreadsheetsResource.ValuesResource.BatchGetRequest request = service.Spreadsheets.Values.BatchGet(MY_SPREADSHEET_ID);

request.DateTimeRenderOption = SpreadsheetsResource.ValuesResource.BatchGetRequest.DateTimeRenderOptionEnum.FORMATTEDSTRING;

request.Ranges = // what goes here?
```

答:
So it turns out that the way to do this is to specify the row and first column for the beginning of the range, and then a column that is beyond your known columns with no row specified to get all rows containing data after the row specified at the beginning of the range.

And for the .NET Sheets API, the way to specify multiple ranges is with a List<string>.

In my particular case, my columns end at N, so I know column Z is well beyond any data, so this would work to get me the first row, and then row 7 and all rows with data after row 7:

```<code>request.Ranges = new List<string>
{
    "Sheetname!A1:Z1",
    "Sheetname!A7:Z"
};
</code>```

Body:
So it turns out that the way to do this is to specify the row and first column for the beginning of the range, and then a column that is beyond your known columns with no row specified to get all rows containing data after the row specified at the beginning of the range.

And for the .NET Sheets API, the way to specify multiple ranges is with a List<string>.

In my particular case, my columns end at N, so I know column Z is well beyond any data, so this would work to get me the first row, and then row 7 and all rows with data after row 7:

request.Ranges = new List<string>
{
    "Sheetname!A1:Z1",
    "Sheetname!A7:Z"
};


问:
Selenium java webdriver 3: moveToElement not working
Selenium java webdriver 3: moveToElement not working.

```<code>WebElement element = ...
Actions actions = new Actions(driver);
actions.moveToElement(element).build().perform();
</code>```

Tried, adding click()

```<code>WebElement element = ...
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
</code>```

Not working. The mouse is not moved.

答:
WebElement abcd = ..........

```<code>Actions actions = new Actions(driver);

actions.moveToElement(abcd).perform();
</code>```

Above code will work, but please check with the chrome.exe version and the chrome version you are using it your machine. both should be compatible to one another. Check the compatibility with below link.

https://sites.google.com/a/chromium.org/chromedriver/

Body:
Selenium java webdriver 3: moveToElement not working.

WebElement element = ...
Actions actions = new Actions(driver);
actions.moveToElement(element).build().perform();

Tried, adding click()

WebElement element = ...
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

Not working. The mouse is not moved.

Body:
WebElement abcd = ..........

Actions actions = new Actions(driver);

actions.moveToElement(abcd).perform();

Above code will work, but please check with the chrome.exe version and the chrome version you are using it your machine. both should be compatible to one another. Check the compatibility with below link.

https://sites.google.com/a/chromium.org/chromedriver/


问:
Querying based on columns?
A beginner with SQL here - say I have a recipient table and I'm trying to come up with a query and sort the results by ethnicity. Usually I would do

```<code>select abcd
from recipient
where ehthnicity = 'White'
</code>```

but this table has ethnicities listed as fields (attributes) - is this a bad design?

What would be the best way to go about this?

答:
Yes, it's typically a bad design. Reasons vary depending on details.

This data structure is called a pivot, so you want to search on how to do pivot queries if you're stuck with such a table and can't change its design.

Example: https://databricks.com/blog/2018/11/01/sql-pivot-converting-rows-to-columns.html

Oracle supports PIVOT clauses, lucky for you.

Title: Querying based on columns?

Body:
A beginner with SQL here - say I have a recipient table and I'm trying to come up with a query and sort the results by ethnicity. Usually I would do

select abcd
from recipient
where ehthnicity = 'White'

but this table has ethnicities listed as fields (attributes) - is this a bad design?

What would be the best way to go about this?


问:
Knitr 'asis' option not working when R produces LaTeX code
I am running a process where I automatically produce a report. It has worked up until a point. But now knitr::opts_chunk$set(result='asis') does not work when I cat LaTeX code into the document. It replaces the \ with \textbackslash{} when I knit the document. Even though if you run the cat command on its own, it produces the correct LaTeX code:

```<code>---
title: "Untitled"
date: "October 15, 2017"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, comment = NA, background = NA, results='asis')
```

```{r}
cat("
  \\begin{tabular*}{1\\textwidth}{c c}
  \\parbox[c]{0.4\\linewidth}{
    {\\HUGE{\\textcolor{blue}{\\textbf{\\uppercase{Headline}}} }}\\\\
    \\Large{{\\textsc{Example}}}\\\\
  }&
    \\parbox{0.25\\textwidth}{
      \\icontext{MapMarker}{12}{Global}\\\\
      \\icontext{MobilePhone}{12}{999 666 23}\\\\
      \\icontext{Send}{12}{someemail@gmail.com}\\\\
    }
  \\end{tabular*}")
```
</code>```

The error being produced:

I have tried using knitr::asis_output(), but it results in the same error

The Tex being produced is the following:

```<code>\begin{document}
\maketitle

\textbackslash{}begin\{tabular\emph{\}\{1\textwidth\}\{c c\}
\parbox[c]{0.4\linewidth}{
    {\HUGE{\textcolor{blue}{\textbf{\uppercase{Headline}}} }}\\
    \Large{{\textsc{Example}}}\\
  }\& \parbox{0.25\textwidth}{
      \icontext{MapMarker}{12}{Glogab}\\
      \icontext{MobilePhone}{12}{999 666 23}\\
      \icontext{Send}{12}{someemail@gmail.com}\\
    } \textbackslash{}end\{tabular}\}

\end{document}
</code>```

答:
There is finally a solution to these issues:

```<code>knitr::raw_latex("here all your tex content")

instead of cat() + results='asis'.
</code>```

https://github.com/yihui/knitr/issues/1622

Body:
I am running a process where I automatically produce a report. It has worked up until a point. But now knitr::opts_chunk$set(result='asis') does not work when I cat LaTeX code into the document. It replaces the \ with \textbackslash{} when I knit the document. Even though if you run the cat command on its own, it produces the correct LaTeX code:

---
title: "Untitled"
date: "October 15, 2017"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, comment = NA, background = NA, results='asis')
```

```{r}
cat("
  \\begin{tabular*}{1\\textwidth}{c c}
  \\parbox[c]{0.4\\linewidth}{
    {\\HUGE{\\textcolor{blue}{\\textbf{\\uppercase{Headline}}} }}\\\\
    \\Large{{\\textsc{Example}}}\\\\
  }&
    \\parbox{0.25\\textwidth}{
      \\icontext{MapMarker}{12}{Global}\\\\
      \\icontext{MobilePhone}{12}{999 666 23}\\\\
      \\icontext{Send}{12}{someemail@gmail.com}\\\\
    }
  \\end{tabular*}")
```

The error being produced:

I have tried using knitr::asis_output(), but it results in the same error

The Tex being produced is the following:

\begin{document}
\maketitle

\textbackslash{}begin\{tabular\emph{\}\{1\textwidth\}\{c c\}
\parbox[c]{0.4\linewidth}{
    {\HUGE{\textcolor{blue}{\textbf{\uppercase{Headline}}} }}\\
    \Large{{\textsc{Example}}}\\
  }\& \parbox{0.25\textwidth}{
      \icontext{MapMarker}{12}{Glogab}\\
      \icontext{MobilePhone}{12}{999 666 23}\\
      \icontext{Send}{12}{someemail@gmail.com}\\
    } \textbackslash{}end\{tabular}\}

\end{document}

Body:
There is finally a solution to these issues:

knitr::raw_latex("here all your tex content")

instead of cat() + results='asis'.

https://github.com/yihui/knitr/issues/1622


问:
Is there a way to format date to only show month and year in plsql?
I have trouble to output only month and year like this
December 2018 when I made a function to pass a parameter for the date.

I made a simple function with a parameter to return date only shows month and year with below test code. I used the month instead of mon as described from above, but there is a gap in between e.g. December     2019.

```<code>function get_month(p_month DATE DEFAULT sysdate)
return VARCHAR2
is

v_month varchar2(50);

begin

select to_char(trunc(p_month), 'Month yyyy') into v_month from dual;

return v_month;
commit;

end;
</code>```

Ideally, I would expect the output of the month in full name like to_char(sysdate,'Month DDth, YYYY') but without the day in the middle.

答:
This is explained in the documentation:

Oracle uses trailing blank characters and leading zeroes to fill format elements to a constant width. The width is equal to the display width of the largest element for the relevant format model ...

The character elements MONTH, MON, DAY, and DY are padded with trailing blanks to the width of the longest full month name ...

But also:

The FM modifier suppresses the above padding in the return value of the TO_CHAR function.

So as @WernfriedDomscheit said in a comment, add the FM modifier:

```<code>select to_char(trunc(p_month), 'FMMonth yyyy') into v_month from dual;
</code>```

although the trunc() isn't adding anything so:

```<code>select to_char(p_month, 'FMMonth yyyy') into v_month from dual;
</code>```

or more simply, avoid the context switch and just assign directly:

```<code>v_month := to_char(p_month, 'FMMonth yyyy');
</code>```

Body:
I have trouble to output only month and year like this
December 2018 when I made a function to pass a parameter for the date.

I made a simple function with a parameter to return date only shows month and year with below test code. I used the month instead of mon as described from above, but there is a gap in between e.g. December     2019.

function get_month(p_month DATE DEFAULT sysdate)
return VARCHAR2
is

v_month varchar2(50);

begin

select to_char(trunc(p_month), 'Month yyyy') into v_month from dual;

return v_month;
commit;

end;

Ideally, I would expect the output of the month in full name like to_char(sysdate,'Month DDth, YYYY') but without the day in the middle.

Body:
This is explained in the documentation:

Oracle uses trailing blank characters and leading zeroes to fill format elements to a constant width. The width is equal to the display width of the largest element for the relevant format model ...

The character elements MONTH, MON, DAY, and DY are padded with trailing blanks to the width of the longest full month name ...

But also:

The FM modifier suppresses the above padding in the return value of the TO_CHAR function.

So as @WernfriedDomscheit said in a comment, add the FM modifier:

select to_char(trunc(p_month), 'FMMonth yyyy') into v_month from dual;

although the trunc() isn't adding anything so:

select to_char(p_month, 'FMMonth yyyy') into v_month from dual;

or more simply, avoid the context switch and just assign directly:

v_month := to_char(p_month, 'FMMonth yyyy');


问:
Show each row colums information php and sql
I want to print the values of custom columns for all rows, I've got a sql developer file, i mean that i want to print some columns of every rows, if for example my table is named client and has name, subname and email i want to print every client name, subname and email I've found how to make it with mysql but I want to make it with php and sql developer.

The code I've shown only shows the first user name and not the rest names and other columns of other users.

```<code><?php
function clientes($conexion) {
    $consulta = "SELECT NOMBRE FROM CLIENTE";
    $stmt = $conexion -> prepare($consulta);
    $stmt -> execute();
    return $stmt -> fetchColumn();
}

echo clientes($conexion);
?>
</code>```

答:
For getting all columns

You need to address your SQL Query different for it to work probably. At the moment you are only looking for the field nombre. Try to change it to:

```<code>  $consulta = "SELECT * FROM CLIENTE";
</code>```

With the asterisk you calling all fields in the table cliente. For performance you should only call the fields your are needing. This would look like this:

```<code>  $consulta = "SELECT nombre,dni,sexo FROM CLIENTE";
</code>```

For getting all rows

At the moment you just address one row here. You need to change your code to

```<code>return $stmt ->fetchAll();
</code>```

Body:
I want to print the values of custom columns for all rows, I've got a sql developer file, i mean that i want to print some columns of every rows, if for example my table is named client and has name, subname and email i want to print every client name, subname and email I've found how to make it with mysql but I want to make it with php and sql developer.

The code I've shown only shows the first user name and not the rest names and other columns of other users.

<?php
function clientes($conexion) {
    $consulta = "SELECT NOMBRE FROM CLIENTE";
    $stmt = $conexion -> prepare($consulta);
    $stmt -> execute();
    return $stmt -> fetchColumn();
}

echo clientes($conexion);
?>

Body:
For getting all columns

You need to address your SQL Query different for it to work probably. At the moment you are only looking for the field nombre. Try to change it to:

  $consulta = "SELECT * FROM CLIENTE";

With the asterisk you calling all fields in the table cliente. For performance you should only call the fields your are needing. This would look like this:

  $consulta = "SELECT nombre,dni,sexo FROM CLIENTE";

For getting all rows

At the moment you just address one row here. You need to change your code to

return $stmt ->fetchAll();


问:
Missing ";" before statement
I can't figure out where I made a mistake in the syntax, please help. The error is in the first line. I made everything else before I did the first line and the error wasn't there before I made it.</p>

```<code>    String msg.payload2 = msg.payload.toLowerCase();
if (msg.payload2 == "-coinflip") {
    rnd = Math.floor (Math.random() * (2-0));
    if (rnd == 1) {
        msg.payload = "Heads";
    } else {
        msg.payload = "Tails";
    }
}
return msg.payload
</code>```

答:
msg is already an object therefore you can add properties without further declaration. And there is no need to cast a variable to anything in JS.

Your code should be:

```<code>msg.payload2 = msg.payload.toLowerCase();
if (msg.payload2 == "-coinflip") {
    rnd = Math.floor (Math.random() * (2-0));
    if (rnd == 1) {
        msg.payload = "Heads";
    } else {
        msg.payload = "Tails";
    }
}
return msg.payload
</code>```

Title: Missing ";" before statement

Body:
I can't figure out where I made a mistake in the syntax, please help. The error is in the first line. I made everything else before I did the first line and the error wasn't there before I made it.

    String msg.payload2 = msg.payload.toLowerCase();
if (msg.payload2 == "-coinflip") {
    rnd = Math.floor (Math.random() * (2-0));
    if (rnd == 1) {
        msg.payload = "Heads";
    } else {
        msg.payload = "Tails";
    }
}
return msg.payload

Body:
msg is already an object therefore you can add properties without further declaration. And there is no need to cast a variable to anything in JS.

Your code should be:

msg.payload2 = msg.payload.toLowerCase();
if (msg.payload2 == "-coinflip") {
    rnd = Math.floor (Math.random() * (2-0));
    if (rnd == 1) {
        msg.payload = "Heads";
    } else {
        msg.payload = "Tails";
    }
}
return msg.payload


问:
How do you debug heavily templated code in c++?
I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.

What tips or advice can you offer when trying to figure out why something is not compiling other than just picking through the code manually and hoping it will come to me?

答:
This should help you I think.

http://www.bdsoft.com/tools/stlfilt.html

I have not used it myself; but, it might help you. I can also tell you that as you get more experience with templates and metaprograms you will get used to the error messages. They can be a bit tough to read sometimes; but, there is logic to their madness. Just make your terminal as large as you can and try to translate what it is saying in your head as you read it.

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: David Segonds

OwnerDisplayName: James Matta


问:
Why nest an <svg> element inside another <svg> element?
Why would a demo such as this: http://jsbin.com/ejorus/2/edit, have an <svg> element nested inside another <svg> element?

```<code><svg class="graph">
    <svg viewBox="0 0 1000 1000" preserveAspectRatio="none">
        <g transform="translate(30,0)">
            <!-- ... -->
        </g>
    </svg>
</svg>
</code>```

The JS Bin is a modified version of the demo in this blog post: http://meloncholy.com/blog/making-responsive-svg-graphs/

答:
I am about to do this for an entirely different reason: website implementation efficiency.

I have several SVG files that I insert into my web page after downloading them via AJAX.  I want to consolidate them into one file because that's better for downloading.  I could do this with a text file and then insert the SVG text into a web page element's innerHTML property, but .svg files offer two additional advantages over .txt files:

1) The standard .svgz format allows you to store pre-zipped files on the web server, no need for mod_deflate. SVG files zip very efficiently, I'm seeing 70-85% compression.

2) The web browser parses the SVG outside of my javascript code, hopefully more efficiently.  To insert the svg element into the HTML, I use the parent element's insertBefore or appendChild method instead of innerHTML.

Body:
Why would a demo such as this: http://jsbin.com/ejorus/2/edit, have an <svg> element nested inside another <svg> element?

<svg class="graph">
    <svg viewBox="0 0 1000 1000" preserveAspectRatio="none">
        <g transform="translate(30,0)">

        </g>
    </svg>
</svg>

The JS Bin is a modified version of the demo in this blog post: http://meloncholy.com/blog/making-responsive-svg-graphs/


问:
Querying XML nodes in MS SQL
I have the following XML record.

```<code><row>
  <c1>BUSINESS.HOME</c1>
  <c1 m="2">PAYMENTS.HOME</c1>
  <c1 m="3">DEPARTMENT.PAGE</c1>
  <c1 m="4">SECTION.HOME</c1>
  <c1 m="5">ABOUT.HOME</c1>

  <c2>Our Business</c2>
  <c2 m="1" s="2">Businesul nostru</c2>
  <c2 m="2">Payment Services</c2>
  <c2 m="2" s="2">Plati</c2>
  <c2 m="3">Department Operations</c2>
  <c2 m="3" s="2">Departamente</c2>
  <c2 m="4">Section Operations</c2>
  <c2 m="4" s="2">Sectiuni</c2>
  <c2 m="5">ABOUT</c2>
  <c2 m="5" s="2">Despre</c2>

  <c6>2</c6>
  <c10>GB0010001</c10>
  <c11>1</c11>
</row>
</code>```

C2 are lables for C1 in two languages differentiated by the S attribute so the count of S2 is always double C1.

I would like to select a query with the following output.

```<code>NAME              LABEL
--------------------------------------
BUSINESS.HOME     Our Business
PAYMENTS.HOME     Payment Services
DEPARTMENT.PAGE   Department Operations
SECTION.HOME      Section Operations
ABOUT.HOME        ABOUT
</code>```

Every value from C1 and the corresponding first value from C2.

I tried cross apply like this:

```<code>select t.p.query('.').value('data(./c2)[1]', 'varchar(max)') c2
from table_name
cross apply XMLRECORD.nodes('(/row/c2)') t(p)
where ID  = 'HOME.PAGE'
</code>```

But do not know how to proceed further in order to exclude the foreign language and include the C1 tag.

答:
You've got a working approach already. That's fine.

I just want to add an alternative, which should be better in performance.

```<code>DECLARE @XML xml = '
<row>
  <c1>BUSINESS.HOME</c1>
  <c1 m="2">PAYMENTS.HOME</c1>
  <c1 m="3">DEPARTMENT.PAGE</c1>
  <c1 m="4">SECTION.HOME</c1>
  <c1 m="5">ABOUT.HOME</c1>

  <c2>Our Business</c2>
  <c2 m="1" s="2">Businesul nostru</c2>
  <c2 m="2">Payment Services</c2>
  <c2 m="2" s="2">Plati</c2>
  <c2 m="3">Department Operations</c2>
  <c2 m="3" s="2">Departamente</c2>
  <c2 m="4">Section Operations</c2>
  <c2 m="4" s="2">Sectiuni</c2>
  <c2 m="5">ABOUT</c2>
  <c2 m="5" s="2">Despre</c2>

  <c6>2</c6>
  <c10>GB0010001</c10>
  <c11>1</c11>
</row>';
</code>```

-- The query

```<code>WITH Tally(Nmbr) AS(SELECT TOP(@Xml.value('count(/row/c1)','int')) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM master..spt_values )
SELECT @Xml.value('(/row/c1/text())[sql:column("Nmbr")][1]','nvarchar(250)') AS [NAME]
      ,@xml.value('(/row/c2/text())[sql:column("Nmbr")*2-1][1]','nvarchar(250)') AS [LABEL]
FROM Tally;
</code>```

The idea in short:

Create a tally-on-the-fly returning a list from 1 to n, where n is the count of <c1> elements (if you have a numbers table, use this instead)

Use the Tally's Nmbr column, and introduce it into the XQuery predicate with sql:column().

The first .value() calls the <c1> value by its position.

The second calls the corresponding value by the position x2 -1. without "-1" you would get the other language.

This is another approach, filtering for <c2> elements without the s attribute. In this case we do not need the computation with position x2 -1:

```<code>WITH Tally(Nmbr) AS(SELECT TOP(@Xml.value('count(/row/c1)','int')) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM master..spt_values )
SELECT @Xml.value('(/row/c1/text())[sql:column("Nmbr")][1]','nvarchar(250)') AS [NAME]
      ,@xml.value('(/row/c2[empty(@s)]/text())[sql:column("Nmbr")][1]','nvarchar(250)') AS [LABEL]
FROM Tally
</code>```

Title: Querying XML nodes in MS SQL

Body:
I have the following XML record.

<row>
  <c1>BUSINESS.HOME</c1>
  <c1 m="2">PAYMENTS.HOME</c1>
  <c1 m="3">DEPARTMENT.PAGE</c1>
  <c1 m="4">SECTION.HOME</c1>
  <c1 m="5">ABOUT.HOME</c1>

  <c2>Our Business</c2>
  <c2 m="1" s="2">Businesul nostru</c2>
  <c2 m="2">Payment Services</c2>
  <c2 m="2" s="2">Plati</c2>
  <c2 m="3">Department Operations</c2>
  <c2 m="3" s="2">Departamente</c2>
  <c2 m="4">Section Operations</c2>
  <c2 m="4" s="2">Sectiuni</c2>
  <c2 m="5">ABOUT</c2>
  <c2 m="5" s="2">Despre</c2>

  <c6>2</c6>
  <c10>GB0010001</c10>
  <c11>1</c11>
</row>

C2 are lables for C1 in two languages differentiated by the S attribute so the count of S2 is always double C1.

I would like to select a query with the following output.

NAME              LABEL
--------------------------------------
BUSINESS.HOME     Our Business
PAYMENTS.HOME     Payment Services
DEPARTMENT.PAGE   Department Operations
SECTION.HOME      Section Operations
ABOUT.HOME        ABOUT

Every value from C1 and the corresponding first value from C2.

I tried cross apply like this:

select t.p.query('.').value('data(./c2)[1]', 'varchar(max)') c2
from table_name
cross apply XMLRECORD.nodes('(/row/c2)') t(p)
where ID  = 'HOME.PAGE'

But do not know how to proceed further in order to exclude the foreign language and include the C1 tag.

Body:
You've got a working approach already. That's fine.

I just want to add an alternative, which should be better in performance.

DECLARE @XML xml = '
<row>
  <c1>BUSINESS.HOME</c1>
  <c1 m="2">PAYMENTS.HOME</c1>
  <c1 m="3">DEPARTMENT.PAGE</c1>
  <c1 m="4">SECTION.HOME</c1>
  <c1 m="5">ABOUT.HOME</c1>

  <c2>Our Business</c2>
  <c2 m="1" s="2">Businesul nostru</c2>
  <c2 m="2">Payment Services</c2>
  <c2 m="2" s="2">Plati</c2>
  <c2 m="3">Department Operations</c2>
  <c2 m="3" s="2">Departamente</c2>
  <c2 m="4">Section Operations</c2>
  <c2 m="4" s="2">Sectiuni</c2>
  <c2 m="5">ABOUT</c2>
  <c2 m="5" s="2">Despre</c2>

  <c6>2</c6>
  <c10>GB0010001</c10>
  <c11>1</c11>
</row>';

-- The query

WITH Tally(Nmbr) AS(SELECT TOP(@Xml.value('count(/row/c1)','int')) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM master..spt_values )
SELECT @Xml.value('(/row/c1/text())[sql:column("Nmbr")][1]','nvarchar(250)') AS [NAME]
      ,@xml.value('(/row/c2/text())[sql:column("Nmbr")*2-1][1]','nvarchar(250)') AS [LABEL]
FROM Tally;

The idea in short:

Create a tally-on-the-fly returning a list from 1 to n, where n is the count of <c1> elements (if you have a numbers table, use this instead)

Use the Tally's Nmbr column, and introduce it into the XQuery predicate with sql:column().

The first .value() calls the <c1> value by its position.

The second calls the corresponding value by the position x2 -1. without "-1" you would get the other language.

This is another approach, filtering for <c2> elements without the s attribute. In this case we do not need the computation with position x2 -1:

WITH Tally(Nmbr) AS(SELECT TOP(@Xml.value('count(/row/c1)','int')) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM master..spt_values )
SELECT @Xml.value('(/row/c1/text())[sql:column("Nmbr")][1]','nvarchar(250)') AS [NAME]
      ,@xml.value('(/row/c2[empty(@s)]/text())[sql:column("Nmbr")][1]','nvarchar(250)') AS [LABEL]
FROM Tally


问:
Auto Increment filed not returning value (Not Primary Key) - Spring boot JPA
According to my requirement I have field with auto increment & not a key. I'm in need of getting the value of that auto increment field after calling repository save().

```<code>merchantEntity = merchantRepository.save(merchantEntity);
merchantEntity.getMerchId() // returns null
</code>```

But some how im not getting the value of auto increment filed, it returns null.
Here is my Entity Class.

```<code>@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Integer merchId;
</code>```

I have tried using several other workarounds such as flushing the entity just after save. But the result is same.

```<code>        merchantEntity = merchantRepository.saveAndFlush(entity); // still returns null

        merchantEntity = merchantRepository.save(entity);
        merchantRepository.flush();
        MerchantEntity toBeUpdatedMerchantEntity =
                  merchantRepository.findOne(merchantEntity.getId()); // still returns null
</code>```

Is it possible to achieve what i'm expecting. Any help is highly appreciated.
Thanks

答:
The only way to get this auto incremented value is to do a refresh of the record.

Because JPA only fetches a primary key because after EntityManager.persist() the ID must be set.

So you have to reload the record with findOne() or EntityManager.refresh()

Body:
According to my requirement I have field with auto increment & not a key. I'm in need of getting the value of that auto increment field after calling repository save().

merchantEntity = merchantRepository.save(merchantEntity);
merchantEntity.getMerchId() // returns null

But some how im not getting the value of auto increment filed, it returns null.
Here is my Entity Class.

@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Integer merchId;

I have tried using several other workarounds such as flushing the entity just after save. But the result is same.

        merchantEntity = merchantRepository.saveAndFlush(entity); // still returns null

        merchantEntity = merchantRepository.save(entity);
        merchantRepository.flush();
        MerchantEntity toBeUpdatedMerchantEntity =
                  merchantRepository.findOne(merchantEntity.getId()); // still returns null

Is it possible to achieve what i'm expecting. Any help is highly appreciated.
Thanks


问:
na.locf - Negative length vectors are not allowed
I am trying carry forward non-na values until reaching the next non-na with the following code:

```<code>test3 <- data.table(final_data)

test3 <- test3[, na.locf(test3, na.rm = F, fromLast = F, maxgap = Inf), by = "gvkey"]
</code>```

It works when I don't include the ... by = gvkey] part.
However, I need the code to stop when reaching a new gvkey, bc otherwise it would carry forward wrong company data. I got it in long format (example below). As you can see, what happens if i don't use ...by = gvkey], it carries the value of gvkey1 over to gvkey2, which I want to avoid. But when doing so, I receive the following error message:

```<code>Error in `[.data.table`(test3, , na.locf(test3, na.rm = F, fromLast = F,  :
  negative length vectors are not allowed
</code>```

date	gvkey	dlcq	dlttq

date1	gvkey1	10	20

date2	gvkey1	NA	NA

date3	gvkey1	NA	10

.

.

.

date10	gvkey2	NA	NA

date11	gvkey2	10	NA

date12	gvkey2	NA	NA

```

Any suggestions/solutions very welcome!

答:
Using the data shown reproducibly in the Note at the end I don't get any error messages:

```<code>library(data.table)
library(zoo)

test3[, na.locf(test3, na.rm = FALSE, fromLast = FALSE, maxgap = Inf), by = "gvkey"]
</code>```

giving this which has no errors although it is not the desired answer.

```<code>     gvkey   date  gvkey dlcq dlttq
 1: gvkey1  date1 gvkey1   10    20
 2: gvkey1  date2 gvkey1   10    20
 3: gvkey1  date3 gvkey1   10    10
 4: gvkey1 date10 gvkey2   10    10
 5: gvkey1 date11 gvkey2   10    10
 6: gvkey1 date12 gvkey2   10    10
 7: gvkey2  date1 gvkey1   10    20
 8: gvkey2  date2 gvkey1   10    20
 9: gvkey2  date3 gvkey1   10    10
10: gvkey2 date10 gvkey2   10    10
11: gvkey2 date11 gvkey2   10    10
12: gvkey2 date12 gvkey2   10    10
</code>```

The problem is that the correct way to refer to test3 within test3 is to use .SD like this:

```<code>test3[, na.locf(.SD, na.rm = FALSE, fromLast = FALSE, maxgap = Inf), by = "gvkey"]
</code>```

giving:

```<code>    gvkey   date dlcq dlttq
1: gvkey1  date1   10    20
2: gvkey1  date2   10    20
3: gvkey1  date3   10    10
4: gvkey2 date10   NA    NA
5: gvkey2 date11   10    NA
6: gvkey2 date12   10    NA
</code>```

Note

```<code>Lines <- "
date | gvkey | dlcq | dlttq
date1 | gvkey1 | 10 | 20
date2 | gvkey1 | NA | NA
date3 | gvkey1 | NA | 10
date10 | gvkey2 | NA | NA
date11 | gvkey2 | 10 | NA
date12 | gvkey2 | NA | NA"

library(data.table)
test3 <- fread(Lines)
</code>```

Body:
I am trying carry forward non-na values until reaching the next non-na with the following code:

test3 <- data.table(final_data)

test3 <- test3[, na.locf(test3, na.rm = F, fromLast = F, maxgap = Inf), by = "gvkey"]

It works when I don't include the ... by = gvkey] part.
However, I need the code to stop when reaching a new gvkey, bc otherwise it would carry forward wrong company data. I got it in long format (example below). As you can see, what happens if i don't use ...by = gvkey], it carries the value of gvkey1 over to gvkey2, which I want to avoid. But when doing so, I receive the following error message:

Error in `[.data.table`(test3, , na.locf(test3, na.rm = F, fromLast = F,  :
  negative length vectors are not allowed

date	gvkey	dlcq	dlttq

date1	gvkey1	10	20

date2	gvkey1	NA	NA

date3	gvkey1	NA	10

.

.

.

date10	gvkey2	NA	NA

date11	gvkey2	10	NA

date12	gvkey2	NA	NA

Any suggestions/solutions very welcome!

Body:
Using the data shown reproducibly in the Note at the end I don't get any error messages:

library(data.table)
library(zoo)

test3[, na.locf(test3, na.rm = FALSE, fromLast = FALSE, maxgap = Inf), by = "gvkey"]

giving this which has no errors although it is not the desired answer.

     gvkey   date  gvkey dlcq dlttq
 1: gvkey1  date1 gvkey1   10    20
 2: gvkey1  date2 gvkey1   10    20
 3: gvkey1  date3 gvkey1   10    10
 4: gvkey1 date10 gvkey2   10    10
 5: gvkey1 date11 gvkey2   10    10
 6: gvkey1 date12 gvkey2   10    10
 7: gvkey2  date1 gvkey1   10    20
 8: gvkey2  date2 gvkey1   10    20
 9: gvkey2  date3 gvkey1   10    10
10: gvkey2 date10 gvkey2   10    10
11: gvkey2 date11 gvkey2   10    10
12: gvkey2 date12 gvkey2   10    10

The problem is that the correct way to refer to test3 within test3 is to use .SD like this:

test3[, na.locf(.SD, na.rm = FALSE, fromLast = FALSE, maxgap = Inf), by = "gvkey"]

giving:

    gvkey   date dlcq dlttq
1: gvkey1  date1   10    20
2: gvkey1  date2   10    20
3: gvkey1  date3   10    10
4: gvkey2 date10   NA    NA
5: gvkey2 date11   10    NA
6: gvkey2 date12   10    NA

Note

Lines <- "
date | gvkey | dlcq | dlttq
date1 | gvkey1 | 10 | 20
date2 | gvkey1 | NA | NA
date3 | gvkey1 | NA | 10
date10 | gvkey2 | NA | NA
date11 | gvkey2 | 10 | NA
date12 | gvkey2 | NA | NA"

library(data.table)
test3 <- fread(Lines)


问:
Response doesn't reach socket on multicast in Windows
I'm trying to get a little SSDP client / server up and running. So far the server is working just fine, responding to my M-SEARCH (according to wireshark). The client code is written in Visual Studio using Winsock2 (see code below). The problem is that the response never reaches my recv call when i send the search to the multicast address.

I already tried sending and receiving directly to the server ip address, which will generate a response that reaches my recv call correctly. However, when i change the ip to the multicast addess, it doesn't work (even though i can see the response on Wireshark!). So for some reason the socket (on OS level?) refuses to pass it on to the application.

I should note that the response is always unicast.

Here's my code:

```<code>#include <Winsock2.h> // before Windows.h, else Winsock 1 conflict
#include <Ws2tcpip.h> // needed for ip_mreq definition for multicast
#include <Windows.h>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define SERVERPORT 1900
char buff[] = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: ssdp:discover\r\nST: ssdp:all\r\n\r\n";

int main()
{
    char rcvdbuff[1000];
    int len, Ret = 2;

    WSADATA wsaData;
    if (WSAStartup(0x0101, &wsaData)) {
        perror("WSAStartup");
        return 1;
    }

    struct sockaddr_in their_addr;
    SOCKET sock;

    sock = socket(AF_INET, SOCK_DGRAM, 0);

    their_addr.sin_family = AF_INET;
    ////THIS APPROACH DOES NOT WORK
    their_addr.sin_addr.s_addr = inet_addr("239.255.255.250");
    //THIS APPROACH WORKS - SOMEHOW THE SOCKET IS BOUND TO THIS IP AND CAN THUS RECEIVE
    //their_addr.sin_addr.s_addr = inet_addr("192.168.3.90");
    their_addr.sin_port = htons(SERVERPORT);
    len = sizeof(struct sockaddr_in);

    while (1)
    {
        printf("buff:\n%s\n", buff);
        Ret = sendto(sock, buff, strlen(buff), 0, (struct sockaddr*)&their_addr, len);
        if (Ret < 0)
        {
            printf("error in SENDTO() function");
            closesocket(sock);
            return 0;
        }

        //Receiving Text from server
        printf("\n\nwaiting to recv:\n");
        memset(rcvdbuff, 0, sizeof(rcvdbuff));
        Ret = recvfrom(sock, rcvdbuff, sizeof(rcvdbuff), 0, (struct sockaddr *)&their_addr, &len);
        if (Ret < 0)
        {
            printf("Error in Receiving");
            return 0;
        }
        rcvdbuff[Ret - 1] = '\0';
        printf("RECEIVED MESSAGE FROM SERVER\t: %s\n", rcvdbuff);

        //Delay for testing purpose
        Sleep(3 * 1000);
    }
    closesocket(sock);
    WSACleanup();
}
</code>```

I tried one interesting thing (without restarting the application!):

1) First send to the direct ip address (192.168.3.90)

2) Get response

3) Now send to the multicast address

4) Now the response gets back just fine!

It's as if the socket somehow 'knows' the unicast address from the first send/recv call.

Does anyone know what to do or how to debug?

答:
I think I've found the solution to the question: Windows Firewall.
Here's a quote over from Quora:

Only connections that are explicitly allowed, using firewall rules, are permitted. Windows Firewall, by default, allows all outboundconnections, and permits only established inbound connections (that is, an inbound connection that is in direct response to an outbound connection initiated from your computer or network).

This is exactly the situation: We've not established an outbound connection, and thus it's blocked by Windows Firewall!

In the other case, when I first send directly, Windows Firewall opens up for that exact inbound connection and therefore the subsequent multicast send gets a response.

Body:
I'm trying to get a little SSDP client / server up and running. So far the server is working just fine, responding to my M-SEARCH (according to wireshark). The client code is written in Visual Studio using Winsock2 (see code below). The problem is that the response never reaches my recv call when i send the search to the multicast address.

I already tried sending and receiving directly to the server ip address, which will generate a response that reaches my recv call correctly. However, when i change the ip to the multicast addess, it doesn't work (even though i can see the response on Wireshark!). So for some reason the socket (on OS level?) refuses to pass it on to the application.

I should note that the response is always unicast.

Here's my code:

#include <Winsock2.h> // before Windows.h, else Winsock 1 conflict
#include <Ws2tcpip.h> // needed for ip_mreq definition for multicast
#include <Windows.h>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define SERVERPORT 1900
char buff[] = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: ssdp:discover\r\nST: ssdp:all\r\n\r\n";

int main()
{
    char rcvdbuff[1000];
    int len, Ret = 2;

    WSADATA wsaData;
    if (WSAStartup(0x0101, &wsaData)) {
        perror("WSAStartup");
        return 1;
    }

    struct sockaddr_in their_addr;
    SOCKET sock;

    sock = socket(AF_INET, SOCK_DGRAM, 0);

    their_addr.sin_family = AF_INET;
    ////THIS APPROACH DOES NOT WORK
    their_addr.sin_addr.s_addr = inet_addr("239.255.255.250");
    //THIS APPROACH WORKS - SOMEHOW THE SOCKET IS BOUND TO THIS IP AND CAN THUS RECEIVE
    //their_addr.sin_addr.s_addr = inet_addr("192.168.3.90");
    their_addr.sin_port = htons(SERVERPORT);
    len = sizeof(struct sockaddr_in);

    while (1)
    {
        printf("buff:\n%s\n", buff);
        Ret = sendto(sock, buff, strlen(buff), 0, (struct sockaddr*)&their_addr, len);
        if (Ret < 0)
        {
            printf("error in SENDTO() function");
            closesocket(sock);
            return 0;
        }

        //Receiving Text from server
        printf("\n\nwaiting to recv:\n");
        memset(rcvdbuff, 0, sizeof(rcvdbuff));
        Ret = recvfrom(sock, rcvdbuff, sizeof(rcvdbuff), 0, (struct sockaddr *)&their_addr, &len);
        if (Ret < 0)
        {
            printf("Error in Receiving");
            return 0;
        }
        rcvdbuff[Ret - 1] = '\0';
        printf("RECEIVED MESSAGE FROM SERVER\t: %s\n", rcvdbuff);

        //Delay for testing purpose
        Sleep(3 * 1000);
    }
    closesocket(sock);
    WSACleanup();
}

I tried one interesting thing (without restarting the application!):

1) First send to the direct ip address (192.168.3.90)

2) Get response

3) Now send to the multicast address

4) Now the response gets back just fine!

It's as if the socket somehow 'knows' the unicast address from the first send/recv call.

Does anyone know what to do or how to debug?


问:
CORS, S3 and CloudFront configuration
Whenever I try to POST a file to my S3 bucket, I get the following error message:

```<code>POST https://api.*.com/sermon 413
Access to XMLHttpRequest at 'https://api*.com/sermon' from origin 'https://*.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

My S3 ELB bucket is configured as follows (for https://api.*.com/sermon):

My Cloudfront is set up as follows (for https://api.*.com/sermon):

I've also set up a CloudFront Origin Response trigger as a Lambda function:

```<code>'use strict';

// If the response lacks a Vary: header, fix it in a CloudFront Origin Response trigger.

exports.handler = (event, context, callback) => {
    const response = event.Records[0].cf.response;
    const headers = response.headers;

    if (!headers['vary'])
    {
        headers['vary'] = [
            { key: 'Vary', value: 'Access-Control-Request-Headers' },
            { key: 'Vary', value: 'Access-Control-Request-Method' },
            { key: 'Vary', value: 'Origin' },
        ];
    }
    callback(null, response);
};
</code>```

HTTP status:

Is there anything I am missing?

答:
The CORS setup is on S3, but looks like you're hitting an HTTP 413 ("Payload too Large") at CloudFront, prior to reaching S3.  So this issue is not really related to CORS per se.

HTTP 413 usually means exceeding the CloudFront request size of 20 kb, or the URL length of 8 kb.  Note the 'request size' is defined to include the request headers & query strings but not the request body.

So the first thing is to verify that the request size & URL length limits aren't being exceeded.  And that any payload is in the POST body, not part of a request header.

Also see if uploading smaller files (< 100 mb) will work, to rule out any issues around multipart uploads.

Title: CORS, S3 and CloudFront configuration

Body:
Whenever I try to POST a file to my S3 bucket, I get the following error message:

POST https://api.*.com/sermon 413
Access to XMLHttpRequest at 'https://api*.com/sermon' from origin 'https://*.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My S3 ELB bucket is configured as follows (for https://api.*.com/sermon):

My Cloudfront is set up as follows (for https://api.*.com/sermon):

I've also set up a CloudFront Origin Response trigger as a Lambda function:

'use strict';

// If the response lacks a Vary: header, fix it in a CloudFront Origin Response trigger.

exports.handler = (event, context, callback) => {
    const response = event.Records[0].cf.response;
    const headers = response.headers;

    if (!headers['vary'])
    {
        headers['vary'] = [
            { key: 'Vary', value: 'Access-Control-Request-Headers' },
            { key: 'Vary', value: 'Access-Control-Request-Method' },
            { key: 'Vary', value: 'Origin' },
        ];
    }
    callback(null, response);
};

HTTP status:

Is there anything I am missing?


问:
Fullpage.js sticky header background color change when scrolling
I have fullpage.js working perfectly as I want it to. Also already got my header to be sticky. It starts transparent and when you scroll its background turns white. Thing is that when I enable fullpage.js it is as if the header was not detecting any scroll and therefore even though it stays sticky the background color does not change.

I have tested various settings to see if they work but none have yet worked. Im completely new to coding.

```<code>jQuery(document).ready(function($) {
$('#fullpage').fullpage({
    //options here
    scrollingSpeed: 1000,
    autoScrolling: true,
    navigation: true,
    slidesNavigation: true,
    css3: false,
    fitToSection: true,
    fitToSectionDelay: 0,
    scrollBar: false,
    lazyLoading: true,
    menu: true

});
//methods
$.fn.fullpage.setAllowScrolling(true);
$("#navigation").sticky({topSpacing:0}).css({'background':'#000'});
</code>```

});

I want that when the fullpage.js scrolls the header changes color. It currently does not detect any scrolling. Im sorry if this is too basic. Im just trying to learn and thanks!

答:
As detailed in the fullPage.js FAQs you'll need to use scrollBar:true or autoScrolling:false if you want to rely on the scroll event.

Otherwise, you should be using fullPage.js callbacks or state classes to deal with those changes of state.

You can check my video tutorial regarding how to use the fullpage.js state classes to trigger changes in state.

Body:
I have fullpage.js working perfectly as I want it to. Also already got my header to be sticky. It starts transparent and when you scroll its background turns white. Thing is that when I enable fullpage.js it is as if the header was not detecting any scroll and therefore even though it stays sticky the background color does not change.

I have tested various settings to see if they work but none have yet worked. Im completely new to coding.

jQuery(document).ready(function($) {
$('#fullpage').fullpage({
    //options here
    scrollingSpeed: 1000,
    autoScrolling: true,
    navigation: true,
    slidesNavigation: true,
    css3: false,
    fitToSection: true,
    fitToSectionDelay: 0,
    scrollBar: false,
    lazyLoading: true,
    menu: true

});
//methods
$.fn.fullpage.setAllowScrolling(true);
$("#navigation").sticky({topSpacing:0}).css({'background':'#000'});

});

I want that when the fullpage.js scrolls the header changes color. It currently does not detect any scrolling. Im sorry if this is too basic. Im just trying to learn and thanks!