问:
JAXBWrapperException: An internal assertion error occurred. JAXB object does not have a successflag xml property
I am exposing a web service whhich accepts data and inserts this data to DB and returns a successFlag if insertion is complete. I am not using any interface. The web parameters are given directly in the implementation class itself. When testing, the data is being inserted. But the SOAP response received shows JAXBWrapperException.

PFB the implementation java code, the WSDL,soap response and stack trace.Please tell me what is wrong.

Java impl class

@WebService
public class Service11_SAPCall {

```<code>Connection connect = null;
ResultSet result = null;

public void GetSrnDetails(
        @WebParam(name = "clear_db", mode = WebParam.Mode.IN) String clear_db,
        @WebParam(name = "count", mode = WebParam.Mode.IN) int count,
        @WebParam(name = "srnList", mode = WebParam.Mode.IN) srnDetailsBean[] srnList,
        @WebParam(name = "status", mode = WebParam.Mode.IN) String status,
        @WebParam(name = "successflag", mode = WebParam.Mode.OUT) Holder<String> successFlag,
        @WebParam(name = "failedSrnList", mode = WebParam.Mode.OUT) Holder<ArrayList<String>> failedSrnList)
{
    boolean dataFlag = false; //to identify if data is being inserted
    ArrayList<String> failed_srn_list = new ArrayList<String>();
    Logger LOGGER = null;
    try
    {
        Handler fh = new FileHandler("/data/build/Service11.log");
        LOGGER = Logger.getLogger(Service10_SAPCall.class.getName());
        Logger.getLogger("LOGGER").addHandler(fh);
        LOGGER.info("Logger Name : "+LOGGER.getName());
        System.out.println("GetSrnDetails execution begins");
        System.out.println("Inside GetSrnDetails");
        LOGGER.info("Inside GetSrnDetails");

        Properties props = new Properties();
        FileInputStream fin = null;
        fin = new FileInputStream("/data/build/ENivesh/Properties/DB_connection.txt");
        props.load(fin);
        //DB connection details
        String connection_url=props.getProperty("DCURL");
        String uname=props.getProperty("DCUserId");
        String pwd=props.getProperty("DCPwd");
        fin.close();

        //Load Driver
        Class.forName("com.ibm.db2.jcc.DB2Driver");
        System.out.println("Driver Loaded");
        System.out.println("connection_url="+connection_url+"\nuname="+uname+"\npwd="+pwd);

        System.out.println("Inside getcount");

        connect = DriverManager.getConnection(connection_url,uname,pwd);
        connect.setAutoCommit(false);
        Statement stmt_insertCount = connect.createStatement();
        int insert_count_status = 0;
        int insert_data_status[] = null;

        //Inserting the received count and status to DB
        String insert_count = "insert into SRN_COUNT_SERVICE11(DSD_SRN_STATUS,SRN_COUNT) values ('"+status+"','"+count+"')";
        insert_count_status=stmt_insertCount.executeUpdate(insert_count);

        //Inserting data passed if any.Data is passed only for beyond time line statuses.
        if(status.equalsIgnoreCase("HIAB-BT") || status.equalsIgnoreCase("WIPG-BT") || status.equalsIgnoreCase("PTPR-BT")
            || status.equalsIgnoreCase("UPDH-BT") || status.equalsIgnoreCase("PPRE-BT") || status.equalsIgnoreCase("PDMD-BT")
            || status.equalsIgnoreCase("UPAO-BT") || status.equalsIgnoreCase("PQAO-BT") || status.equalsIgnoreCase("PQRO-BT")
            || status.equalsIgnoreCase("PAID-BT") || status.equalsIgnoreCase("PQDH-BT") || status.equalsIgnoreCase("UPDH-BT"))
        {
            if(srnList.length != 0)
            {
                Statement stmt_insertData = connect.createStatement();
                String insert_data = null;
                for(int i=0; i<srnList.length; i++)
                {
                    insert_data = "insert into SRN_DTLS_SERVICE11 values "
                            + "('"+srnList[i].getSrn()+"','"+srnList[i].getStatus()+"','"
                            +srnList[i].getUserId()+"','"+srnList[i].getMobileNumber()+"','"
                            +srnList[i].getCompanyEmailId()+"','"+srnList[i].getAddressType()+"','"+srnList[i].getAddress()+"','"
                            +srnList[i].getCityCode()+"','"+srnList[i].getStateCode()+"','"+srnList[i].getDistrictCode()+"','"+srnList[i].getCountry()+"','"
                            +srnList[i].getCompanyname()+"','"+srnList[i].getTelNo()+"','"+srnList[i].getRocCode()+"','"+srnList[i].getDate()+"')";
                    stmt_insertData.addBatch(insert_data);
                }
                insert_data_status = stmt_insertData.executeBatch();
                for(int j=0; j<insert_data_status.length; j++)
                {
                    if(!(insert_data_status[j]>0))
                        failed_srn_list.add(srnList[j].getSrn());
                }
                dataFlag = true; //setting to true as data was inserted
            }
        }
        connect.commit();
        if(insert_count_status > 0) {
            if(dataFlag) {  //If data is inserted, failed_srn_list is checked to see if any insertions failed.If no X is passed.
                if (failed_srn_list.size() == 0)    {
                    successFlag.value = "X";
                }
                else {
                    failedSrnList.value.addAll(failed_srn_list); //if there are failed insertions, the failed SRNs are passed back to SAP.
                }
            } //If dataFlag is not set, only insertion of count is considered to set successFlag.
            else {
                successFlag.value = "X";
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        LOGGER.severe(ex.getMessage());
    }
    finally {
        try {
            connect.close();
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.severe(e.getMessage());
        }
    }
}
</code>```

}

WSDL

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sap="http://sapservice.me.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <sap:GetSrnDetails>
         <!--Optional:-->
         <clear_db></clear_db>
         <count></count>
         <!--Zero or more repetitions:-->
         <srnList>
            <!--Optional:-->
            <srn></srn>
            <!--Optional:-->
            <status></status>
            <!--Optional:-->
            <date></date>
            <!--Optional:-->
            <userId></userId>
            <!--Optional:-->
            <mobileNumber></mobileNumber>
            <!--Optional:-->
            <companyEmailId></companyEmailId>
            <!--Optional:-->
            <addressType>Home</addressType>
            <!--Optional:-->
            <address>home</address>
            <!--Optional:-->
            <cityCode>cuty</cityCode>
            <!--Optional:-->
            <stateCode>state</stateCode>
            <!--Optional:-->
            <districtCode></districtCode>
            <!--Optional:-->
            <country></country>
            <!--Optional:-->
            <telNo></telNo>
            <!--Optional:-->
            <companyname></companyname>
            <!--Optional:-->
            <rocCode></rocCode>
         </srnList>
         <!--Optional:-->
         <status></status>
      </sap:GetSrnDetails>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

SOAP error

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server</faultcode>
         <faultstring>org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.</faultstring>
         <detail/>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

Stack Trace

```<code>000000b9 AxisEngine    E org.apache.axis2.engine.AxisEngine receive org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.
                                 org.apache.axis2.AxisFault: org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.
    at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
    at org.apache.axis2.jaxws.server.JAXWSMessageReceiver.receive(JAXWSMessageReceiver.java:242)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:208)
    at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
    at com.ibm.ws.websvcs.transport.http.WASAxis2Servlet.doPost(WASAxis2Servlet.java:1583)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1032)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3761)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:976)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:459)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:526)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:312)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:283)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)
Caused by: javax.xml.ws.WebServiceException: org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.
    at org.apache.axis2.jaxws.ExceptionFactory.createWebServiceException(ExceptionFactory.java:175)
    at org.apache.axis2.jaxws.ExceptionFactory.makeWebServiceException(ExceptionFactory.java:70)
    at org.apache.axis2.jaxws.ExceptionFactory.makeWebServiceException(ExceptionFactory.java:128)
    at org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMethodMarshaller.marshalResponse(DocLitWrappedMethodMarshaller.java:511)
    at org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.createResponse(JavaBeanDispatcher.java:349)
    at org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.invoke(JavaBeanDispatcher.java:141)
    at org.apache.axis2.jaxws.server.EndpointController.invoke(EndpointController.java:111)
    at org.apache.axis2.jaxws.server.JAXWSMessageReceiver.receive(JAXWSMessageReceiver.java:161)
    ... 29 more
Caused by: org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.
    at org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperToolImpl.wrap(JAXBWrapperToolImpl.java:294)
    at org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMethodMarshaller.marshalResponse(DocLitWrappedMethodMarshaller.java:482)
    ... 33 more
</code>```

答:
I had the same issue after upgrading the WAS FP 8.5.5.10 to 8.5.5.12. We had two Services with exactly same method name but different targetNameSpace,like DomainService1 has 'get' method and DomainService2 also has 'get' method, but WAS 8.5.5.12 throws this exception and doesn't give any clue to find the root cause. Apparently WAS is more strict in recent version with the naming of the methods.

This was the exception: org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The com.xxx.web.myapp.services.jaxws.GetResponse JAXB object does not have a xxxxxStatus xml

After changing the name of the method specific to each service 'getABC' and 'getPQR' it worked!!!

hope this works!

Body:
I am exposing a web service whhich accepts data and inserts this data to DB and returns a successFlag if insertion is complete. I am not using any interface. The web parameters are given directly in the implementation class itself. When testing, the data is being inserted. But the SOAP response received shows JAXBWrapperException.

PFB the implementation java code, the WSDL,soap response and stack trace.Please tell me what is wrong.

Java impl class

@WebService
public class Service11_SAPCall {

Connection connect = null;
ResultSet result = null;

public void GetSrnDetails(
        @WebParam(name = "clear_db", mode = WebParam.Mode.IN) String clear_db,
        @WebParam(name = "count", mode = WebParam.Mode.IN) int count,
        @WebParam(name = "srnList", mode = WebParam.Mode.IN) srnDetailsBean[] srnList,
        @WebParam(name = "status", mode = WebParam.Mode.IN) String status,
        @WebParam(name = "successflag", mode = WebParam.Mode.OUT) Holder<String> successFlag,
        @WebParam(name = "failedSrnList", mode = WebParam.Mode.OUT) Holder<ArrayList<String>> failedSrnList)
{
    boolean dataFlag = false; //to identify if data is being inserted
    ArrayList<String> failed_srn_list = new ArrayList<String>();
    Logger LOGGER = null;
    try
    {
        Handler fh = new FileHandler("/data/build/Service11.log");
        LOGGER = Logger.getLogger(Service10_SAPCall.class.getName());
        Logger.getLogger("LOGGER").addHandler(fh);
        LOGGER.info("Logger Name : "+LOGGER.getName());
        System.out.println("GetSrnDetails execution begins");
        System.out.println("Inside GetSrnDetails");
        LOGGER.info("Inside GetSrnDetails");

        Properties props = new Properties();
        FileInputStream fin = null;
        fin = new FileInputStream("/data/build/ENivesh/Properties/DB_connection.txt");
        props.load(fin);
        //DB connection details
        String connection_url=props.getProperty("DCURL");
        String uname=props.getProperty("DCUserId");
        String pwd=props.getProperty("DCPwd");
        fin.close();

        //Load Driver
        Class.forName("com.ibm.db2.jcc.DB2Driver");
        System.out.println("Driver Loaded");
        System.out.println("connection_url="+connection_url+"\nuname="+uname+"\npwd="+pwd);

        System.out.println("Inside getcount");

        connect = DriverManager.getConnection(connection_url,uname,pwd);
        connect.setAutoCommit(false);
        Statement stmt_insertCount = connect.createStatement();
        int insert_count_status = 0;
        int insert_data_status[] = null;

        //Inserting the received count and status to DB
        String insert_count = "insert into SRN_COUNT_SERVICE11(DSD_SRN_STATUS,SRN_COUNT) values ('"+status+"','"+count+"')";
        insert_count_status=stmt_insertCount.executeUpdate(insert_count);

        //Inserting data passed if any.Data is passed only for beyond time line statuses.
        if(status.equalsIgnoreCase("HIAB-BT") || status.equalsIgnoreCase("WIPG-BT") || status.equalsIgnoreCase("PTPR-BT")
            || status.equalsIgnoreCase("UPDH-BT") || status.equalsIgnoreCase("PPRE-BT") || status.equalsIgnoreCase("PDMD-BT")
            || status.equalsIgnoreCase("UPAO-BT") || status.equalsIgnoreCase("PQAO-BT") || status.equalsIgnoreCase("PQRO-BT")
            || status.equalsIgnoreCase("PAID-BT") || status.equalsIgnoreCase("PQDH-BT") || status.equalsIgnoreCase("UPDH-BT"))
        {
            if(srnList.length != 0)
            {
                Statement stmt_insertData = connect.createStatement();
                String insert_data = null;
                for(int i=0; i<srnList.length; i++)
                {
                    insert_data = "insert into SRN_DTLS_SERVICE11 values "
                            + "('"+srnList[i].getSrn()+"','"+srnList[i].getStatus()+"','"
                            +srnList[i].getUserId()+"','"+srnList[i].getMobileNumber()+"','"
                            +srnList[i].getCompanyEmailId()+"','"+srnList[i].getAddressType()+"','"+srnList[i].getAddress()+"','"
                            +srnList[i].getCityCode()+"','"+srnList[i].getStateCode()+"','"+srnList[i].getDistrictCode()+"','"+srnList[i].getCountry()+"','"
                            +srnList[i].getCompanyname()+"','"+srnList[i].getTelNo()+"','"+srnList[i].getRocCode()+"','"+srnList[i].getDate()+"')";
                    stmt_insertData.addBatch(insert_data);
                }
                insert_data_status = stmt_insertData.executeBatch();
                for(int j=0; j<insert_data_status.length; j++)
                {
                    if(!(insert_data_status[j]>0))
                        failed_srn_list.add(srnList[j].getSrn());
                }
                dataFlag = true; //setting to true as data was inserted
            }
        }
        connect.commit();
        if(insert_count_status > 0) {
            if(dataFlag) {  //If data is inserted, failed_srn_list is checked to see if any insertions failed.If no X is passed.
                if (failed_srn_list.size() == 0)    {
                    successFlag.value = "X";
                }
                else {
                    failedSrnList.value.addAll(failed_srn_list); //if there are failed insertions, the failed SRNs are passed back to SAP.
                }
            } //If dataFlag is not set, only insertion of count is considered to set successFlag.
            else {
                successFlag.value = "X";
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        LOGGER.severe(ex.getMessage());
    }
    finally {
        try {
            connect.close();
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.severe(e.getMessage());
        }
    }
}

}

WSDL

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sap="http://sapservice.me.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <sap:GetSrnDetails>

         <clear_db></clear_db>
         <count></count>

         <srnList>

            <srn></srn>

            <status></status>

            <date></date>

            <userId></userId>

            <mobileNumber></mobileNumber>

            <companyEmailId></companyEmailId>

            <addressType>Home</addressType>

            <address>home</address>

            <cityCode>cuty</cityCode>

            <stateCode>state</stateCode>

            <districtCode></districtCode>

            <country></country>

            <telNo></telNo>

            <companyname></companyname>

            <rocCode></rocCode>
         </srnList>

         <status></status>
      </sap:GetSrnDetails>
   </soapenv:Body>
</soapenv:Envelope>

SOAP error

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server</faultcode>
         <faultstring>org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.</faultstring>
         <detail/>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

Stack Trace

000000b9 AxisEngine    E org.apache.axis2.engine.AxisEngine receive org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.
                                 org.apache.axis2.AxisFault: org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.
    at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
    at org.apache.axis2.jaxws.server.JAXWSMessageReceiver.receive(JAXWSMessageReceiver.java:242)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:208)
    at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
    at com.ibm.ws.websvcs.transport.http.WASAxis2Servlet.doPost(WASAxis2Servlet.java:1583)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1032)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3761)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:976)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:459)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:526)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:312)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:283)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)
Caused by: javax.xml.ws.WebServiceException: org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.
    at org.apache.axis2.jaxws.ExceptionFactory.createWebServiceException(ExceptionFactory.java:175)
    at org.apache.axis2.jaxws.ExceptionFactory.makeWebServiceException(ExceptionFactory.java:70)
    at org.apache.axis2.jaxws.ExceptionFactory.makeWebServiceException(ExceptionFactory.java:128)
    at org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMethodMarshaller.marshalResponse(DocLitWrappedMethodMarshaller.java:511)
    at org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.createResponse(JavaBeanDispatcher.java:349)
    at org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.invoke(JavaBeanDispatcher.java:141)
    at org.apache.axis2.jaxws.server.EndpointController.invoke(EndpointController.java:111)
    at org.apache.axis2.jaxws.server.JAXWSMessageReceiver.receive(JAXWSMessageReceiver.java:161)
    ... 29 more
Caused by: org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The org.me.sapservice.jaxws.GetSrnDetailsResponse JAXB object does not have a successflag xml property.
    at org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperToolImpl.wrap(JAXBWrapperToolImpl.java:294)
    at org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMethodMarshaller.marshalResponse(DocLitWrappedMethodMarshaller.java:482)
    ... 33 more


来源: stackexchange

问:
Null propagation operator, out parameters and false compiler errors?
Let's assume I have a class that has a property of type Dictionary<string,string>, that may be null.

This compiles but the call to TryGetValue() could throw at a NullRef exception at runtime:

```<code>MyClass c = ...;
string val;
if(c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val);
}
</code>```

So I'm adding a null-propagating operator to guard against nulls, but this doesn't compile:

```<code>MyClass c = ...;
string val;
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // use of unassigned local variable

}
</code>```

Is there an actual use case where val will be uninitialized inside the if block, or can the compiler simply not infer this (and why) ?

Update: The cleanest (?) way to workaround^H^H^H^H^H fix this is:

```<code>MyClass c = ...;
string val = null; //POW! initialized.
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // no more compiler error

}
</code>```

答:
By initializing val to a erhm, value (e.g., String.Empty) the compiler is able to grok the intent for the null operators and behaves as expected (via LINQPad, natch):

```<code>void Main()
{
    MyClass c = new MyClass();
    string val = string.Empty;
    if (c.PossiblyNullDictionary?.TryGetValue("someKey", out val) ?? false)
    {

        Console.WriteLine(val);

    }
}
public class MyClass {
    public Dictionary<string, string> PossiblyNullDictionary;
}
// Define other methods and classes here
</code>```

Ed: by 'grok the intent' I meant that the compiler can't make important guarantees about the program's characteristics if it allows execution to leave the current scope with val uninitialized. When it evaluates the null operators, the method invocation.

The use case you ask for is this:
Say that instead of TryGetValue, we have bool SomeMethod(string s, out v). Let's say that when invoked, SomeMethod is naughty and simply has a body of return true;. The compiler treats method invocation bodies as opaque (since it may not always be in an assembly available/visible to the compiler), so it concludes that there's no way to prove that val is ever initialized.

ed:
In response to some comments, I wanted to update my answer to point out that this behavior isn't specific to the ?? or ?. C# language features; you can reproduce the same effect simply by using a ternary expression:

```<code>c.PossiblyNullDictionary == null ?
    false :
    c.PossiblyNullDictionary.TryGetValue("someKey", out val)
 //error: use of possibly uninitialized local variable
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's assume I have a class that has a property of type Dictionary<string,string>, that may be null.

This compiles but the call to TryGetValue() could throw at a NullRef exception at runtime:

MyClass c = ...;
string val;
if(c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val);
}

So I'm adding a null-propagating operator to guard against nulls, but this doesn't compile:

MyClass c = ...;
string val;
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // use of unassigned local variable

}

Is there an actual use case where val will be uninitialized inside the if block, or can the compiler simply not infer this (and why) ?

Update: The cleanest (?) way to workaround^H^H^H^H^H fix this is:

MyClass c = ...;
string val = null; //POW! initialized.
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {

    Console.WriteLine(val); // no more compiler error

}

Body:
By initializing val to a erhm, value (e.g., String.Empty) the compiler is able to grok the intent for the null operators and behaves as expected (via LINQPad, natch):

void Main()
{
    MyClass c = new MyClass();
    string val = string.Empty;
    if (c.PossiblyNullDictionary?.TryGetValue("someKey", out val) ?? false)
    {

        Console.WriteLine(val);

    }
}
public class MyClass {
    public Dictionary<string, string> PossiblyNullDictionary;
}
// Define other methods and classes here

Ed: by 'grok the intent' I meant that the compiler can't make important guarantees about the program's characteristics if it allows execution to leave the current scope with val uninitialized. When it evaluates the null operators, the method invocation.

The use case you ask for is this:
Say that instead of TryGetValue, we have bool SomeMethod(string s, out v). Let's say that when invoked, SomeMethod is naughty and simply has a body of return true;. The compiler treats method invocation bodies as opaque (since it may not always be in an assembly available/visible to the compiler), so it concludes that there's no way to prove that val is ever initialized.

ed:
In response to some comments, I wanted to update my answer to point out that this behavior isn't specific to the ?? or ?. C# language features; you can reproduce the same effect simply by using a ternary expression:

c.PossiblyNullDictionary == null ?
    false :
    c.PossiblyNullDictionary.TryGetValue("someKey", out val)
 //error: use of possibly uninitialized local variable


问:
C - Segmentation fault after freeing dynamically allocated array
I'm trying to create dynamically allocated array of clusters, where every cluster has its own dynamically allocated array of points.

```<code>typedef struct Point
{
    int ID; //each point has some ID and XY coordinates
    int X;
    int Y;
}Point;

typedef struct Cluster
{
    int size;      //how many points can cluster hold
    int count;     //how many points cluster actually holds
    Point *points; //dynamically allocated array of points
}Cluster;
</code>```

I am able to initialize clusters array and populate it with this function:

```<code>void fill_array(Cluster **arr, int how_many_clusters)
{
    *arr = (Cluster *)malloc(sizeof(Cluster) * how_many_clusters);

    for(int i = 0; i < how_many_clusters; i++)
    {
        Point point;
        point.ID = i;
        point.X = i * 2;
        point.Y = i * 3;
        (*arr)[i].size = 1;
        (*arr)[i].count = 1;
        (*arr)[i].points = (Point *)malloc(sizeof(Point));
        (*arr)[i].points[i] = point;
    }
}
</code>```

In main I want to create the array, fill it with function mentioned before and then free it.

```<code>int main ()
{
    Cluster *clusters;
    int clusters_count = 20;
    fill_array(&cluters, clusters_count);

    for(int i = clusters_count - 1; i >= 0; i--)
    {
        free(clusters[i].points); //crash point
        clusters[i].points = NULL;
    }
    free(clusters);

    return 0;
}
</code>```

When I compile and run this program, it crashes at second iteration of freeing with segmentation fault. I have spent last 2 days digging through the internet, but didn't find anything about what I'm doing wrong.
Can anyone point out where is the mistake I can't see?

答:
```<code>(*arr)[i].points[i] = point;
</code>```

This doesn't look right. It should be

```<code>(*arr)[i].points[0] = point;
</code>```

Body:
I'm trying to create dynamically allocated array of clusters, where every cluster has its own dynamically allocated array of points.

typedef struct Point
{
    int ID; //each point has some ID and XY coordinates
    int X;
    int Y;
}Point;

typedef struct Cluster
{
    int size;      //how many points can cluster hold
    int count;     //how many points cluster actually holds
    Point *points; //dynamically allocated array of points
}Cluster;

I am able to initialize clusters array and populate it with this function:

void fill_array(Cluster **arr, int how_many_clusters)
{
    *arr = (Cluster *)malloc(sizeof(Cluster) * how_many_clusters);

    for(int i = 0; i < how_many_clusters; i++)
    {
        Point point;
        point.ID = i;
        point.X = i * 2;
        point.Y = i * 3;
        (*arr)[i].size = 1;
        (*arr)[i].count = 1;
        (*arr)[i].points = (Point *)malloc(sizeof(Point));
        (*arr)[i].points[i] = point;
    }
}

In main I want to create the array, fill it with function mentioned before and then free it.

int main ()
{
    Cluster *clusters;
    int clusters_count = 20;
    fill_array(&cluters, clusters_count);

    for(int i = clusters_count - 1; i >= 0; i--)
    {
        free(clusters[i].points); //crash point
        clusters[i].points = NULL;
    }
    free(clusters);

    return 0;
}

When I compile and run this program, it crashes at second iteration of freeing with segmentation fault. I have spent last 2 days digging through the internet, but didn't find anything about what I'm doing wrong.
Can anyone point out where is the mistake I can't see?

Body:
(*arr)[i].points[i] = point;

This doesn't look right. It should be

(*arr)[i].points[0] = point;


问:
cURL Equivalent to xhrFields: {withCredentials: true}

Goal:

Log into processor's site using their API and store the success response into COOKIEs and SESSIONs on my site.

What almost works:

```<code>jQuery(document).ready(function($){
    $.ajax({
      type: 'POST',
      url: '{url-to-api-call}',
      xhrFields: {
        withCredentials: true
      },
      dataType: 'text',
      data: 'Email={email}&GuestSessionToken={token}&Password={pass}&Format=JSON&RememberMe=true',
      processData: false,
      crossDomain: true,
      success: function (res) { console.log('success'); },
      error: function (jqXHR, textStatus, ex) {
          console.log('error');
      }
    });
});
</code>```

Why it doesn't work:
I'm unable to store the response to COOKIEs and SESSIONs.

What I would like to work:

```<code>$url = {url-to-api};
$curl = curl_init();
$curl_post_data = array(
    'Email' => $fields['user_email'],
    'GuestSessionToken' => $_COOKIE['SessionToken'],
    'Password' => $fields['user_pass'],
    'Format' => "JSON",
    'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);

$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);

if ($content_array['StatusCode'] == 'OK') {
    $fields['UserId'] = $content_array['Data']['UserId'];
    $fields['SessionID'] = $content_array['Data']['ID'];
    $fields['SessionToken'] = $content_array['Data']['Token'];
    return true;
} else {
    $errors->add( 'error', 'Unable to sign in.' );
    return false;
}
</code>```

Why it doesn't work:
This will return a success response that I can use to set the COOKIEs and SESSIONs, but it will not log the user into the processor's site.

Why I think it doesn't work:
The ajax call wouldn't sign the user in until I added the xhrFields part. I think if I could find a cURL equivalent for the xhrFields part, I would be all set.

Thanks in advance!

My duct tape fix.

```<code><?php

// If signin form is submitted and signin cURL was successful.
echo (isset($fields['signin_script'])) ? $fields['signin_script'] : "";

function processor_signin(&$fields, &$errors) {

    $url = '{url-to-api-call}';
    $curl = curl_init();
    $curl_post_data = array(
        'Email' => $fields['user_email'],
        'GuestSessionToken' => $_COOKIE['SessionToken'],
        'Password' => $fields['user_pass'],
        'Format' => "JSON",
        'RememberMe' => "true"
    );
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
    curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
    curl_setopt($curl, CURLOPT_TIMEOUT, 90);

    $content = curl_exec($curl);
    curl_close($curl);
    $content_array = json_decode($content, true);

    if ($content_array['StatusCode'] == 'OK') {
        $fields['UserId'] = $content_array['Data']['UserId'];
        $fields['SessionID'] = $content_array['Data']['ID'];
        $fields['SessionID'] = $content_array['Data']['ID'];
        $fields['SessionToken'] = $content_array['Data']['Token'];

        // Duct tape fix
        $fields['signin_script'] = "
        <script>
            jQuery(document).ready(function($){
                $.ajax({
                  type: 'POST',
                  url: '{url-to-api-call}',
                  xhrFields: {
                    withCredentials: true
                  },
                  dataType: 'text',
                  data: '
                    Email=".$fields['user_email']."
                    &GuestSessionToken=".$_COOKIE['SessionToken']."
                    &Password=".$fields['user_pass']."
                    &Format=JSON
                    &RememberMe=true',
                  processData: false,
                  crossDomain: true,
                  success: function (res) { console.log('signin success'); },
                  error: function (jqXHR, textStatus, ex) {
                      console.log('signin error');
                  }
                });
            });
        </script>
        ";

        return true;
    } else {
        $errors->add( 'error', 'Unable to sign in.' );
        return false;
    }

}
?>
</code>```

答:
Maybe you are logged in but you are not storing the cookies.

So you need to parse the headers and in the end store all cookies. In proceeding requests you need to send back all cookies that you retrieved before.

Here is an example how to retrieve the cookies and other headers from the server:

```<code>public function sendRequest(HttpRequest $request)
{
    ...
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getHeaders());
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, [$this, 'fetchHeader']);
    ...
    $content = curl_exec($ch);
    ...
}

/**
 * @param resource $ch     - curl handle
 * @param string   $header
 *
 * @return int
 */
private function fetchHeader($ch, $header)
{
    $headerParts = explode(': ', $header, 2);
    if (2 === count($headerParts)) {
        $headerName = strtolower($headerParts[0]);
        if ('set-cookie' === $headerName) {
            $this->responseHeaders[$headerName][] = trim($headerParts[1]);
            return strlen($header);
        }
        $this->responseHeaders[$headerName] = trim($headerParts[1]);
    }
    return strlen($header);
}
</code>```

Body:
Goal:

Log into processor's site using their API and store the success response into COOKIEs and SESSIONs on my site.

What almost works:

jQuery(document).ready(function($){
    $.ajax({
      type: 'POST',
      url: '{url-to-api-call}',
      xhrFields: {
        withCredentials: true
      },
      dataType: 'text',
      data: 'Email={email}&GuestSessionToken={token}&Password={pass}&Format=JSON&RememberMe=true',
      processData: false,
      crossDomain: true,
      success: function (res) { console.log('success'); },
      error: function (jqXHR, textStatus, ex) {
          console.log('error');
      }
    });
});

Why it doesn't work:
I'm unable to store the response to COOKIEs and SESSIONs.

What I would like to work:

$url = {url-to-api};
$curl = curl_init();
$curl_post_data = array(
    'Email' => $fields['user_email'],
    'GuestSessionToken' => $_COOKIE['SessionToken'],
    'Password' => $fields['user_pass'],
    'Format' => "JSON",
    'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);

$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);

if ($content_array['StatusCode'] == 'OK') {
    $fields['UserId'] = $content_array['Data']['UserId'];
    $fields['SessionID'] = $content_array['Data']['ID'];
    $fields['SessionToken'] = $content_array['Data']['Token'];
    return true;
} else {
    $errors->add( 'error', 'Unable to sign in.' );
    return false;
}

Why it doesn't work:
This will return a success response that I can use to set the COOKIEs and SESSIONs, but it will not log the user into the processor's site.

Why I think it doesn't work:
The ajax call wouldn't sign the user in until I added the xhrFields part. I think if I could find a cURL equivalent for the xhrFields part, I would be all set.

Thanks in advance!

My duct tape fix.

<?php

// If signin form is submitted and signin cURL was successful.
echo (isset($fields['signin_script'])) ? $fields['signin_script'] : "";

function processor_signin(&$fields, &$errors) {

    $url = '{url-to-api-call}';
    $curl = curl_init();
    $curl_post_data = array(
        'Email' => $fields['user_email'],
        'GuestSessionToken' => $_COOKIE['SessionToken'],
        'Password' => $fields['user_pass'],
        'Format' => "JSON",
        'RememberMe' => "true"
    );
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
    curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
    curl_setopt($curl, CURLOPT_TIMEOUT, 90);

    $content = curl_exec($curl);
    curl_close($curl);
    $content_array = json_decode($content, true);

    if ($content_array['StatusCode'] == 'OK') {
        $fields['UserId'] = $content_array['Data']['UserId'];
        $fields['SessionID'] = $content_array['Data']['ID'];
        $fields['SessionID'] = $content_array['Data']['ID'];
        $fields['SessionToken'] = $content_array['Data']['Token'];

        // Duct tape fix
        $fields['signin_script'] = "

        ";

        return true;
    } else {
        $errors->add( 'error', 'Unable to sign in.' );
        return false;
    }

}
?>

Body:
Maybe you are logged in but you are not storing the cookies.

So you need to parse the headers and in the end store all cookies. In proceeding requests you need to send back all cookies that you retrieved before.

Here is an example how to retrieve the cookies and other headers from the server:

public function sendRequest(HttpRequest $request)
{
    ...
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getHeaders());
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, [$this, 'fetchHeader']);
    ...
    $content = curl_exec($ch);
    ...
}

/**
 * @param resource $ch     - curl handle
 * @param string   $header
 *
 * @return int
 */
private function fetchHeader($ch, $header)
{
    $headerParts = explode(': ', $header, 2);
    if (2 === count($headerParts)) {
        $headerName = strtolower($headerParts[0]);
        if ('set-cookie' === $headerName) {
            $this->responseHeaders[$headerName][] = trim($headerParts[1]);
            return strlen($header);
        }
        $this->responseHeaders[$headerName] = trim($headerParts[1]);
    }
    return strlen($header);
}


问:
Create an array of integers property in Objective-C
I'm having troubles creating a property of an array of integers in Objective-C.
I'm not sure whether this is even possible to do in Obj-C so I'm hoping someone can help me in finding out either how to do it correctly or provide an alternative solution.

myclass.h

```<code>@interface myClass : NSObject {

@private int doubleDigits[10];
}

@property int doubleDigits;
@end
</code>```

myclass.m

```<code>@implementation myClass

    @synthesize doubleDigits;
    -(id) init {

        self = [super init];

        int doubleDigits[10] = {1,2,3,4,5,6,7,8,9,10};

        return self;
    }

    @end
</code>```

When I build and run, I get the following error:

error: type of property 'doubleDigits'
  does not match type of ivar
  'doubleDigits'

答:
I'm just speculating:

I think that the variable defined in the ivars allocates the space right in the object. This prevents you from creating accessors because you can't give an array by value to a function but only through a pointer. Therefore you have to use a pointer in the ivars:

```<code>int *doubleDigits;
</code>```

And then allocate the space for it in the init-method:

```<code>@synthesize doubleDigits;

- (id)init {
    if (self = [super init]) {
        doubleDigits = malloc(sizeof(int) * 10);
        /*
         * This works, but is dangerous (forbidden) because bufferDoubleDigits
         * gets deleted at the end of -(id)init because it's on the stack:
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * [self setDoubleDigits:bufferDoubleDigits];
         *
         * If you want to be on the safe side use memcpy() (needs #include <string.h>)
         * doubleDigits = malloc(sizeof(int) * 10);
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * memcpy(doubleDigits, bufferDoubleDigits, sizeof(int) * 10);
         */
    }
    return self;
}

- (void)dealloc {
    free(doubleDigits);
    [super dealloc];
}
</code>```

In this case the interface looks like this:

```<code>@interface MyClass : NSObject {
    int *doubleDigits;
}
@property int *doubleDigits;
</code>```

Edit:

I'm really unsure wether it's allowed to do this, are those values really on the stack or are they stored somewhere else? They are probably stored on the stack and therefore not safe to use in this context. (See the question on initializer lists)

```<code>int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
[self setDoubleDigits:bufferDoubleDigits];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having troubles creating a property of an array of integers in Objective-C.
I'm not sure whether this is even possible to do in Obj-C so I'm hoping someone can help me in finding out either how to do it correctly or provide an alternative solution.

myclass.h

@interface myClass : NSObject {

@private int doubleDigits[10];
}

@property int doubleDigits;
@end

myclass.m

@implementation myClass

    @synthesize doubleDigits;
    -(id) init {

        self = [super init];

        int doubleDigits[10] = {1,2,3,4,5,6,7,8,9,10};

        return self;
    }

    @end

When I build and run, I get the following error:

error: type of property 'doubleDigits'
  does not match type of ivar
  'doubleDigits'

Body:
I'm just speculating:

I think that the variable defined in the ivars allocates the space right in the object. This prevents you from creating accessors because you can't give an array by value to a function but only through a pointer. Therefore you have to use a pointer in the ivars:

int *doubleDigits;

And then allocate the space for it in the init-method:

@synthesize doubleDigits;

- (id)init {
    if (self = [super init]) {
        doubleDigits = malloc(sizeof(int) * 10);
        /*
         * This works, but is dangerous (forbidden) because bufferDoubleDigits
         * gets deleted at the end of -(id)init because it's on the stack:
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * [self setDoubleDigits:bufferDoubleDigits];
         *
         * If you want to be on the safe side use memcpy() (needs #include <string.h>)
         * doubleDigits = malloc(sizeof(int) * 10);
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * memcpy(doubleDigits, bufferDoubleDigits, sizeof(int) * 10);
         */
    }
    return self;
}

- (void)dealloc {
    free(doubleDigits);
    [super dealloc];
}

In this case the interface looks like this:

@interface MyClass : NSObject {
    int *doubleDigits;
}
@property int *doubleDigits;

Edit:

I'm really unsure wether it's allowed to do this, are those values really on the stack or are they stored somewhere else? They are probably stored on the stack and therefore not safe to use in this context. (See the question on initializer lists)

int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
[self setDoubleDigits:bufferDoubleDigits];

OwnerDisplayName: gs

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: gs


问:
What's the benefit of postfixing arrays with "List" for variables?
I have seen numerous developers postfixing variable names with a "List" when it's an array. What's the point of this and would you encourage this style? For example:

```<code>// Java
String[] fileList;
String file;

// PHP
$fileList = array();
$file = '';
</code>```

The idea applies to any language with support for arrays.

答:
The idea? Readability - you can tell the variable is a collection in one glance. This can be achieved with pluralizing the variable name (ie. files).

If the fact that the data type is a list is significant (assuming several different collection types), then using that postfix is the right thing to do (as opposed to simply being a collection).

I personally tend to pluralize variable names, using a list postfix only if it adds information or can't be inferred from the name otherwise (say a list of lists).

Body:
I have seen numerous developers postfixing variable names with a "List" when it's an array. What's the point of this and would you encourage this style? For example:

// Java
String[] fileList;
String file;

// PHP
$fileList = array();
$file = '';

The idea applies to any language with support for arrays.


问:
How do I get SSL certificate from ACM, using android aws sdk?
I am trying to retrieve SSL certificate from ACM, but unable to. I tried using the old aws-java-sdk-acm but it has a http client which is no more usable. Hence I am not able to fetch the certificate from the AWS. Please help me out as I dont see any option / acm methods in the latest aws sdk.</p>

答:
What do you mean by "retrieve SSL certificate"? Do you want to pull the certificate with the private key? If so, please refer to John Hanley's answer.

If you just want the public portion of the certificate (what is served from a webserver, etc.), you can call ACM's GetCertificate to pull the certificate with chain.


问:
File upload with Meteor + React failing silently
Im using React and Meteor. I need to allow users to upload profile images.

Ive installed these packages:

```<code>cfs:standard-packages
cfs:filesystem
</code>```

Ive defined my collection in images.js:

```<code>export const Images = new FS.Collection('images', {
  stores: [new FS.Store.FileSystem('images', { path: '~/uploads' })],
});
</code>```

This file isn't imported into the server JavaScript.

It is imported into my React component (code below). My console.log does log the file and doesn't show me any errors. I also dont see any errors in Meteor's terminal.

```<code>import { Images } from '../../../api/images';

  const imgFormSubmit = e => {
    e.preventDefault();

    const file = e.target.profile.files[0];
    console.log(file);

    Images.insert(file, function(err, fileObj) {
      //If !err, we have inserted new doc with ID fileObj._id, and
      //kicked off the data upload using HTTP
    });
  };
</code>```

However when I look at MongoDB there isnt any table called images so nothing has been saved. I also don't have any file or uploads folder added to my filesystem.

I have autopublish and insecure packages enabled.

答: cfs:standard-packages, cfs:filesystem are deprecated use MeteorFiles instead. There is a section in there doc for react check it out. </p>

Body:
Im using React and Meteor. I need to allow users to upload profile images.

Ive installed these packages:

cfs:standard-packages
cfs:filesystem

Ive defined my collection in images.js:

export const Images = new FS.Collection('images', {
  stores: [new FS.Store.FileSystem('images', { path: '~/uploads' })],
});

This file isn't imported into the server JavaScript.

It is imported into my React component (code below). My console.log does log the file and doesn't show me any errors. I also dont see any errors in Meteor's terminal.

import { Images } from '../../../api/images';

  const imgFormSubmit = e => {
    e.preventDefault();

    const file = e.target.profile.files[0];
    console.log(file);

    Images.insert(file, function(err, fileObj) {
      //If !err, we have inserted new doc with ID fileObj._id, and
      //kicked off the data upload using HTTP
    });
  };

However when I look at MongoDB there isnt any table called images so nothing has been saved. I also don't have any file or uploads folder added to my filesystem.

I have autopublish and insecure packages enabled.


问:
Compare end punctuation in columns A and B in Excel (VBA?)
I'm trying to catch and resolve instances in Excel where the end punctuation (in my case an empty line) in cells in column B doesn't match the end punctuation in cells in column A. For background, column A contains English text and column B contains translated version of the very same content. The problem is - in some cases the source text has empty/blank lines at the end of text in cells, while some translated text doesn't and I need to find and fix those instances.

So, I'm trying to:

1) Compare the last line of each cell in column A to the adjacent cell in the same row in column B.

2) If the cell in column A has a blank line at the end and corresponding cell in column B doesn't, add such blank line to the end of cell in column B.

Example:

```<code>         **Column A**    **Column B**
Row 1       Text X          Text Y
            \n
Row 2       Text X          Text Y
Row 3       Text X          Text Y
            \n
Row 4       Text X          Text Y
            \n              \n
</code>```

So, in the example above, I need to flag cells B1 and B3 because they don't have a line feed (\n) at the end, similar to their counterparts in cells A1 and A3.

Thank you in advance!

答:
Depending on whether the newline spaces are inside of the cell or lead onto the next cell I would do one of two things:

If the newline is inside of the cell, like: CELL A1 = "Text X \n",
A simple solution to this could be to insert an extra column and use the =TRIM() formula. The TRIM() formula gets rid of leading and trailing spaces, you can see the Excel documentation here

If the newline is on the next cell, like CELL A1 = "Text X", CELL A2 = "\n",
Then you could just use the LEN() formula on the cell, and filter by "0". You can see the Excel documentation for LEN() here.

Body:
I'm trying to catch and resolve instances in Excel where the end punctuation (in my case an empty line) in cells in column B doesn't match the end punctuation in cells in column A. For background, column A contains English text and column B contains translated version of the very same content. The problem is - in some cases the source text has empty/blank lines at the end of text in cells, while some translated text doesn't and I need to find and fix those instances.

So, I'm trying to:

1) Compare the last line of each cell in column A to the adjacent cell in the same row in column B.

2) If the cell in column A has a blank line at the end and corresponding cell in column B doesn't, add such blank line to the end of cell in column B.

Example:

         **Column A**    **Column B**
Row 1       Text X          Text Y
            \n
Row 2       Text X          Text Y
Row 3       Text X          Text Y
            \n
Row 4       Text X          Text Y
            \n              \n

So, in the example above, I need to flag cells B1 and B3 because they don't have a line feed (\n) at the end, similar to their counterparts in cells A1 and A3.

Thank you in advance!


问:
Using a static class as an input parameter on another class
I have no idea if this is possible but it feels like it should be from using C# up to this point.

I want to have a bunch of static classes that contain 'set values' for users of the library to send into another class as parameter.

So this is where I was headed but I can't figure it out.  This below is just an example of what I was thinking so don't try and work out 'why' :-)

First - The Class that will be called

```<code>public class myClass
    {
        public bool isError { private set; get; }

        public DataTable output { private set; get; }

        public String filename { set; private get; }

        public settingModule settings { set; private get; }

        public static void execute()
        {

            //Call Private 'getTheData'
            //set isError accordingly
            //Load output

        }

        private static DataTable getTheData()
        {
            //Open and read file for 'fileName'

            //Use settings.startingRow
            //Use settings.fileType
            //User settings.skipEmpty

            //Do some stuff

            return Datatable from workings

        }

    }
</code>```

Second - The Class I want to user to pass

```<code>public static class settingMobule
    {
        public static class fileTypeA
        {
            public static int startingRow = 1;
            public static String fileType = "txt";
            public static bool skipEmpty = true;
        }

        public static class fileTypeB
        {
            public static int startingRow = 10;
            public static String fileType = "csv";
            public static bool skipEmpty = false;
        }

        public static class fileTypeC
        {
            public static int startingRow = 3;
            public static String fileType = "hex";
            public static bool skipEmpty = true;
        }

    }
</code>```

Lastly the way I want to be able to call it

```<code>myClass test = new myClass();

test.filename = "c:\\temp\\test.txt;

test.settings = settingModule.fileTypeA;

test.execute();

if(test.isError == false

{
DataTable myTable = test.output;
test.dispose()
}
</code>```

Thanks in advance... and yes, "your nuts there is a much better way" is a perfectly valid answer :-)

I would also LOVE to know how to add a .dispose() to my code, it's not something i have got to yet but while I am here... :-D

答:
No. This is not possible. It is not possible because of 2 reasons:

Static classes cannot be passed around.

The receiver cannot know that these classes are supposed to contain the same set of settings and has no way to access them.

Choose another approach where there is only one non-static file type class used to create several setting objects: (C# 6.0)

```<code>public class FileType
{
    public FileType(int startingRow, string extension, bool skipEmpty)
    {
        this.StartingRow = startingRow;
        this.Extension = extension;  // 'FileType': Member names cannot be the same as their
                                     // enclosing type.
        this.SkipEmpty = skipEmpty;
    }

    public int StartingRow { get; }
    public string Extension { get; }
    public bool SkipEmpty { get; }
}
</code>```

The static settings class can now present several setting objects of the same type that can be passed around.

```<code>public static class SettingModule
{
    public static FileType TxtFileType { get; } = new FileType(1, "txt", true);
    public static FileType CsvFileType { get; } = new FileType(10, "csv", false);
    public static FileType HexFileType { get; } = new FileType(3, "hex", true);
}
</code>```

Now, the test class could be written as:

```<code>public class MyTestClass
{
    private FileType fileType;
    private string filename;

    public MyTestClass(FileType fileType, string filename)
    {
        this.fileType = fileType;
        this.filename = filename;
    }

    public void Execute()
    {
        Console.WriteLine(
            $"Extension = {fileType.Extension}, starting row = {fileType.StartingRow}");
    }
}
</code>```

And you can perform the test like this

```<code>var test = new MyTestClass(SettingModule.TxtFileType, @"c:\temp\test.txt");
test.Execute();
</code>```

Non-static classes are a kind of template from which numerous objects can be created. Unlike static classes, such classes are types that can be used to declare variables, method parameters, properties and more.

Body:
I have no idea if this is possible but it feels like it should be from using C# up to this point.

I want to have a bunch of static classes that contain 'set values' for users of the library to send into another class as parameter.

So this is where I was headed but I can't figure it out.  This below is just an example of what I was thinking so don't try and work out 'why' :-)

First - The Class that will be called

public class myClass
    {
        public bool isError { private set; get; }

        public DataTable output { private set; get; }

        public String filename { set; private get; }

        public settingModule settings { set; private get; }

        public static void execute()
        {

            //Call Private 'getTheData'
            //set isError accordingly
            //Load output

        }

        private static DataTable getTheData()
        {
            //Open and read file for 'fileName'

            //Use settings.startingRow
            //Use settings.fileType
            //User settings.skipEmpty

            //Do some stuff

            return Datatable from workings

        }

    }

Second - The Class I want to user to pass

public static class settingMobule
    {
        public static class fileTypeA
        {
            public static int startingRow = 1;
            public static String fileType = "txt";
            public static bool skipEmpty = true;
        }

        public static class fileTypeB
        {
            public static int startingRow = 10;
            public static String fileType = "csv";
            public static bool skipEmpty = false;
        }

        public static class fileTypeC
        {
            public static int startingRow = 3;
            public static String fileType = "hex";
            public static bool skipEmpty = true;
        }

    }

Lastly the way I want to be able to call it

myClass test = new myClass();

test.filename = "c:\\temp\\test.txt;

test.settings = settingModule.fileTypeA;

test.execute();

if(test.isError == false

{
DataTable myTable = test.output;
test.dispose()
}

Thanks in advance... and yes, "your nuts there is a much better way" is a perfectly valid answer :-)

I would also LOVE to know how to add a .dispose() to my code, it's not something i have got to yet but while I am here... :-D

Body:
No. This is not possible. It is not possible because of 2 reasons:

Static classes cannot be passed around.

The receiver cannot know that these classes are supposed to contain the same set of settings and has no way to access them.

Choose another approach where there is only one non-static file type class used to create several setting objects: (C# 6.0)

public class FileType
{
    public FileType(int startingRow, string extension, bool skipEmpty)
    {
        this.StartingRow = startingRow;
        this.Extension = extension;  // 'FileType': Member names cannot be the same as their
                                     // enclosing type.
        this.SkipEmpty = skipEmpty;
    }

    public int StartingRow { get; }
    public string Extension { get; }
    public bool SkipEmpty { get; }
}

The static settings class can now present several setting objects of the same type that can be passed around.

public static class SettingModule
{
    public static FileType TxtFileType { get; } = new FileType(1, "txt", true);
    public static FileType CsvFileType { get; } = new FileType(10, "csv", false);
    public static FileType HexFileType { get; } = new FileType(3, "hex", true);
}

Now, the test class could be written as:

public class MyTestClass
{
    private FileType fileType;
    private string filename;

    public MyTestClass(FileType fileType, string filename)
    {
        this.fileType = fileType;
        this.filename = filename;
    }

    public void Execute()
    {
        Console.WriteLine(
            $"Extension = {fileType.Extension}, starting row = {fileType.StartingRow}");
    }
}

And you can perform the test like this

var test = new MyTestClass(SettingModule.TxtFileType, @"c:\temp\test.txt");
test.Execute();

Non-static classes are a kind of template from which numerous objects can be created. Unlike static classes, such classes are types that can be used to declare variables, method parameters, properties and more.


问:
Android App crashes on older devices
My app works perfectly on my phone. On some older devices it crashes though:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blub.bla/com.blub.bla.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class ImageButton
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
...
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class ImageButton
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
    at
...
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_google_plus_icon.xml from drawable resource ID #0x7f0700ab
    at android.content.res.Resources.loadDrawableForCookie(Resources.java:2872)
...
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: invalid color state list tag gradient
    at android.content.res.ColorStateList.createFromXmlInner(ColorStateList.java:217)
    at
...
</code>```

I checked other posts and most of the time it had something to do with gradle, and I can say that i have vectorDrawables.useSupportLibrary = true set.

Gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 27

    repositories {
        mavenCentral()
    }
    defaultConfig {
        applicationId "com.blub.bla"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 19
        targetSdkVersion 27

        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    android {
        lintOptions {
            disable 'RestrictedApi'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.facebook.android:facebook-login:[4,5)'
    implementation 'com.facebook.android:facebook-share:[4,5)'
    implementation 'com.android.support:appcompat-v7:27.0.1'
    implementation 'com.android.support:design:27.0.1'
    implementation 'com.android.support:support-v4:27.0.1'

    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.squareup.okhttp:okhttp:2.4.0'
    implementation 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
    implementation 'com.google.android.gms:play-services-location:10.+'
    implementation 'com.google.android.gms:play-services-places:10.+'
    implementation 'com.google.maps.android:android-maps-utils:0.4+'

    implementation 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
    testImplementation 'junit:junit:4.12'
}
</code>```

Edit:
activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/activity_main_drawer">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:paddingBottom="10dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                >
                <com.facebook.share.widget.ShareButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:id="@+id/fb_share_button"/>
                <ImageButton
                    android:id="@+id/sm_twitter"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_twitter_bird_logo"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
                    />
                <ImageButton
                    android:id="@+id/sm_facebook"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_f_icon_color"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_toLeftOf="@id/sm_twitter"
                    />
                <ImageButton
                    android:id="@+id/sm_gplus"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_google_plus_icon"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_toLeftOf="@id/sm_facebook"
                    />
            </RelativeLayout >
        </RelativeLayout>
    </android.support.design.widget.NavigationView>>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_filter"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="175dp"
            android:orientation="horizontal">
            <include
                layout="@layout/filter_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />
        </RelativeLayout>
    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
</code>```

Does anyone know how to fix that? :(

答: That happens when you try to show an SVG in an Android version under 21, you can use AppCompatImageButton instead of ImageButton or AppCompatImageView with app: srcCompat</p>

Title: Android App crashes on older devices

Body:
My app works perfectly on my phone. On some older devices it crashes though:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blub.bla/com.blub.bla.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class ImageButton
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
...
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class ImageButton
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
    at
...
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_google_plus_icon.xml from drawable resource ID #0x7f0700ab
    at android.content.res.Resources.loadDrawableForCookie(Resources.java:2872)
...
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: invalid color state list tag gradient
    at android.content.res.ColorStateList.createFromXmlInner(ColorStateList.java:217)
    at
...

I checked other posts and most of the time it had something to do with gradle, and I can say that i have vectorDrawables.useSupportLibrary = true set.

Gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27

    repositories {
        mavenCentral()
    }
    defaultConfig {
        applicationId "com.blub.bla"
        vectorDrawables.useSupportLibrary = true
        minSdkVersion 19
        targetSdkVersion 27

        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    android {
        lintOptions {
            disable 'RestrictedApi'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.facebook.android:facebook-login:[4,5)'
    implementation 'com.facebook.android:facebook-share:[4,5)'
    implementation 'com.android.support:appcompat-v7:27.0.1'
    implementation 'com.android.support:design:27.0.1'
    implementation 'com.android.support:support-v4:27.0.1'

    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.squareup.okhttp:okhttp:2.4.0'
    implementation 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
    implementation 'com.google.android.gms:play-services-location:10.+'
    implementation 'com.google.android.gms:play-services-places:10.+'
    implementation 'com.google.maps.android:android-maps-utils:0.4+'

    implementation 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
    testImplementation 'junit:junit:4.12'
}

Edit:
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/activity_main_drawer">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:paddingBottom="10dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                >
                <com.facebook.share.widget.ShareButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:id="@+id/fb_share_button"/>
                <ImageButton
                    android:id="@+id/sm_twitter"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_twitter_bird_logo"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
                    />
                <ImageButton
                    android:id="@+id/sm_facebook"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_f_icon_color"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_toLeftOf="@id/sm_twitter"
                    />
                <ImageButton
                    android:id="@+id/sm_gplus"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_google_plus_icon"
                    android:background="@color/transparent"
                    android:layout_alignParentBottom="true"
                    android:layout_toLeftOf="@id/sm_facebook"
                    />
            </RelativeLayout >
        </RelativeLayout>
    </android.support.design.widget.NavigationView>>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@drawable/bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_filter"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="175dp"
            android:orientation="horizontal">
            <include
                layout="@layout/filter_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />
        </RelativeLayout>
    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

Does anyone know how to fix that? :(


问:
shared_mutex C++11 implementation
I have found the answer from HowardHinnant in this thread.
C++11 equivalent to boost shared_mutex

Unfortunately it seems to make use of the following macro which the Microsoft compiler (VS2015 x64) does not seem to support and the code needs to be C++11 and cross-platform.

```<code>_LIBCPP_BEGIN_NAMESPACE_STD
_LIBCPP_END_NAMESPACE_STD
</code>```

I have tried to change it to just

```<code>namespace std{
...
}
</code>```

Then the compiler complains with the following message.

Severity  Code    Description Project File    Line    Column  Source  Suppression
  State Tool Error  C2244   'std::unique_lock<_Mutex>::unique_lock': unable
  to match function definition to an existing
  declaration   shared_mutex_test   c:\documents\visual studio
  2015\projects\shared_mutex_test\shared_mutex.hpp  1217    1   Build

Question, how to solve this. I need shared_mutex / shared_lock functionality and I have to be C++11 compliant. We have decided not to bring in a bigger library like Boost, hence if I could get HowardHinnant's implementation to work cross-platform it would be the optimal solution.

Many thanks.

Ps.
I have not yet got a reputation high enough to comment on closed questions, hence I was forced to open up this new thread. Feel free to move it into the other thread.

答:
Solved by just removing all code that failed. It seems it interfered with the available c++11 implementation of unique_lock. Since I can use C++11 I did not need that part of the code.

To fully solve it the complete unique_lock class probably needs to be implemented.

Title: shared_mutex C++11 implementation

Body:
I have found the answer from HowardHinnant in this thread.
C++11 equivalent to boost shared_mutex

Unfortunately it seems to make use of the following macro which the Microsoft compiler (VS2015 x64) does not seem to support and the code needs to be C++11 and cross-platform.

_LIBCPP_BEGIN_NAMESPACE_STD
_LIBCPP_END_NAMESPACE_STD

I have tried to change it to just

namespace std{
...
}

Then the compiler complains with the following message.

Severity  Code    Description Project File    Line    Column  Source  Suppression
  State Tool Error  C2244   'std::unique_lock<_Mutex>::unique_lock': unable
  to match function definition to an existing
  declaration   shared_mutex_test   c:\documents\visual studio
  2015\projects\shared_mutex_test\shared_mutex.hpp  1217    1   Build

Question, how to solve this. I need shared_mutex / shared_lock functionality and I have to be C++11 compliant. We have decided not to bring in a bigger library like Boost, hence if I could get HowardHinnant's implementation to work cross-platform it would be the optimal solution.

Many thanks.

Ps.
I have not yet got a reputation high enough to comment on closed questions, hence I was forced to open up this new thread. Feel free to move it into the other thread.


答:
The following bit:

```<code>    (*arr)[i].points = (Point *)malloc(sizeof(Point));
    (*arr)[i].points[i] = point;
</code>```

does not allocate the correct amount of memory. i will be some number greater than zero, but you've only allocated space for one Point. You're smashing your heap and a crash will follow.

Title: C - Segmentation fault after freeing dynamically allocated array

Body:
The following bit:

    (*arr)[i].points = (Point *)malloc(sizeof(Point));
    (*arr)[i].points[i] = point;

does not allocate the correct amount of memory. i will be some number greater than zero, but you've only allocated space for one Point. You're smashing your heap and a crash will follow.


问:
How to listen messageSent event in laravel 5.5
Hi I am a beginner for events and listeners in laravel. So please explain me how to achieve this :

Aim :

Send an email to user. And know whether email is sent or not.

My Understanding :

Laravel has in-built event Illuminate\Mail\Events\MessageSent to fire after email is sent and I have to write a listener to listen the event.

What I did :

To send email :

```<code>Mail::to($receiverAddress)->send(new SendNewUserPassword($content));
</code>```

This is working fine. Able to send email to user successfully.

To listen messageSent event, I created this listener :

```<code><?php

namespace App\Listeners;

use Illuminate\Mail\Events\MessageSent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class LogSentMessage
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  MessageSent  $event
     * @return void
     */
    public function handle(MessageSent $event)
    {
        return $event->message;
    }
}
</code>```

To Register Event :

```<code>protected $listen = [
    'App\Events\Event' => [
        'App\Listeners\EventListener',
    ],

    'Illuminate\Mail\Events\MessageSent' => [
        'App\Listeners\LogSentMessage',
    ],
];
</code>```

In Controller :

```<code>event(new MessageSent())
</code>```

Please guide me how to return the message handled in Listener from controller. If my above approach is wrong explain me how to achieve it. This I am using for an api, so if sending mail is success/fail I want to know.

答:
In your EventServiceProvider add your event and listener

```<code>protected $listen = [
       'Illuminate\Notifications\Events\NotificationSent' => [
       'App\Listeners\YourListenerClass',
    ],
];
</code>```

and in YourListnerClass

```<code>public function handle(NotificationSent $event)
{

 //access your $event data here
 //which includes notification details too

}
</code>```

Body:
Hi I am a beginner for events and listeners in laravel. So please explain me how to achieve this :

Aim :

Send an email to user. And know whether email is sent or not.

My Understanding :

Laravel has in-built event Illuminate\Mail\Events\MessageSent to fire after email is sent and I have to write a listener to listen the event.

What I did :

To send email :

Mail::to($receiverAddress)->send(new SendNewUserPassword($content));

This is working fine. Able to send email to user successfully.

To listen messageSent event, I created this listener :

<?php

namespace App\Listeners;

use Illuminate\Mail\Events\MessageSent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class LogSentMessage
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  MessageSent  $event
     * @return void
     */
    public function handle(MessageSent $event)
    {
        return $event->message;
    }
}

To Register Event :

protected $listen = [
    'App\Events\Event' => [
        'App\Listeners\EventListener',
    ],

    'Illuminate\Mail\Events\MessageSent' => [
        'App\Listeners\LogSentMessage',
    ],
];

In Controller :

event(new MessageSent())

Please guide me how to return the message handled in Listener from controller. If my above approach is wrong explain me how to achieve it. This I am using for an api, so if sending mail is success/fail I want to know.

Body:
In your EventServiceProvider add your event and listener

protected $listen = [
       'Illuminate\Notifications\Events\NotificationSent' => [
       'App\Listeners\YourListenerClass',
    ],
];

and in YourListnerClass

public function handle(NotificationSent $event)
{

 //access your $event data here
 //which includes notification details too

}


问:
Output all licenses of installed node.js libraries
Is there an option in npm (or other tool) to print all used licenses?
I have a project and I want to make sure I don't use a library which is under a license I can't use.

EDIT: Found out that many developers don't include the license in the package.json, so I had to find out manually using "npm docs package-name"

答:
Yarn has a command for this as well. yarn licenses list renders short output, yarn licenses generate-disclaimer renders all the actual license text to stdout (suitable for disclaimers, as the option would imply).

If you want to omit devDependencies:

```<code>NODE_ENV=production yarn licenses list
</code>```

For my purposes, the following command got me close enough:

```<code>yarn licenses list | grep License | \
grep -vE 'MIT|ISC|WTFPL|BSD|Apache|Unlicense|CC-BY|Public Domain'`
</code>```

Body:
Yarn has a command for this as well. yarn licenses list renders short output, yarn licenses generate-disclaimer renders all the actual license text to stdout (suitable for disclaimers, as the option would imply).

If you want to omit devDependencies:

NODE_ENV=production yarn licenses list

For my purposes, the following command got me close enough:

yarn licenses list | grep License | \
grep -vE 'MIT|ISC|WTFPL|BSD|Apache|Unlicense|CC-BY|Public Domain'`


问:
Prevent duplicate posts within foreach

Hello all, I'm currently working on a foreach loop that pulls images from a gallery from the backend of Wordpress. The gallery is working fine and as expected, however, I would like to prevent duplicate photos from appearing.

```<code><?php if () $query->have_posts() ):
  $thumbs = [];
?>
<?php
    foreach( $query->posts as $gallery ):
      $images = get_field('gallery_images', $gallery->ID);
      if( $images ):
        foreach( $images as $image ):
          $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
          $img_id[] = $image['ID'];
          $thumbs[] = $cropped_img;
?>
</code>```

Unrelated HTML to the Problem

```<code><?php endforeach; endif; endforeach; ?>
<?php foreach($thumbs as $thumbnail): ?>
  <div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
<?php endforeach; ?>
</code>```

Here is essentially what I'm trying to work out. I've thought to add two variables for the image ID so that they aren't duplicated in the first block of code. So that first if/foreach state looks like:

```<code><?php if( $images ):
  foreach( $images as $image ):
    $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
    $img_id[] = $image['ID'];
    $do_not_duplicate[] = $image['ID'];
    $thumbs[] = $cropped_img;
?>
</code>```

Followed by the followed foreach for the thumbnails

```<code><?php foreach($thumbs as $thumbnail): ?>
    <?php foreach($img_id as $img): ?>
      <?php if ($img == $do_not_duplicate) : ?>
      //do nothing
      <?php else : ?>
      <div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
      <?php endif; ?>
<?php endforeach; endforeach; ?>
</code>```

The problem I'm experiencing with this is I'm getting 22 images outputed 23 times because there are 22 images being pulled(with 1 duplicate). Essentially I'm trying to accomplish 22 images with no duplicates.

Any insight would be greatly appreciated, thank you in advance.

答:
You could check if the image id already exists in the $img_id array before adding it.

I modified your code below

```<code><?php if () $query->have_posts() ):
  $thumbs = [];
?>
<?php
    foreach( $query->posts as $gallery ):
      $images = get_field('gallery_images', $gallery->ID);
      if( $images ):

        // Initialize $img_id[]
        $img_id = [];

        foreach( $images as $image ):

          // Only add to the $img_id array and $thumbs array if
          //   $image['ID'] is not in $img_id array
          if( ! in_array($image['ID'], $img_id)):
            $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
            $img_id[] = $image['ID'];
            $thumbs[] = $cropped_img;
?>
</code>```

Hope this helps!

Depending on what your $image['ID'] values are, you may need to pass use the third argument of in_array() to do strict checking.

Reference: http://php.net/manual/en/function.in-array.php

Title: Prevent duplicate posts within foreach

Body:
Hello all, I'm currently working on a foreach loop that pulls images from a gallery from the backend of Wordpress. The gallery is working fine and as expected, however, I would like to prevent duplicate photos from appearing.

<?php if () $query->have_posts() ):
  $thumbs = [];
?>
<?php
    foreach( $query->posts as $gallery ):
      $images = get_field('gallery_images', $gallery->ID);
      if( $images ):
        foreach( $images as $image ):
          $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
          $img_id[] = $image['ID'];
          $thumbs[] = $cropped_img;
?>

Unrelated HTML to the Problem

<?php endforeach; endif; endforeach; ?>
<?php foreach($thumbs as $thumbnail): ?>

<img src="<?= $thumbnail; ?>">

<?php endforeach; ?>

Here is essentially what I'm trying to work out. I've thought to add two variables for the image ID so that they aren't duplicated in the first block of code. So that first if/foreach state looks like:

<?php if( $images ):
  foreach( $images as $image ):
    $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
    $img_id[] = $image['ID'];
    $do_not_duplicate[] = $image['ID'];
    $thumbs[] = $cropped_img;
?>

Followed by the followed foreach for the thumbnails

<?php foreach($thumbs as $thumbnail): ?>
    <?php foreach($img_id as $img): ?>
      <?php if ($img == $do_not_duplicate) : ?>
      //do nothing
      <?php else : ?>

<img src="<?= $thumbnail; ?>">

      <?php endif; ?>
<?php endforeach; endforeach; ?>

The problem I'm experiencing with this is I'm getting 22 images outputed 23 times because there are 22 images being pulled(with 1 duplicate). Essentially I'm trying to accomplish 22 images with no duplicates.

Any insight would be greatly appreciated, thank you in advance.

Body:
You could check if the image id already exists in the $img_id array before adding it.

I modified your code below

<?php if () $query->have_posts() ):
  $thumbs = [];
?>
<?php
    foreach( $query->posts as $gallery ):
      $images = get_field('gallery_images', $gallery->ID);
      if( $images ):

        // Initialize $img_id[]
        $img_id = [];

        foreach( $images as $image ):

          // Only add to the $img_id array and $thumbs array if
          //   $image['ID'] is not in $img_id array
          if( ! in_array($image['ID'], $img_id)):
            $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
            $img_id[] = $image['ID'];
            $thumbs[] = $cropped_img;
?>

Hope this helps!

Depending on what your $image['ID'] values are, you may need to pass use the third argument of in_array() to do strict checking.

Reference: http://php.net/manual/en/function.in-array.php


问:
How do declare an array in C++ as a parameter?
I am working with propriety code in my iOS project and all I have access to is the header files for my project. How do you declare an array in C++ so that it will return an array when I make a call?

Here's the header file method,

```<code> short WI_GetIDsFromList(int32_t module, int32_t *idsArray, uint32_t *count);
</code>```

How do you declare an array to received an array of in32_t? I keep getting a parameter error for returnedIdsArray when I make this call? It works perfectly fine for count? I tried making it into a pointer but it did not work?

```<code>    //Array of ID's
    int32_t returnedIdsArray[] = {};

    // Array of ID's count
    uint32_t count;

 rc += WI_GetIDsFromList(mod, returnedIdsArray, &count);
</code>```

Another Example

```<code>short dpCount;

//Get number of data points from the device
WI_GetDatapointCount(modIDHDS, &dpCount);

//dpCount now has returned value of method WI_GetDatapointCount
NSLog@"%d", int(dpCount);
</code>```

答:
You cannot pass an array in C or C++, because they will always decay to a pointer to the first element.

You can, however, pass a reference to an array.  It retains its array type rather than decay to a pointer, so sizeof() will return the actual size of the array rather than the sizeof pointer, and so on.

```<code>void f(char(&charArray)[30])
{
}
</code>```

Syntax is pretty ugly though.  A type alias can help:

```<code>using CharArray30 = char(&)[30];
void f(CharArray30 charArray)
{
}
</code>```

etc.  It has restrictions, though.  For example, you cannot pass arrays of a different size.

If you need your function to work with various sizes, you can use a function template with a non-type parameter for the size:

```<code>template <size_t SIZE>
void f(int32_t module, int32_t(&idArray)[SIZE])
{
  // ...
}
</code>```

Body:
I am working with propriety code in my iOS project and all I have access to is the header files for my project. How do you declare an array in C++ so that it will return an array when I make a call?

Here's the header file method,

 short WI_GetIDsFromList(int32_t module, int32_t *idsArray, uint32_t *count);

How do you declare an array to received an array of in32_t? I keep getting a parameter error for returnedIdsArray when I make this call? It works perfectly fine for count? I tried making it into a pointer but it did not work?

    //Array of ID's
    int32_t returnedIdsArray[] = {};

    // Array of ID's count
    uint32_t count;

 rc += WI_GetIDsFromList(mod, returnedIdsArray, &count);

Another Example

short dpCount;

//Get number of data points from the device
WI_GetDatapointCount(modIDHDS, &dpCount);

//dpCount now has returned value of method WI_GetDatapointCount
NSLog@"%d", int(dpCount);

Body:
You cannot pass an array in C or C++, because they will always decay to a pointer to the first element.

You can, however, pass a reference to an array.  It retains its array type rather than decay to a pointer, so sizeof() will return the actual size of the array rather than the sizeof pointer, and so on.

void f(char(&charArray)[30])
{
}

Syntax is pretty ugly though.  A type alias can help:

using CharArray30 = char(&)[30];
void f(CharArray30 charArray)
{
}

etc.  It has restrictions, though.  For example, you cannot pass arrays of a different size.

If you need your function to work with various sizes, you can use a function template with a non-type parameter for the size:

template <size_t SIZE>
void f(int32_t module, int32_t(&idArray)[SIZE])
{
  // ...
}