问:
Sending iDOC from Java to SAP
We have iDOC files that are generated from our system. Now we are trying to send them to SAP via RFC connection. I already etablished an RFC connection AS A CLIENT but i am unable to send iDOC!

I tried to create a sample iDOC to test it but it doesn't work!

```<code>Exception in thread "main" java.lang.NoSuchMethodError: com.sap.conn.idoc.jco.SAPRepository$ConnectionProvider.execute(Lcom/sap/conn/jco/JCoFunction;Lcom/sap/conn/jco/rt/AbapRepository;)V
    at com.sap.conn.idoc.jco.SAPRepository.queryRootSegmentMetaData40(SAPRepository.java:1204)
    at com.sap.conn.idoc.jco.SAPRepository.queryRootSegmentMetaData(SAPRepository.java:1110)
    at com.sap.conn.idoc.jco.SAPRepository.getRootSegmentMetaData(SAPRepository.java:909)
    at com.sap.conn.idoc.rt.DefaultIDocDocument.<init>(DefaultIDocDocument.java:124)
    at com.sap.conn.idoc.rt.DefaultIDocDocument.<init>(DefaultIDocDocument.java:61)
    at com.sap.conn.idoc.jco.JCoIDocDocument.<init>(JCoIDocDocument.java:51)
    at com.sap.conn.idoc.jco.JCoIDocRuntime.createIDocDocument(JCoIDocRuntime.java:133)
    at com.sap.conn.idoc.jco.JCoIDocRuntime.createIDocDocument(JCoIDocRuntime.java:35)
    at com.sap.conn.idoc.rt.DefaultIDocRuntime.createIDocDocument(DefaultIDocRuntime.java:175)
    at com.sap.conn.idoc.rt.DefaultIDocRuntime.createIDocDocument(DefaultIDocRuntime.java:18)
    at com.idoc.sender.IDocClientExample.main(IDocClientExample.java:49)
</code>```

I even tried to send a sample iDOC XML but i am also facing another error, tried to change the XML many times but i am facing the same problem again an again!

```<code>com.sap.conn.idoc.IDocParseException: (7) IDOC_ERROR_PARSE_FAILURE: Invalid character encountered in XML input data source:
state=READING_XMLDECLARATION, charPosition=14, lineNumber=1, columnNumber=15, invalidChar=U+003D,
sourceSnippet=...@<?xml version="1.0" encoding="UTF-8"?><DEBMAS06><IDOC><EDI_DC40><DOCNUM>20120114120000</DOCNUM><IDO...
                               ^
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.throwIDocParseException(DefaultIDocXMLParser.java:2223)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.parseProlog(DefaultIDocXMLParser.java:1635)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.parse(DefaultIDocXMLParser.java:320)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:112)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:54)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:31)
    at com.idoc.sender.IDocClientExample.main(IDocClientExample.java:57)
</code>```

This is the code i am using to create the iDOC and send the iDOC XML:

```<code>package com.idoc.sender;

import com.sap.conn.idoc.*;
import com.sap.conn.idoc.jco.JCoIDoc;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;

import java.io.BufferedReader;
import java.io.FileReader;

public class IDocClientExample {

 public static void main(String[] args) {

  try {

   String iDocXML = null;
   FileReader fileReader;

   try {
    fileReader = new FileReader("TestSalesOrder.xml");
    BufferedReader br = new BufferedReader(fileReader);
    StringBuffer sb = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
     sb.append(line);
    }

    iDocXML = sb.toString();

    br.close();
    fileReader.close();
   } catch (Exception ex) {
    ex.printStackTrace();
   }

   // see provided configuration file xxxx.jcoDestination
   JCoDestination destination = JCoDestinationManager.getDestination("xxxx");
   IDocRepository iDocRepository = JCoIDoc.getIDocRepository(destination);
   String tid = destination.createTID();
   IDocFactory iDocFactory = JCoIDoc.getIDocFactory();

   System.out.println(destination.getAttributes());

   // a) create sample new idoc
   IDocDocument doc = iDocFactory.createIDocDocument(iDocRepository, "SYSTAT01");
   IDocSegment segment = doc.getRootSegment();
   segment.addChild("E1MARAM");
   JCoIDoc.send(doc, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);

   // b) use existent xml file
   IDocXMLProcessor processor = iDocFactory.getIDocXMLProcessor();
   IDocDocumentList iDocList = processor.parse(iDocRepository, iDocXML);
   JCoIDoc.send(iDocList, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);
   destination.confirmTID(tid);

  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.print("program end");
 }
}
// a) create sample new idoc
IDocDocument doc = iDocFactory.createIDocDocument(iDocRepository, "SYSTAT01");
IDocSegment segment = doc.getRootSegment();
segment.addChild("E1MARAM");
JCoIDoc.send(doc, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);

// b) use existent xml file
IDocXMLProcessor processor = iDocFactory.getIDocXMLProcessor();
IDocDocumentList iDocList = processor.parse(iDocRepository, iDocXML);
JCoIDoc.send(iDocList, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);
destination.confirmTID(tid);

} catch (Exception e) {
 e.printStackTrace();
}
System.out.print("program end");
}
}
</code>```

This is my connection file:

```<code>jco.client.lang=EN
jco.client.client=100
jco.client.passwd=xxxx
jco.client.user=xxxx
jco.client.sysnr=01
jco.client.ashost=xxxx
</code>```

This is my xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<DEBMAS06>
<IDOC>
<EDI_DC40>
<DOCNUM>20120114120000</DOCNUM><IDOCTYP>DEBMAS06</IDOCTYP>
<MESTYP>DEBMAS</MESTYP>
<SNDPOR>HTTPDEMO</SNDPOR>
<SNDPRT>LS</SNDPRT>
<SNDPRN>HTTPDEMO</SNDPRN>
<RCVPOR>SAPxxx</RCVPOR>
<RCVPRT>LS</RCVPRT>
<RCVPRN>xxxCLNT100</RCVPRN>
</EDI_DC40>
<E1KNA1M segment="1">
<KUNNR>47</KUNNR>
<NAME1>Test Customer</NAME1>
<KTOKD>0004</KTOKD>
<SORTL>TEST</SORTL>
<ORT01>City</ORT01>
<LAND1>PL</LAND1>
<LZONE>A</LZONE>
<SPRAS>L</SPRAS>
<STRAS>Street</STRAS>
</E1KNA1M>
</IDOC>
</DEBMAS06>
</code>```

I am using sapjco3-x86-64bit-3.0.5 and sapidoc-3.0.1!

Testing the creation of iDOC and sending IDOC XML is just for test but in our case, we have the iDOC ready!

My question is, how can i send iDOC directly from my disk to SAP via RFC? If i can't do so, how can i slove the error of creating iDOC or sending iDOC XML? My second question, once i am able to send iDOC, do i have to etablish a new SERVER RFC connection so i can receive iDOC from SAP?

** EDIT **

Now i ma able to send and receive IDoc properly. My problem is how i can get the IDoc as a Flat IDoc.

I can receive my IDoc as XML IDoc with this code:

```<code>package com.idoc.actif;

import com.sap.conn.idoc.IDocDocumentList;
import com.sap.conn.idoc.IDocXMLProcessor;
import com.sap.conn.idoc.jco.*;
import com.sap.conn.jco.server.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class IDocServerExample
{
    public static void main(String[] a)
    {
        try
        {
            // see provided examples of configuration files xxxx.jcoServer and  xxxx.jcoDestination
            JCoIDocServer server = JCoIDoc.getServer("xxxx");
            server.setIDocHandlerFactory(new MyIDocHandlerFactory());

            server.setTIDHandler(new MyTidHandler());

            MyThrowableListener listener = new MyThrowableListener();
            server.addServerErrorListener(listener);
            server.addServerExceptionListener(listener);
            //server.setConnectionCount(1);
            server.start();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
     }

    static class MyIDocHandler implements JCoIDocHandler
    {
        public void handleRequest(JCoServerContext serverCtx, IDocDocumentList idocList)
        {

            FileOutputStream fos=null;
            OutputStreamWriter osw=null;
            try
            {
                //receiving XML IDoc, how to get the IDoc as a Flat IDoc (SAP is sending the IDoc as Flat)???
                IDocXMLProcessor xmlProcessor = JCoIDoc.getIDocFactory().getIDocXMLProcessor();
                fos=new FileOutputStream(serverCtx.getTID());
                osw=new OutputStreamWriter(fos, "UTF8");
                xmlProcessor.render(idocList, osw, IDocXMLProcessor.RENDER_WITH_TABS_AND_CRLF);
                osw.flush();
            }
            catch (Throwable thr)
            {
                thr.printStackTrace();
            }
            finally
            {
                try
                {
                    if (osw!=null)
                        osw.close();
                    if (fos!=null)
                        fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    static class MyIDocHandlerFactory implements JCoIDocHandlerFactory
    {
        private JCoIDocHandler handler = new MyIDocHandler();
        public JCoIDocHandler getIDocHandler(JCoIDocServerContext serverCtx)
        {
            return handler;
        }
    }

    static class MyThrowableListener implements JCoServerErrorListener, JCoServerExceptionListener
    {

        public void serverErrorOccurred(JCoServer server, String connectionId, JCoServerContextInfo ctx, Error error)
        {
            System.out.println(">>> Error occured on " + server.getProgramID() + " connection " + connectionId);
            error.printStackTrace();
        }
        public void serverExceptionOccurred(JCoServer server, String connectionId, JCoServerContextInfo ctx, Exception error)
        {
            System.out.println(">>> Error occured on " + server.getProgramID() + " connection " + connectionId);
            error.printStackTrace();
        }
    }

    static class MyTidHandler implements JCoServerTIDHandler
    {
        public boolean checkTID(JCoServerContext serverCtx, String tid)
        {
            System.out.println("checkTID called for TID="+tid);
            return true;
        }

        public void confirmTID(JCoServerContext serverCtx, String tid)
        {
            System.out.println("confirmTID called for TID="+tid);
        }

        public void commit(JCoServerContext serverCtx, String tid)
        {
            System.out.println("commit called for TID="+tid);
        }

        public void rollback(JCoServerContext serverCtx, String tid)
        {
            System.out.print("rollback called for TID="+tid);
        }
    }
}
</code>```

答:
I guess that there is an incompatibility between the two SAP libraries that you use. I recommend to install the latest patch levels first. Currently this is JCo version 3.0.17 and the Java IDoc Library 3.0.12.

I only do not understand what you are doing with the StringBuffer here. If you would like to read IDoc-XML from a file, then the IDocXMLProcessor offers appropriate parse methods for this - the best would be

```<code>IDocXMLProcessor.parse(IDocRepository repository, InputStream xmlStream)
</code>```

so that it also can take care of different file encodings as specified in the contained XML encoding attribute. If you choose a java.io.Reader or a String then you have to take care for this on your own (which you don't do in your example).

But in principle your code doesn't seem to be wrong at first sight.
In contrast to the IDoc-XML itself which is lacking the mandatory BEGIN="1" and SEGMENT="1" attributes for the <IDOC> and <EDI_DC40> tags.

Title: Sending iDOC from Java to SAP

Body:
We have iDOC files that are generated from our system. Now we are trying to send them to SAP via RFC connection. I already etablished an RFC connection AS A CLIENT but i am unable to send iDOC!

I tried to create a sample iDOC to test it but it doesn't work!

Exception in thread "main" java.lang.NoSuchMethodError: com.sap.conn.idoc.jco.SAPRepository$ConnectionProvider.execute(Lcom/sap/conn/jco/JCoFunction;Lcom/sap/conn/jco/rt/AbapRepository;)V
    at com.sap.conn.idoc.jco.SAPRepository.queryRootSegmentMetaData40(SAPRepository.java:1204)
    at com.sap.conn.idoc.jco.SAPRepository.queryRootSegmentMetaData(SAPRepository.java:1110)
    at com.sap.conn.idoc.jco.SAPRepository.getRootSegmentMetaData(SAPRepository.java:909)
    at com.sap.conn.idoc.rt.DefaultIDocDocument.<init>(DefaultIDocDocument.java:124)
    at com.sap.conn.idoc.rt.DefaultIDocDocument.<init>(DefaultIDocDocument.java:61)
    at com.sap.conn.idoc.jco.JCoIDocDocument.<init>(JCoIDocDocument.java:51)
    at com.sap.conn.idoc.jco.JCoIDocRuntime.createIDocDocument(JCoIDocRuntime.java:133)
    at com.sap.conn.idoc.jco.JCoIDocRuntime.createIDocDocument(JCoIDocRuntime.java:35)
    at com.sap.conn.idoc.rt.DefaultIDocRuntime.createIDocDocument(DefaultIDocRuntime.java:175)
    at com.sap.conn.idoc.rt.DefaultIDocRuntime.createIDocDocument(DefaultIDocRuntime.java:18)
    at com.idoc.sender.IDocClientExample.main(IDocClientExample.java:49)

I even tried to send a sample iDOC XML but i am also facing another error, tried to change the XML many times but i am facing the same problem again an again!

com.sap.conn.idoc.IDocParseException: (7) IDOC_ERROR_PARSE_FAILURE: Invalid character encountered in XML input data source:
state=READING_XMLDECLARATION, charPosition=14, lineNumber=1, columnNumber=15, invalidChar=U+003D,
sourceSnippet=...@<?xml version="1.0" encoding="UTF-8"?><DEBMAS06><IDOC><EDI_DC40><DOCNUM>20120114120000</DOCNUM><IDO...
                               ^
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.throwIDocParseException(DefaultIDocXMLParser.java:2223)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.parseProlog(DefaultIDocXMLParser.java:1635)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLParser.parse(DefaultIDocXMLParser.java:320)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:112)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:54)
    at com.sap.conn.idoc.rt.xml.DefaultIDocXMLProcessor.parse(DefaultIDocXMLProcessor.java:31)
    at com.idoc.sender.IDocClientExample.main(IDocClientExample.java:57)

This is the code i am using to create the iDOC and send the iDOC XML:

package com.idoc.sender;

import com.sap.conn.idoc.*;
import com.sap.conn.idoc.jco.JCoIDoc;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;

import java.io.BufferedReader;
import java.io.FileReader;

public class IDocClientExample {

 public static void main(String[] args) {

  try {

   String iDocXML = null;
   FileReader fileReader;

   try {
    fileReader = new FileReader("TestSalesOrder.xml");
    BufferedReader br = new BufferedReader(fileReader);
    StringBuffer sb = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
     sb.append(line);
    }

    iDocXML = sb.toString();

    br.close();
    fileReader.close();
   } catch (Exception ex) {
    ex.printStackTrace();
   }

   // see provided configuration file xxxx.jcoDestination
   JCoDestination destination = JCoDestinationManager.getDestination("xxxx");
   IDocRepository iDocRepository = JCoIDoc.getIDocRepository(destination);
   String tid = destination.createTID();
   IDocFactory iDocFactory = JCoIDoc.getIDocFactory();

   System.out.println(destination.getAttributes());

   // a) create sample new idoc
   IDocDocument doc = iDocFactory.createIDocDocument(iDocRepository, "SYSTAT01");
   IDocSegment segment = doc.getRootSegment();
   segment.addChild("E1MARAM");
   JCoIDoc.send(doc, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);

   // b) use existent xml file
   IDocXMLProcessor processor = iDocFactory.getIDocXMLProcessor();
   IDocDocumentList iDocList = processor.parse(iDocRepository, iDocXML);
   JCoIDoc.send(iDocList, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);
   destination.confirmTID(tid);

  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.print("program end");
 }
}
// a) create sample new idoc
IDocDocument doc = iDocFactory.createIDocDocument(iDocRepository, "SYSTAT01");
IDocSegment segment = doc.getRootSegment();
segment.addChild("E1MARAM");
JCoIDoc.send(doc, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);

// b) use existent xml file
IDocXMLProcessor processor = iDocFactory.getIDocXMLProcessor();
IDocDocumentList iDocList = processor.parse(iDocRepository, iDocXML);
JCoIDoc.send(iDocList, IDocFactory.IDOC_VERSION_DEFAULT, destination, tid);
destination.confirmTID(tid);

} catch (Exception e) {
 e.printStackTrace();
}
System.out.print("program end");
}
}

This is my connection file:

jco.client.lang=EN
jco.client.client=100
jco.client.passwd=xxxx
jco.client.user=xxxx
jco.client.sysnr=01
jco.client.ashost=xxxx

This is my xml file:

<?xml version="1.0" encoding="UTF-8"?>
<DEBMAS06>
<IDOC>
<EDI_DC40>
<DOCNUM>20120114120000</DOCNUM><IDOCTYP>DEBMAS06</IDOCTYP>
<MESTYP>DEBMAS</MESTYP>
<SNDPOR>HTTPDEMO</SNDPOR>
<SNDPRT>LS</SNDPRT>
<SNDPRN>HTTPDEMO</SNDPRN>
<RCVPOR>SAPxxx</RCVPOR>
<RCVPRT>LS</RCVPRT>
<RCVPRN>xxxCLNT100</RCVPRN>
</EDI_DC40>
<E1KNA1M segment="1">
<KUNNR>47</KUNNR>
<NAME1>Test Customer</NAME1>
<KTOKD>0004</KTOKD>
<SORTL>TEST</SORTL>
<ORT01>City</ORT01>
<LAND1>PL</LAND1>
<LZONE>A</LZONE>
<SPRAS>L</SPRAS>
<STRAS>Street</STRAS>
</E1KNA1M>
</IDOC>
</DEBMAS06>

I am using sapjco3-x86-64bit-3.0.5 and sapidoc-3.0.1!

Testing the creation of iDOC and sending IDOC XML is just for test but in our case, we have the iDOC ready!

My question is, how can i send iDOC directly from my disk to SAP via RFC? If i can't do so, how can i slove the error of creating iDOC or sending iDOC XML? My second question, once i am able to send iDOC, do i have to etablish a new SERVER RFC connection so i can receive iDOC from SAP?

** EDIT **

Now i ma able to send and receive IDoc properly. My problem is how i can get the IDoc as a Flat IDoc.

I can receive my IDoc as XML IDoc with this code:

package com.idoc.actif;

import com.sap.conn.idoc.IDocDocumentList;
import com.sap.conn.idoc.IDocXMLProcessor;
import com.sap.conn.idoc.jco.*;
import com.sap.conn.jco.server.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class IDocServerExample
{
    public static void main(String[] a)
    {
        try
        {
            // see provided examples of configuration files xxxx.jcoServer and  xxxx.jcoDestination
            JCoIDocServer server = JCoIDoc.getServer("xxxx");
            server.setIDocHandlerFactory(new MyIDocHandlerFactory());

            server.setTIDHandler(new MyTidHandler());

            MyThrowableListener listener = new MyThrowableListener();
            server.addServerErrorListener(listener);
            server.addServerExceptionListener(listener);
            //server.setConnectionCount(1);
            server.start();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
     }

    static class MyIDocHandler implements JCoIDocHandler
    {
        public void handleRequest(JCoServerContext serverCtx, IDocDocumentList idocList)
        {

            FileOutputStream fos=null;
            OutputStreamWriter osw=null;
            try
            {
                //receiving XML IDoc, how to get the IDoc as a Flat IDoc (SAP is sending the IDoc as Flat)???
                IDocXMLProcessor xmlProcessor = JCoIDoc.getIDocFactory().getIDocXMLProcessor();
                fos=new FileOutputStream(serverCtx.getTID());
                osw=new OutputStreamWriter(fos, "UTF8");
                xmlProcessor.render(idocList, osw, IDocXMLProcessor.RENDER_WITH_TABS_AND_CRLF);
                osw.flush();
            }
            catch (Throwable thr)
            {
                thr.printStackTrace();
            }
            finally
            {
                try
                {
                    if (osw!=null)
                        osw.close();
                    if (fos!=null)
                        fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    static class MyIDocHandlerFactory implements JCoIDocHandlerFactory
    {
        private JCoIDocHandler handler = new MyIDocHandler();
        public JCoIDocHandler getIDocHandler(JCoIDocServerContext serverCtx)
        {
            return handler;
        }
    }

    static class MyThrowableListener implements JCoServerErrorListener, JCoServerExceptionListener
    {

        public void serverErrorOccurred(JCoServer server, String connectionId, JCoServerContextInfo ctx, Error error)
        {
            System.out.println(">>> Error occured on " + server.getProgramID() + " connection " + connectionId);
            error.printStackTrace();
        }
        public void serverExceptionOccurred(JCoServer server, String connectionId, JCoServerContextInfo ctx, Exception error)
        {
            System.out.println(">>> Error occured on " + server.getProgramID() + " connection " + connectionId);
            error.printStackTrace();
        }
    }

    static class MyTidHandler implements JCoServerTIDHandler
    {
        public boolean checkTID(JCoServerContext serverCtx, String tid)
        {
            System.out.println("checkTID called for TID="+tid);
            return true;
        }

        public void confirmTID(JCoServerContext serverCtx, String tid)
        {
            System.out.println("confirmTID called for TID="+tid);
        }

        public void commit(JCoServerContext serverCtx, String tid)
        {
            System.out.println("commit called for TID="+tid);
        }

        public void rollback(JCoServerContext serverCtx, String tid)
        {
            System.out.print("rollback called for TID="+tid);
        }
    }
}

Body:
I guess that there is an incompatibility between the two SAP libraries that you use. I recommend to install the latest patch levels first. Currently this is JCo version 3.0.17 and the Java IDoc Library 3.0.12.

I only do not understand what you are doing with the StringBuffer here. If you would like to read IDoc-XML from a file, then the IDocXMLProcessor offers appropriate parse methods for this - the best would be

IDocXMLProcessor.parse(IDocRepository repository, InputStream xmlStream)

so that it also can take care of different file encodings as specified in the contained XML encoding attribute. If you choose a java.io.Reader or a String then you have to take care for this on your own (which you don't do in your example).

But in principle your code doesn't seem to be wrong at first sight.
In contrast to the IDoc-XML itself which is lacking the mandatory BEGIN="1" and SEGMENT="1" attributes for the <IDOC> and <EDI_DC40> tags.


来源: stackexchange

问:
ROUND() in SQL Server when dealing with a decimal in varchar
I know the usage of Round() and it works fine for

```<code>select round(147.26719,5,1)
</code>```

which returns 147.26719.

Currently I am working on a table imported from a txt file so all the column are varchar, when I using round() to deal with a decimal in varchar like this

```<code>select round('147.26719',5,1)
</code>```

very weird it returns 147.26718.

I current make it run correctly as

```<code>select round(cast('147.26719', decimal(11,6)),5,1)
</code>```

but can anybody explains to me why this happens? I believe it is something when implicitly convert the varchar to decimal, but just don't know why.

Thanks in advance

答:
By default, the implicit conversion of the string for the round() is into a float, not a decimal.  Floating point numbers are imprecise and might be off just a wee, wee bit from what you see -- but enough to matter.

Your solution is the correct one -- cast to a decimal.

You can readily see this by using code such as:

```<code>select round('123.3', 1) as col
into x;

select *
from information_schema.columns
where table_name = 'x';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know the usage of Round() and it works fine for

select round(147.26719,5,1)

which returns 147.26719.

Currently I am working on a table imported from a txt file so all the column are varchar, when I using round() to deal with a decimal in varchar like this

select round('147.26719',5,1)

very weird it returns 147.26718.

I current make it run correctly as

select round(cast('147.26719', decimal(11,6)),5,1)

but can anybody explains to me why this happens? I believe it is something when implicitly convert the varchar to decimal, but just don't know why.

Thanks in advance

Body:
By default, the implicit conversion of the string for the round() is into a float, not a decimal.  Floating point numbers are imprecise and might be off just a wee, wee bit from what you see -- but enough to matter.

Your solution is the correct one -- cast to a decimal.

You can readily see this by using code such as:

select round('123.3', 1) as col
into x;

select *
from information_schema.columns
where table_name = 'x';


问:
Sort model relationship date
I have two tables:

```<code>Discussion:
╔════╦════════════════╗
║ id ║     name       ║
╠════╬════════════════╣
║  1 ║ Stackoverflow  ║
║  2 ║ Stackoverflow2 ║
╚════╩════════════════╝

Message:
╔════╦════════════════╦═══════════╦════════════╗
║ id ║ discussion_id  ║  content  ║    date    ║
╠════╬════════════════╬═══════════╬════════════╣
║  1 ║       1        ║ message 1 ║  jan 2011  ║
║  2 ║       1        ║ message 2 ║  jan 2012  ║
║  3 ║       2        ║ message 3 ║  jan 2013  ║
║  4 ║       2        ║ message 4 ║  jan 2014  ║
╚════╩════════════════╩═══════════╩════════════╝
</code>```

The results of Discussion::find() should be sorted like this:

```<code>Stackoverflow2
Stackoverflow
</code>```

Because "Stackoverflow2" is more recent than "Stackoverflow" according to the dates in the Message table.

Do you have an idea?

答:
Thanks, with the syntax Phalcon, it's become :</p>

```<code>$discussions = $this->modelsManager->createBuilder()
->from('Phalcon\Model\DiscussionModel')
->join('Phalcon\Model\MessageModel')
->orderBy("Phalcon\Model\MessageModel.cts DESC")
->getQuery()
->execute();
</code>```

Title: Sort model relationship date

Body:
I have two tables:

Discussion:
╔════╦════════════════╗
║ id ║     name       ║
╠════╬════════════════╣
║  1 ║ Stackoverflow  ║
║  2 ║ Stackoverflow2 ║
╚════╩════════════════╝

Message:
╔════╦════════════════╦═══════════╦════════════╗
║ id ║ discussion_id  ║  content  ║    date    ║
╠════╬════════════════╬═══════════╬════════════╣
║  1 ║       1        ║ message 1 ║  jan 2011  ║
║  2 ║       1        ║ message 2 ║  jan 2012  ║
║  3 ║       2        ║ message 3 ║  jan 2013  ║
║  4 ║       2        ║ message 4 ║  jan 2014  ║
╚════╩════════════════╩═══════════╩════════════╝

The results of Discussion::find() should be sorted like this:

Stackoverflow2
Stackoverflow

Because "Stackoverflow2" is more recent than "Stackoverflow" according to the dates in the Message table.

Do you have an idea?

Body:
Thanks, with the syntax Phalcon, it's become :

$discussions = $this->modelsManager->createBuilder()
->from('Phalcon\Model\DiscussionModel')
->join('Phalcon\Model\MessageModel')
->orderBy("Phalcon\Model\MessageModel.cts DESC")
->getQuery()
->execute();


问:
Can opengl calls run without a GPU present?
I know that opengl is a library that allows certain tasks/calls (like shading) to be executed on the GPU for faster computation (hardware accelerated). I've been reading on the internet about it and am wondering if calls to opengl will run without a GPU present. For example, someone on this forum (https://www.gamedev.net/forums/topic/638883-will-opengl-3d-games-run-in-a-pc-without-a-dedicated-video-card/) mentioned that it can run as a software emulation. Can anyone speak to this?</p>

答: Yes, if it all just depends on whether or not the vendor of the device bothered to write OpenGL drivers for his or her system. All OpenGL functions can be implemented without a graphics card, but with a performance penalty, of course.</p>


问:
Connection Timeout With File_get_contents()
I am working on a script that fetches csv files from a web server. I am using file_get_contents presently. Sometimes i get the message

```<code>Warning: file_get_contents failed to open stream: Connection timed out
</code>```

I assume it can be due to website being down. Or can there be a situation where the website is fine but still this warning shows up. Also what advantage does CURL provide over this function.

答: For accessing remote files, you should use cURL.  You can set cURL to timeout quietly if the remote server takes too long.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am working on a script that fetches csv files from a web server. I am using file_get_contents presently. Sometimes i get the message

Warning: file_get_contents failed to open stream: Connection timed out

I assume it can be due to website being down. Or can there be a situation where the website is fine but still this warning shows up. Also what advantage does CURL provide over this function.


问:
C++ - functor vs inline function vs operator overload?
Based on various Stack Overflow posts, I put the following together in a license plate recognition program I did a while back:

PossiblePlate.h:

```<code>(lines omitted)

std::string strChars;

///////////////////////////////////////////////////////////////////////////////////////////////
static bool sortDescendingByNumberOfChars(const PossiblePlate &ppLeft, const PossiblePlate &ppRight) {
    return(ppLeft.strChars.length() > ppRight.strChars.length());
}

(lines omitted)
</code>```

Main.cpp

```<code>(lines omitted)

// sort the vector of possible plates in descending order (most number of chars to least number of chars)
std::sort(vectorOfPossiblePlates.begin(), vectorOfPossiblePlates.end(), PossiblePlate::sortDescendingByNumberOfChars);

(lines omitted)
</code>```

Here is the repo if more context would be helpful:

https://github.com/MicrocontrollersAndMore/OpenCV_3_License_Plate_Recognition_Cpp

This code is great for sorting a vector of objects in C++ based on any member variable, I've re-used it quite a few times since in various other projects.

My question is, what is this?  A functor, inline function, operator overload, or something else entirely?  How could I determine the difference?

答:
My question is, what is this? A functor, inline function, operator overload, or something else entirely?

It is just a function, that got converted to a pointer to function. A function pointer can be used in the function call operator, thus it can be used as a comparator for std::sort.

Body:
Based on various Stack Overflow posts, I put the following together in a license plate recognition program I did a while back:

PossiblePlate.h:

(lines omitted)

std::string strChars;

///////////////////////////////////////////////////////////////////////////////////////////////
static bool sortDescendingByNumberOfChars(const PossiblePlate &ppLeft, const PossiblePlate &ppRight) {
    return(ppLeft.strChars.length() > ppRight.strChars.length());
}

(lines omitted)

Main.cpp

(lines omitted)

// sort the vector of possible plates in descending order (most number of chars to least number of chars)
std::sort(vectorOfPossiblePlates.begin(), vectorOfPossiblePlates.end(), PossiblePlate::sortDescendingByNumberOfChars);

(lines omitted)

Here is the repo if more context would be helpful:

https://github.com/MicrocontrollersAndMore/OpenCV_3_License_Plate_Recognition_Cpp

This code is great for sorting a vector of objects in C++ based on any member variable, I've re-used it quite a few times since in various other projects.

My question is, what is this?  A functor, inline function, operator overload, or something else entirely?  How could I determine the difference?


问:
Convert MSP432 freeRTOS demo project to Fresh empty Project
I recently started to learn RTOS. I need help to modify MSP432 freeRTOS demo project to a fresh Project or Create a new freeRTOS project for MSP432. I use Code compiler studio from Texas Instrument. I searched all over the web, but no luck.</p>

答:
As replied on the FreeRTOS forum too:

If you really must create a project from scratch then the following
links might help, but it is really best to adapt an existing project
that start a new one:
http://www.freertos.org/Creating-a-new-FreeRTOS-project.html
http://www.freertos.org/porting-a-freertos-demo-to-different-hardware.html


问:
Thymeleaf show another image if not exists
I'm using the following image code that will show an image only if it exists.

```<code><img th:if="${!ad.adPhotos.empty}" th:src="|/imageDisplay?id=${ad.adPhotos[0].id}|" alt="" class="img-respocive" />
</code>```

I want to show this for the else caluse

```<code><img height="150" width="150" src="img/NoPicAvailable.png" />
</code>```

How would this be done with Thymeleaf?

答:
I would personally do it like this:

```<code><img th:unless="${ad.adPhotos.empty}" th:src="|/imageDisplay?id=${ad.adPhotos[0].id}|" alt="" class="img-respocive" />
<img th:if="${ad.adPhotos.empty}"height="150" width="150" src="img/NoPicAvailable.png" />
</code>```

As a sidenote, I think I would generate the src with thymeleaf url syntax, rather than string concatenation.

```<code><img th:unless="${ad.adPhotos.empty}" th:src="@{/imageDisplay(id=${ad.adPhotos[0].id})}" alt="" class="img-respocive" />
</code>```

Body:
I'm using the following image code that will show an image only if it exists.

I want to show this for the else caluse

How would this be done with Thymeleaf?

Body:
I would personally do it like this:

<img th:unless="${ad.adPhotos.empty}" th:src="|/imageDisplay?id=${ad.adPhotos[0].id}|" alt="" class="img-respocive" />
<img th:if="${ad.adPhotos.empty}"height="150" width="150" src="img/NoPicAvailable.png" />

As a sidenote, I think I would generate the src with thymeleaf url syntax, rather than string concatenation.

<img th:unless="${ad.adPhotos.empty}" th:src="@{/imageDisplay(id=${ad.adPhotos[0].id})}" alt="" class="img-respocive" />


问:
Google Sheets removing leading spaces query results
My sheet is pulling data from another sheet with:

```<code>=QUERY('WHERE TO SEND STUDENTS'!A:D, "select B,C,D where A<>'' order by D",1)
</code>```

Some of the contents of D has a leading space which causes it to be at the top of the column. Is there a way to remove this leading space and then sort the column D?

答:
I concede this in the category "Quick & Dirty", but it does the job:</p>

```<code>=arrayformula( query( if( {0,0,0,1}, TRIM(A:D), A:D), "select Col2, Col3, Col4 where Col2 <> '' order by Col4", 1 ) )
</code>```

Body:
My sheet is pulling data from another sheet with:

=QUERY('WHERE TO SEND STUDENTS'!A:D, "select B,C,D where A<>'' order by D",1)

Some of the contents of D has a leading space which causes it to be at the top of the column. Is there a way to remove this leading space and then sort the column D?

Body:
I concede this in the category "Quick & Dirty", but it does the job:

=arrayformula( query( if( {0,0,0,1}, TRIM(A:D), A:D), "select Col2, Col3, Col4 where Col2 <> '' order by Col4", 1 ) )


问:
How can I call a parent function which would use the subclass's overriden final variables?
Relevant code from my first class:

```<code>protected static final float MAX_HEALTH = 100.0f;
protected static final float MIN_HEALTH = 0.0f;

public void modifyHealth(float enteredAmount)
{
    if (health + enteredAmount > MAX_HEALTH )
    {
        health = MAX_HEALTH;
    }
    else if (health + enteredAmount < MIN_HEALTH)
    {
        health = MIN_HEALTH;
    }
    else
    {
        health += enteredAmount;
    }
}
</code>```

Second class which extends the first class:

```<code>private final float MAX_HEALTH = 500.0f;
</code>```

When I call the modifyHealth method on the second class, I want the health to be able to increase beyond 100, however currently it still uses the parent classs' final variable value. How can I make it so that the health can increase up to 500, while keeping both the variables final?

答:
Change the definition to
    protected float MAX_HEALTH = 100.0f;

And override in the subclass. That way you can still use the method with different MAX_HEALTH value.

Body:
Relevant code from my first class:

protected static final float MAX_HEALTH = 100.0f;
protected static final float MIN_HEALTH = 0.0f;

public void modifyHealth(float enteredAmount)
{
    if (health + enteredAmount > MAX_HEALTH )
    {
        health = MAX_HEALTH;
    }
    else if (health + enteredAmount < MIN_HEALTH)
    {
        health = MIN_HEALTH;
    }
    else
    {
        health += enteredAmount;
    }
}

Second class which extends the first class:

private final float MAX_HEALTH = 500.0f;

When I call the modifyHealth method on the second class, I want the health to be able to increase beyond 100, however currently it still uses the parent classs' final variable value. How can I make it so that the health can increase up to 500, while keeping both the variables final?


问:
How to have a
 that is on the right side of a menu expand as the browser window expands?
You must know that this question is very specific to my situation and I would really love to hear what you guys have to say!

So, I am trying to have a page on my website where on the left side there is a menu and on the right side there is the content. I gave the div that contains the menu a width of 200px, but my question is, how do I place the div that contains the content on the right of the side-menu? Because keep in mind that I want the div that contains the content to expand or shrink as the browsers window size changes.

First scenario:
I floated the side-menu to the left and I also floated the div containing the content to the left, but when I give it a width of 100% it goes under the side-menu.

Second scenario:
I floated the side-menu to the left and I placed the div containing the content to the right of the side menu by giving it a margin-left of 250px.

But in both of these scenarios the div containing the content doesn't fit the browser's window, meaning if i resized the browser that div won't expand, it  goes under the side-menu.

Question 1:
How do i give the div containing the content a non-fixed width so it can expand or shrink when the browser's window is resized. The side-menu will still be there even when the browser window size shrinks or expands.

Question 2: How do I place the div that contains the content next to the side menu? Do I float it? Do I give it a margin-left? Do I absolutely position it?

Please tell me how to place that div and how to make it expand or shrink and fit different browser window size.

Here is a screenshot of it: (click on the link)

side menu on the left and content on the right

答:
It appears that you have not started coding yet. That's a bit of an issue, so my answer is going to be a little dry, but here we go:

Question 1: How do i give the div containing the content a non-fixed width so it can expand or shrink when the browser's window is resized. The side-menu will still be there even when the browser window size shrinks or expands.

CSS Flexbox flex-basis might do the trick. If you combine it with relative units such as percentages.

Question 2: How do I place the div that contains the content next to the side menu? Do I float it? Do I give it a margin-left? Do I absolutely position it?

Again, using CSS Flexbox.

But like what is the general practice in this kind of situations? How do other websites do it? Media-queries?

Usually media queries is a good way to start, yes. Here is a good guide: using media queries - MDN

Holy Grail Layout example:

Follow the guide from MDN : using CSS Flexible Boxes

Come here if you got an issue and a piece of code to show so we can help

Hope I helped a bit.

Title: How to have a <div> that is on the right side of a menu expand as the browser window expands?


问:
Undefined Boost reference
I'm trying to link against a 3rd party library that uses Boost.  I've linked against the correct boost library (libboost_program_options.a), but still not finding it.

The error msg (formatted a bit for clarity):

```<code>undefined reference to `boost::program_options::validate(boost::any&,
                              std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&,
                              std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*,
                              int)'
</code>```

nm --demangle libboost_program_options.a | grep validate

```<code>boost::program_options::validate(boost::any&,                                   std::vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > > const&,
                                  bool*,
                                  int)
 boost::program_options::validate(boost::any&,
                                  std::vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > > const&,
                                  std::string*,
                                  int)
 boost::program_options::validate(boost::any&,
                                  std::vector<std::string, std::allocator<std::string> > const&,
                                  bool*,
                                  int)
 boost::program_options::validate(boost::any&,
                                  std::vector<std::string, std::allocator<std::string> > const&,
                                  std::string*,
                                  int)
</code>```

The second record looks similar, but apparently not close enough.  Any idea how I can compile Boost to get a signature that matches what's in the library?  I have a request out to the library owner to see what version of Boost they're using and such, but haven't heard back yet.

This is on a CentOS 7 box, which uses g++ version 4.8.5.  But the library I'm tryng to link against uses C++11 heavily and was compiled with g++ v 6.1, so I installed devtoolset-6 which gives me a g++ 6 environment (g++ version 6.3.1)

I downloaded and built Boost from scratch (v1.65.1) so that it's built with the same compiler, rather then the system version.

Edit...
I think John Zwinck is on the right track, but I can't get the boost library to compile to the new ABI.

The validate() functions are found in value_semantic.cpp

Stripping the build down to the basics, and adding the flags discussed:

```<code>g++ -std=c++11 -D_GLIBCXX_USE_CXX11_ABI -c -o test.o libs/program_options/src/value_semantic.cpp

nm --demangle test.o | grep validate
00000000000008b6 T boost::program_options::validate(boost::any&, std::vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > > const&, bool*, int)
0000000000000c02 T boost::program_options::validate(boost::any&, std::vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > > const&, std::string*, int)
00000000000005f2 T boost::program_options::validate(boost::any&, std::vector<std::string, std::allocator<std::string> > const&, bool*, int)
0000000000000b9a T boost::program_options::validate(boost::any&, std::vector<std::string, std::allocator<std::string> > const&, std::string*, int)
</code>```

Does the _GLIBCXX_USE_CXX11_ABI macro only work with gcc 5.1?

答:
Ok, I think I've figured out why I can't get g++ to generate the cxx11 signature (new ABI).

If I run g++ with the -v option:

```<code>g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/opt/rh/devtoolset-6/root/usr/libexec/gcc/x86_64-redhat-linux/6.3.1/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --enable-bootstrap --enable-languages=c,c++,fortran,lto --prefix=/opt/rh/devtoolset-6/root/usr --mandir=/opt/rh/devtoolset-6/root/usr/share/man --infodir=/opt/rh/devtoolset-6/root/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --enable-plugin --with-linker-hash-style=gnu --enable-initfini-array --disable-libgcj --with-default-libstdcxx-abi=gcc4-compatible --with-isl=/builddir/build/BUILD/gcc-6.3.1-20170216/obj-x86_64-redhat-linux/isl-install --enable-libmpx --enable-gnu-indirect-function --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 6.3.1 20170216 (Red Hat 6.3.1-3) (GCC)
</code>```

Note the following under the "configured with" field

--with-default-libstdcxx-abi=gcc4-compatible

What I believe this means is that the devtoolset-6 version of g++ is built with the old style ABI "baked in", and it therefore doesn't respond to the _GLIBCXX_USE_CXX11_ABI macro.

According to this link: https://gcc.gnu.org/onlinedocs/libstdc++/manual/configure.html

--with-default-libstdcxx-abi=OPTION
Set the default value for the _GLIBCXX_USE_CXX11_ABI macro (see Macros). The default is OPTION=new which sets the macro to 1, use OPTION=gcc4-compatible to set it to 0. This option does not change the library ABI.

It would seem to only change the default value of _GLIBCXX_USE_CXX11_ABI, but in my attempts setting _GLIBCXX_USE_CXX11_ABI doesn't have any effect.

Not positive of this, but it's my working theory for now.  Any additional insight is appreciated.

Title: Undefined Boost reference

Body:
I'm trying to link against a 3rd party library that uses Boost.  I've linked against the correct boost library (libboost_program_options.a), but still not finding it.

The error msg (formatted a bit for clarity):

undefined reference to `boost::program_options::validate(boost::any&,
                              std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&,
                              std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*,
                              int)'

nm --demangle libboost_program_options.a | grep validate

boost::program_options::validate(boost::any&,                                   std::vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > > const&,
                                  bool*,
                                  int)
 boost::program_options::validate(boost::any&,
                                  std::vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > > const&,
                                  std::string*,
                                  int)
 boost::program_options::validate(boost::any&,
                                  std::vector<std::string, std::allocator<std::string> > const&,
                                  bool*,
                                  int)
 boost::program_options::validate(boost::any&,
                                  std::vector<std::string, std::allocator<std::string> > const&,
                                  std::string*,
                                  int)

The second record looks similar, but apparently not close enough.  Any idea how I can compile Boost to get a signature that matches what's in the library?  I have a request out to the library owner to see what version of Boost they're using and such, but haven't heard back yet.

This is on a CentOS 7 box, which uses g++ version 4.8.5.  But the library I'm tryng to link against uses C++11 heavily and was compiled with g++ v 6.1, so I installed devtoolset-6 which gives me a g++ 6 environment (g++ version 6.3.1)

I downloaded and built Boost from scratch (v1.65.1) so that it's built with the same compiler, rather then the system version.

Edit...
I think John Zwinck is on the right track, but I can't get the boost library to compile to the new ABI.

The validate() functions are found in value_semantic.cpp

Stripping the build down to the basics, and adding the flags discussed:

g++ -std=c++11 -D_GLIBCXX_USE_CXX11_ABI -c -o test.o libs/program_options/src/value_semantic.cpp

nm --demangle test.o | grep validate
00000000000008b6 T boost::program_options::validate(boost::any&, std::vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > > const&, bool*, int)
0000000000000c02 T boost::program_options::validate(boost::any&, std::vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > > const&, std::string*, int)
00000000000005f2 T boost::program_options::validate(boost::any&, std::vector<std::string, std::allocator<std::string> > const&, bool*, int)
0000000000000b9a T boost::program_options::validate(boost::any&, std::vector<std::string, std::allocator<std::string> > const&, std::string*, int)

Does the _GLIBCXX_USE_CXX11_ABI macro only work with gcc 5.1?

Body:
Ok, I think I've figured out why I can't get g++ to generate the cxx11 signature (new ABI).

If I run g++ with the -v option:

g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/opt/rh/devtoolset-6/root/usr/libexec/gcc/x86_64-redhat-linux/6.3.1/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --enable-bootstrap --enable-languages=c,c++,fortran,lto --prefix=/opt/rh/devtoolset-6/root/usr --mandir=/opt/rh/devtoolset-6/root/usr/share/man --infodir=/opt/rh/devtoolset-6/root/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --enable-plugin --with-linker-hash-style=gnu --enable-initfini-array --disable-libgcj --with-default-libstdcxx-abi=gcc4-compatible --with-isl=/builddir/build/BUILD/gcc-6.3.1-20170216/obj-x86_64-redhat-linux/isl-install --enable-libmpx --enable-gnu-indirect-function --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 6.3.1 20170216 (Red Hat 6.3.1-3) (GCC)

Note the following under the "configured with" field

--with-default-libstdcxx-abi=gcc4-compatible

What I believe this means is that the devtoolset-6 version of g++ is built with the old style ABI "baked in", and it therefore doesn't respond to the _GLIBCXX_USE_CXX11_ABI macro.

According to this link: https://gcc.gnu.org/onlinedocs/libstdc++/manual/configure.html

--with-default-libstdcxx-abi=OPTION
Set the default value for the _GLIBCXX_USE_CXX11_ABI macro (see Macros). The default is OPTION=new which sets the macro to 1, use OPTION=gcc4-compatible to set it to 0. This option does not change the library ABI.

It would seem to only change the default value of _GLIBCXX_USE_CXX11_ABI, but in my attempts setting _GLIBCXX_USE_CXX11_ABI doesn't have any effect.

Not positive of this, but it's my working theory for now.  Any additional insight is appreciated.


问:
separate first word in a string in python re
I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:

```<code>for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)
</code>```

Here are some examples of the strings:

```<code>Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,
</code>```

what I need is:

```<code>Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,
</code>```

what I am getting is:

```<code>Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a
</code>```

答:
Requirements are not clear enough, hence some ambiguous use cases. But looking at your own code and subject string together, I'd offer such Regular Expression:

```<code>\(\w+\)_(\w+)|_(\w+)
</code>```

RegEx live demo

Python live demo

Body:
I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:

for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)

Here are some examples of the strings:

Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,

what I need is:

Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,

what I am getting is:

Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a

Body:
Requirements are not clear enough, hence some ambiguous use cases. But looking at your own code and subject string together, I'd offer such Regular Expression:

\(\w+\)_(\w+)|_(\w+)

RegEx live demo

Python live demo


问:
Delete numbers and punctuation with preg_replace PHP
I want to erase numbers and punctuation (full stops, commas, etc) of a string in PHP, I tried this for example

```<code><?php
 $str = "Hello, lorem ipsum, dolor sit amet. Adipiscing90 elit. 1234567890. ";
 $text = preg_replace('/\d+/u', '', $str);
 echo $text;
?>
</code>```

This only delete numbers but no punctuation resulting this:

Hello, lorem ipsum, dolor sit amet. Adipiscing elit. .

I want to get like this, with no commas, full stops, etc:

Hello lorem ipsum dolor sit amet Adipiscing elit

How can I modify preg_replace function?

I would like some help.

答:
There are [:punct:] POSIX character class and \p{P} Unicode property/category class to match punctuation, but note that they are not equal. [:punct:] can also match all symbols, and in fact, [:punct:] = [\p{P}\p{S}].

So, based on your requirements, either use

```<code>preg_replace('/[\d\p{P}]+/u', '', $str)
</code>```

or

```<code>preg_replace('/[\d[:punct:]]+/u', '', $str)
</code>```

You may check which characters belong to each category at FileFormat.info.

Body:
I want to erase numbers and punctuation (full stops, commas, etc) of a string in PHP, I tried this for example

<?php
 $str = "Hello, lorem ipsum, dolor sit amet. Adipiscing90 elit. 1234567890. ";
 $text = preg_replace('/\d+/u', '', $str);
 echo $text;
?>

This only delete numbers but no punctuation resulting this:

Hello, lorem ipsum, dolor sit amet. Adipiscing elit. .

I want to get like this, with no commas, full stops, etc:

Hello lorem ipsum dolor sit amet Adipiscing elit

How can I modify preg_replace function?

I would like some help.

Body:
There are [:punct:] POSIX character class and \p{P} Unicode property/category class to match punctuation, but note that they are not equal. [:punct:] can also match all symbols, and in fact, [:punct:] = [\p{P}\p{S}].

So, based on your requirements, either use

preg_replace('/[\d\p{P}]+/u', '', $str)

or

preg_replace('/[\d[:punct:]]+/u', '', $str)

You may check which characters belong to each category at FileFormat.info.


问:
Select a random li using jQuery
I'm trying to select a random li element with jQuery and change its class.
Most of the time it will change the class on one but other times two, sometimes none at all. I am using the code below to get my random li,

```<code>var selection = $('#options li');
var rand = Math.floor((Math.random() * selection.length) + 1);
$('#options li:eq('+ (rand) +')').addClass('selected');
</code>```

I have 3 li's.

答:
selection should contain an array of li's. I'd just grab a random one of those instead of using an index selector:

```<code>$(document).ready(function() {
  const selection = $('li');
  const randLi = selection[Math.floor(Math.random() * selection.length)];
  $(randLi).addClass('selected');
});
</code>```

Here's a working fiddle to demonstrate.

...and here's one more that uses the above code to select a random li every half second so you can more easily see the random selection.

Title: Select a random li using jQuery

Body:
I'm trying to select a random li element with jQuery and change its class.
Most of the time it will change the class on one but other times two, sometimes none at all. I am using the code below to get my random li,

var selection = $('#options li');
var rand = Math.floor((Math.random() * selection.length) + 1);
$('#options li:eq('+ (rand) +')').addClass('selected');

I have 3 li's.

Body:
selection should contain an array of li's. I'd just grab a random one of those instead of using an index selector:

$(document).ready(function() {
  const selection = $('li');
  const randLi = selection[Math.floor(Math.random() * selection.length)];
  $(randLi).addClass('selected');
});

Here's a working fiddle to demonstrate.

...and here's one more that uses the above code to select a random li every half second so you can more easily see the random selection.


问:
Two times inherited from a generic class
I have two class

```<code>public class Singleton<T> : MonoBehaviour   where T : Component
{
    protected static T _instance;

    public static T Instance
    {
        get
        {
            return _instance;
        }
    }
}
</code>```

and

```<code>public class GameManager : Singleton<GameManager>
{
    // Lots of Methods and Properties...
}
</code>```

I want to create 3. class derived from GameManager for example ShooterGameManager. I can create ShooterGameManager with

```<code>public class ShooterGameManager : GameManager
{}
</code>```

but Instance is still GameManager !!!,
I tried something like to added extra class definition with generic class.

```<code>public class GameManager<T> : Singleton<T> where T : Component
{}
</code>```

but this time there are 2 completely different classes available, nothing inherited from GameManager. What should I do ???

答:
What should I do ???

You should delete the Singleton base class utterly and forget that you ever wrote such a thing.  It does nothing helpful and causes you pain, so why are you using it?

Then write:

```<code>abstract public class GameManager : MonoBehaviour
{
    protected GameManager() { whatever }
    // Lots of Methods and Properties...
}

public sealed class ShooterGameManager : GameManager
{
  private ShooterGameManager() { whatever }
  private static ShooterGameManager instance = new ShooterGameManager();
  public static ShooterGameManager Instance { get { return instance; } }
}
</code>```

Done.  Making the base class a singleton causes you pain and saves you from typing exactly two lines of code. Whether a derived class is a singleton or not is an implementation detail of that derived class; don't force that upon your derived class authors.

Body:
I have two class

public class Singleton<T> : MonoBehaviour   where T : Component
{
    protected static T _instance;

    public static T Instance
    {
        get
        {
            return _instance;
        }
    }
}

and

public class GameManager : Singleton<GameManager>
{
    // Lots of Methods and Properties...
}

I want to create 3. class derived from GameManager for example ShooterGameManager. I can create ShooterGameManager with

public class ShooterGameManager : GameManager
{}

but Instance is still GameManager !!!,
I tried something like to added extra class definition with generic class.

public class GameManager<T> : Singleton<T> where T : Component
{}

but this time there are 2 completely different classes available, nothing inherited from GameManager. What should I do ???

Body:
What should I do ???

You should delete the Singleton base class utterly and forget that you ever wrote such a thing.  It does nothing helpful and causes you pain, so why are you using it?

Then write:

abstract public class GameManager : MonoBehaviour
{
    protected GameManager() { whatever }
    // Lots of Methods and Properties...
}

public sealed class ShooterGameManager : GameManager
{
  private ShooterGameManager() { whatever }
  private static ShooterGameManager instance = new ShooterGameManager();
  public static ShooterGameManager Instance { get { return instance; } }
}

Done.  Making the base class a singleton causes you pain and saves you from typing exactly two lines of code. Whether a derived class is a singleton or not is an implementation detail of that derived class; don't force that upon your derived class authors.


问:
Android Studio 3.0 Unable to merge dex
Just Updated android studio from 2.3.3 to 3.0 now I am having the error

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
</code>```

Here is my gradle file:

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

android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
    applicationId "d91.compassacademy"
    minSdkVersion 19
    targetSdkVersion 25
    versionCode 3
    versionName "1.0"

    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable true
    }
}
}

repositories {
    mavenCentral()
    google()
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:multidex:1.0.2'

compile('com.google.api-client:google-api-client-android:1.22.0') {
    exclude group: 'org.apache.httpcomponents'
}
compile 'pub.devrel:easypermissions:0.2.1'
compile project(path: ':mapviewpager')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'

})
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.android.support:recyclerview-v7:25.4.0'
compile 'com.android.support:cardview-v7:25.4.0'
compile 'com.google.firebase:firebase-database:11.4.2'
compile 'com.google.android.gms:play-services-auth:11.4.2'
compile 'com.google.android.gms:play-services-places:11.4.2'
compile 'com.google.android.gms:play-services:11.4.2'
compile 'com.google.firebase:firebase-storage:11.4.2'
compile 'com.google.firebase:firebase-auth:11.4.2'
compile 'com.firebaseui:firebase-ui-database:1.1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.theartofdev.edmodo:android-image-cropper:2.3.1'
compile 'com.roughike:bottom-bar:2.1.1'
compile 'com.android.support:support-v4:25.4.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.android.support:support-vector-drawable:25.4.0'
compile 'pub.devrel:easypermissions:0.2.1'
compile 'com.google.code.findbugs:jsr305:2.0.1'
compile 'com.jakewharton:butterknife:8.4.0'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.android.support:multidex:1.0.2'
compile 'com.android.support.constraint:constraint-layout:1.1.0-beta3'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

答:
I looked up:

```<code>Error:Execution failed for task ':memDicez:transformDexArchiveWithExternalLibsDexMergerForDebug'.
</code>```

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

yesterday and found nothing usefull,

my issue is now solved,

this method might get you towards a solution (it worked for me, no guarantee it works for you)

I had:

```<code>android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "(my secret applicationId)"
        minSdkVersion 21
        targetSdkVersion 25
        multiDexEnabled true
    }

    ...

}
</code>```

and

```<code>dependencies {
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'ch.acra:acra:4.9.2'
    //compile 'com.google.android.gms:play-services-auth:9.0.0'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.koushikdutta.ion:ion:2.+'
    compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
}
</code>```

and when I changed:

```<code>        minSdkVersion 21
</code>```

to

```<code>        minSdkVersion 16
</code>```

I got a more descriptive error message which did give solutions via google/stack overflow.

in my case

```<code>compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
</code>```

should be changed to

```<code>compile('com.googlecode.json-simple:json-simple:1.1.1') {
    exclude group: 'org.hamcrest', module: 'hamcrest-core'
}
</code>```

You can change the minSdkVersion back to a higher value later on but decreasing it seems to give a more descriptive (or more googleable) problem (and solution)

cheers,

S.

Title: Android Studio 3.0 Unable to merge dex

Body:
Just Updated android studio from 2.3.3 to 3.0 now I am having the error

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Here is my gradle file:

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
    applicationId "d91.compassacademy"
    minSdkVersion 19
    targetSdkVersion 25
    versionCode 3
    versionName "1.0"

    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable true
    }
}
}

repositories {
    mavenCentral()
    google()
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:multidex:1.0.2'

compile('com.google.api-client:google-api-client-android:1.22.0') {
    exclude group: 'org.apache.httpcomponents'
}
compile 'pub.devrel:easypermissions:0.2.1'
compile project(path: ':mapviewpager')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'

})
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.android.support:recyclerview-v7:25.4.0'
compile 'com.android.support:cardview-v7:25.4.0'
compile 'com.google.firebase:firebase-database:11.4.2'
compile 'com.google.android.gms:play-services-auth:11.4.2'
compile 'com.google.android.gms:play-services-places:11.4.2'
compile 'com.google.android.gms:play-services:11.4.2'
compile 'com.google.firebase:firebase-storage:11.4.2'
compile 'com.google.firebase:firebase-auth:11.4.2'
compile 'com.firebaseui:firebase-ui-database:1.1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.theartofdev.edmodo:android-image-cropper:2.3.1'
compile 'com.roughike:bottom-bar:2.1.1'
compile 'com.android.support:support-v4:25.4.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.android.support:support-vector-drawable:25.4.0'
compile 'pub.devrel:easypermissions:0.2.1'
compile 'com.google.code.findbugs:jsr305:2.0.1'
compile 'com.jakewharton:butterknife:8.4.0'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.android.support:multidex:1.0.2'
compile 'com.android.support.constraint:constraint-layout:1.1.0-beta3'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

Body:
I looked up:

Error:Execution failed for task ':memDicez:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

yesterday and found nothing usefull,

my issue is now solved,

this method might get you towards a solution (it worked for me, no guarantee it works for you)

I had:

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "(my secret applicationId)"
        minSdkVersion 21
        targetSdkVersion 25
        multiDexEnabled true
    }

    ...

}

and

dependencies {
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'ch.acra:acra:4.9.2'
    //compile 'com.google.android.gms:play-services-auth:9.0.0'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.koushikdutta.ion:ion:2.+'
    compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
}

and when I changed:

        minSdkVersion 21

to

        minSdkVersion 16

I got a more descriptive error message which did give solutions via google/stack overflow.

in my case

compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'

should be changed to

compile('com.googlecode.json-simple:json-simple:1.1.1') {
    exclude group: 'org.hamcrest', module: 'hamcrest-core'
}

You can change the minSdkVersion back to a higher value later on but decreasing it seems to give a more descriptive (or more googleable) problem (and solution)

cheers,

S.


问:
python key in dict.keys() performance for large dictionaries
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

```<code>dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]
</code>```

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

答:
Step 1: we transform the code using the temp_list into a single expression (I assume temp_list isn't needed outside this code), by using addition instead of the append method. Also, we don't need to use dict.keys() explicitly, as others mentioned (and in fact it wastes a huge amount of time).

```<code>for value in value_list:
   if value.key in dict:
      dict[value.key] = dict[value.key] + [value.val]
   else:
      dict[value.key] = [value.val]
</code>```

Step 2: Transform the assignments-to-the-same-location by using the conditional expression syntax.

```<code>for value in value_list:
   dict[value.key] = dict[value.key] + [value.val] if value.key in dict else [value.val]
</code>```

Step 3: Appending or prepending an empty list has no effect on the value of a list, so we can insert that, and then factor out the common 'addition' of the value.

```<code>for value in value_list:
   dict[value.key] = (dict[value.key] if value.key in dict else []) + [value.val]
</code>```

Step 4: Recognize that the dict has built-in functionality for providing a 'default' value when the key is absent:

```<code>for value in value_list:
   dict[value.key] = dict.get(value.key, []) + [value.val]
</code>```

Step 5: Instead of getting a value, modifying it and setting it back, we can use .setdefault to give us the current contents (or set them up if not already there), and then switch back to using .append to modify the list:

```<code>for value in value_list:
   dict.setdefault(value.key, []).append(value.val)
</code>```

(I mean... I could have just looked at it and thought for a bit and arrived at this, but seeing each step makes it clearer where we're going...)

Body:
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

Body:
Step 1: we transform the code using the temp_list into a single expression (I assume temp_list isn't needed outside this code), by using addition instead of the append method. Also, we don't need to use dict.keys() explicitly, as others mentioned (and in fact it wastes a huge amount of time).

for value in value_list:
   if value.key in dict:
      dict[value.key] = dict[value.key] + [value.val]
   else:
      dict[value.key] = [value.val]

Step 2: Transform the assignments-to-the-same-location by using the conditional expression syntax.

for value in value_list:
   dict[value.key] = dict[value.key] + [value.val] if value.key in dict else [value.val]

Step 3: Appending or prepending an empty list has no effect on the value of a list, so we can insert that, and then factor out the common 'addition' of the value.

for value in value_list:
   dict[value.key] = (dict[value.key] if value.key in dict else []) + [value.val]

Step 4: Recognize that the dict has built-in functionality for providing a 'default' value when the key is absent:

for value in value_list:
   dict[value.key] = dict.get(value.key, []) + [value.val]

Step 5: Instead of getting a value, modifying it and setting it back, we can use .setdefault to give us the current contents (or set them up if not already there), and then switch back to using .append to modify the list:

for value in value_list:
   dict.setdefault(value.key, []).append(value.val)

(I mean... I could have just looked at it and thought for a bit and arrived at this, but seeing each step makes it clearer where we're going...)


答:
Maybe I am over-simplifying your question, but using percentages as width works when the browser window size is changed.  You can click "Run code snippet" to see it in action.

#menu,#content {
  display: inline-block;
  vertical-align: top;
}

#menu {
  width: 20%;
  background-color: #eee;
}

#content {
  width: 79%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menu">
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li>Item four</li>
<li>Item five</li>
</ul>
</div>
<div id="content">
<p>This is the content that shows up to the right of the menu on the left.  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>
</div></code>```

Body:
You must know that this question is very specific to my situation and I would really love to hear what you guys have to say!

So, I am trying to have a page on my website where on the left side there is a menu and on the right side there is the content. I gave the div that contains the menu a width of 200px, but my question is, how do I place the div that contains the content on the right of the side-menu? Because keep in mind that I want the div that contains the content to expand or shrink as the browsers window size changes.

First scenario:
I floated the side-menu to the left and I also floated the div containing the content to the left, but when I give it a width of 100% it goes under the side-menu.

Second scenario:
I floated the side-menu to the left and I placed the div containing the content to the right of the side menu by giving it a margin-left of 250px.

But in both of these scenarios the div containing the content doesn't fit the browser's window, meaning if i resized the browser that div won't expand, it  goes under the side-menu.

Question 1:
How do i give the div containing the content a non-fixed width so it can expand or shrink when the browser's window is resized. The side-menu will still be there even when the browser window size shrinks or expands.

Question 2: How do I place the div that contains the content next to the side menu? Do I float it? Do I give it a margin-left? Do I absolutely position it?

Please tell me how to place that div and how to make it expand or shrink and fit different browser window size.

Here is a screenshot of it: (click on the link)

side menu on the left and content on the right

Body:
Maybe I am over-simplifying your question, but using percentages as width works when the browser window size is changed.  You can click "Run code snippet" to see it in action.

#menu,#content {
  display: inline-block;
  vertical-align: top;
}

#menu {
  width: 20%;
  background-color: #eee;
}

#content {
  width: 79%;
}

<div id="menu">
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li>Item four</li>
<li>Item five</li>
</ul>
</div>
<div id="content">
<p>This is the content that shows up to the right of the menu on the left.  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>
</div>


问:
django channels redis multiple consumers receive message a different times ensured?
Does this need to be implemented or is it in Channels already?

If I have a channel group with multiple consumers subscribed to it and one consumer is sent the message is the message lost to the rest of the consumers or does the message persist until all consumers see the message?

Or does the message persist for time until time is expired regardless of consumers seeing it or not?

答:
The Group objects manages delivery to all consumers (where possible) and message expiry. But note that delivery is not ensured.

From the documentation:

Channels implements this abstraction as a core concept called Groups ...

[Groups] also automatically manage expiry of the group members - when the channel starts having messages expire on it due to non-consumption, we go in and remove it from all the groups it’s in as well ...

One thing channels do not do, however, is guarantee delivery. If you need certainty that tasks will complete, use a system designed for this with retries and persistence (e.g. Celery)


问:
Adding Home button in html page
In my webapplication I am trying to add home button in all the sub pages which on clicking will trigger ActionResult Index()
Any suggestions?

I have simply added a button in my Sub page DetailsForm. Which is next to the submit button. After user is done saving user can click on home button to directly got to the Index.cshtml. Avoiding any Browser back button.
Below code definitely doesn't work for me!

```<code>  <input type="button" class="btn btn-lg btn-success" onclick="location.href='index.cshtml';" value="Home" />
</code>```

答:
In MVC, you navigate to action methods in controls, not to views so your location.href='index.cshtml' cannot work.

Use an  element to redirect (and style it to look like a button if that's what you want), for example

```<code>@Html.ActionLink("Home", "Index", "Home", null, new { @class = "btn btn-lg btn-success" }
</code>```

Title: Adding Home button in html page

Body:
In my webapplication I am trying to add home button in all the sub pages which on clicking will trigger ActionResult Index()
Any suggestions?

I have simply added a button in my Sub page DetailsForm. Which is next to the submit button. After user is done saving user can click on home button to directly got to the Index.cshtml. Avoiding any Browser back button.
Below code definitely doesn't work for me!

  <input type="button" class="btn btn-lg btn-success" onclick="location.href='index.cshtml';" value="Home" />

Body:
In MVC, you navigate to action methods in controls, not to views so your location.href='index.cshtml' cannot work.

Use an <a> element to redirect (and style it to look like a button if that's what you want), for example

@Html.ActionLink("Home", "Index", "Home", null, new { @class = "btn btn-lg btn-success" }


问:
Highlighting Text using javascript not working
I'd like to highlight or change the background color of all p elements to yellow but it won't work.

I would also like my button be a toggle to highlight and highlight the paragraph elements. Is that possible? Help would be appreciated!

```<code> <html>
<head>
  <script type="text/javascript" src="task2.js"></script>
  <style>
  #poem {
    padding: 10px;
    margin-bottom: 10px;
    color: blue;
    font-size: 1.25em;
    font-family: sans-serif;
    background-color: silver;
    border: 1px dashed black;
    width: 30%;
  }
  </style>
</head>
<body>
<div id="poem">
<h2> How Many, How Much  </h2>
<h4> by Shel Silverstein </h4>
<p> How many slams in an old screen door? </p>
<p> Depends how loud you shut it.</p>
<p> How many slices in a bread?</p>
<p> Depends how thin you cut it.</p>
<p> How much good inside a day? </p>
<p> Depends how good you live 'em. </p>
<p> How much love inside a friend? </p>
<p> Depends how much you give 'em. </p>
</div>

<button id="yellow">Click to Highlight </button>
</body>
</html>
</code>```

here is my external js file

```<code>window.onload = function()
{
  document.getElementById("yellow").addEventListener("click", makeYellow);
}

function makeYellow() {
var paragraph = document.getElementsbyTagName("p");
paragraph.style.color ="yellow";
}
</code>```

答:
Try this:</p>

```<code>document.getElementById("yellow").addEventListener("click", myFunction);

function myFunction() {
    var x = document.getElementById("poem");
    if (x.style.color == "blue") {
        x.style.color == "yellow";
    } else if (x.style.color == "yellow") {
        x.style.color == "blue";
    }
}
</code>```

Body:
I'd like to highlight or change the background color of all p elements to yellow but it won't work.

I would also like my button be a toggle to highlight and highlight the paragraph elements. Is that possible? Help would be appreciated!

 How Many, How Much

 by Shel Silverstein

 How many slams in an old screen door?

 Depends how loud you shut it.

 How many slices in a bread?

 Depends how thin you cut it.

 How much good inside a day?

 Depends how good you live 'em.

 How much love inside a friend?

 Depends how much you give 'em.

<button id="yellow">Click to Highlight </button>

here is my external js file

window.onload = function()
{
  document.getElementById("yellow").addEventListener("click", makeYellow);
}

function makeYellow() {
var paragraph = document.getElementsbyTagName("p");
paragraph.style.color ="yellow";
}

Body:
Try this:

document.getElementById("yellow").addEventListener("click", myFunction);

function myFunction() {
    var x = document.getElementById("poem");
    if (x.style.color == "blue") {
        x.style.color == "yellow";
    } else if (x.style.color == "yellow") {
        x.style.color == "blue";
    }
}


问:
How to copy/paste text (github's url) in Bash in Windows 10?
I'm using Windows 10.

I can cut/copy/paste in cmd or shell but i can't do that with Bash. So, I must type url of github if I want to clone something from there

Almost of guides (Dr. Google) also say: Right click -> Properties -> Options -> tick Edit Quick Mode

But I can't do because I can't find out "Quick Edit Mode" or something like that.

Please help me.

Thanks,

Bash's Properties

答:
using your keyboard, you can hold down [Shift] and then hit the [Insert] key.
[Shift]+[Insert]

EDIT: If this does not help, you may find a previous post useful: Copy Paste in Bash on Ubuntu on Windows


问:
Will using LINQ to SQL help prevent SQL injection
I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?

This example is creating the user account.

```<code>Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
profile.UserName = userName;
profile.Password = password;
profile.EmailAddress = email;
profile.QuestionID = qID;
profile.QuestionResponse = securityAnswer;
profile.LastModDt = DateTime.Now;
profile.LastModBy = "web";
context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
context.SubmitChanges();
</code>```

This example is changing the password

```<code>   MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
   var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
   mProfileRecord.Password = sNewPassword;
   dc.SubmitChanges();
</code>```

Are these safe? Does LINQ parameterize the SQL it generates automatically?

答:
Yes, LINQ will help stop SQL injection.

LINQ to SQL passes all data to the
  database via SQL parameters. So,
  although the SQL query is composed
  dynamically, the values are substitued
  server side through parameters
  safeguarding against the most common
  cause of SQL injection attacks.

Also, see Eliminate SQL Injection Attacks Painlessly with LINQ  for some info.

Body:
I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?

This example is creating the user account.

Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
profile.UserName = userName;
profile.Password = password;
profile.EmailAddress = email;
profile.QuestionID = qID;
profile.QuestionResponse = securityAnswer;
profile.LastModDt = DateTime.Now;
profile.LastModBy = "web";
context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
context.SubmitChanges();

This example is changing the password

   MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
   var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
   mProfileRecord.Password = sNewPassword;
   dc.SubmitChanges();

Are these safe? Does LINQ parameterize the SQL it generates automatically?

OwnerDisplayName: Galwegian


问:
'Access Denied' accessing SharePoint Online Site Collection with App Permission
I have created an App Principal in SharePoint Online using the Site Collections /AppRegNew.aspx page and then used page /appInv.aspx to grant that App Principal FullControl of the site collection using the following permission XML:

```<code><AppPermissionRequests>
  <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl"/>
</AppPermissionRequests>
</code>```

However, when I try to access a list in that site collection using CSOM and c# (using TokenHelper.cs), I get error:

```<code>'Access denied. You do not have permission to perform this action or access this resource.'
</code>```

I have another App Principal which I had granted Tenant Admin permission for testing - if I use the ClientID and ClientSecret associated with that App Principal, my code runs properly (I am just reading a few list items for testing)

Am I doing something wrong with the AppPermissionRequests XML? is there some other step I am missing?  I could use the Tenant Admin App Principal, but I want to do this the 'right' way - and from my research, it looks like it should be working with the SiteCollection FullControl permission.

Example code I am using to attempt access:

```<code>        Uri siteUri = new Uri("https://MyCompany.sharepoint.com/sites/johntest");
        string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
        string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken;
        using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken))
        {

            Web thisWeb = context.Web;
            context.Load(thisWeb);
            context.ExecuteQuery();
            List roomsList = context.Web.Lists.GetByTitle("Rooms");
            context.Load(roomsList);
            context.ExecuteQuery();
            Console.WriteLine("List retrieved");
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>SomeValue</Value></Eq></Where></Query></View>";
            ListItemCollection listItems = roomsList.GetItems(camlQuery);
            context.Load(listItems);
            context.ExecuteQuery();
            Console.WriteLine("Query succeeded");
        }
</code>```

答:
Because you are accessing the resource with an application login, by using TokenHelper.GetAppOnlyAccessToken, you must add the AllowAppOnlyPolicy="true" attribute to the AppPermissionRequest.

Friendly reminder, the client id and client secret should be treated like a user name and password when the AllowAppOnlyPolicy attribute is true, especially if the application is highly privileged, such as tenant admin or full control over a site collection.  In any case, the client secret should be guarded, but it has to be combined with an authenticated user, if AllowAppOnlyPolicy is false.

Body:
I have created an App Principal in SharePoint Online using the Site Collections /AppRegNew.aspx page and then used page /appInv.aspx to grant that App Principal FullControl of the site collection using the following permission XML:

<AppPermissionRequests>
  <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl"/>
</AppPermissionRequests>

However, when I try to access a list in that site collection using CSOM and c# (using TokenHelper.cs), I get error:

'Access denied. You do not have permission to perform this action or access this resource.'

I have another App Principal which I had granted Tenant Admin permission for testing - if I use the ClientID and ClientSecret associated with that App Principal, my code runs properly (I am just reading a few list items for testing)

Am I doing something wrong with the AppPermissionRequests XML? is there some other step I am missing?  I could use the Tenant Admin App Principal, but I want to do this the 'right' way - and from my research, it looks like it should be working with the SiteCollection FullControl permission.

Example code I am using to attempt access:

        Uri siteUri = new Uri("https://MyCompany.sharepoint.com/sites/johntest");
        string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
        string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken;
        using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken))
        {

            Web thisWeb = context.Web;
            context.Load(thisWeb);
            context.ExecuteQuery();
            List roomsList = context.Web.Lists.GetByTitle("Rooms");
            context.Load(roomsList);
            context.ExecuteQuery();
            Console.WriteLine("List retrieved");
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>SomeValue</Value></Eq></Where></Query></View>";
            ListItemCollection listItems = roomsList.GetItems(camlQuery);
            context.Load(listItems);
            context.ExecuteQuery();
            Console.WriteLine("Query succeeded");
        }


问:
Fold with closure that returns a Result
I'm using the regex crate to find some text with this regex:

```<code>lazy_static! {
    static ref FIND_STEPS_RE: Regex =
        Regex::new(r"my regex").unwrap();
}
</code>```

I want to find all possible captures and iterate over them:

```<code>FIND_STEPS_RE.captures_iter(script_slice)
</code>```

Each captured element consists of 2 values: an operation and a number. For example, the output could be:

[("+", "10"), ("-", "20"), ("*", "2")]
```

<p>I want to iterate over it, parse the numbers and apply the operation.</p>

<p>I tried:</p>

```let e = FIND_STEPS_RE.captures_iter(script_slice)
    .fold(0, |sum, value| apply_decoding_step)?;
```

<p>where <code>apply_decoding_step</code> is:</p>

```fn apply_decoding_step(sum: i32, capture: regex::Captures<>) -> Result<i32> {
    let number = parse_number(&capture[2])?;

    match  &capture[1] {
        "+" => Ok(s + number),
        "-" => Ok(s - number),
        "*" => Ok(s * number),
        "/" => Ok(s / number),
        _ => bail!("Unknown step operator"),
    }
}
```

<p>But I got this error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0271]: type mismatch resolving `<fn(i32, regex::Captures<'_>) -> std::result::Result<i32, Error> {apply_decoding_step} as std::ops::FnOnce<(i32, regex::Captures<'_>)>>::Output == i32`
   --> src/main.rs:122:10
    |
122 |         .fold(seed, apply_decoding_step);
    |          ^^^^ expected enum `std::result::Result`, found i32
    |
    = note: expected type `std::result::Result<i32, Error>`
               found type `i32`
</code>```

I assume this is because I'm trying to fold a Result into a i32, but since I need to parse the second capture value and also need that otherwise case in my match, how can I fix that?

答:
You could extend Iterator by a custom fold_result function like this (using the full path to Result because it seems you're importing a Result type generated by error_chain):

```<code>trait IterExtFoldResult: Iterator + Sized {
    #[inline]
    fn fold_result<B, F, E>(self, mut init: B, mut f: F) -> ::std::result::Result<B, E>
    where
        F: FnMut(B, Self::Item) -> ::std::result::Result<B, E>,
    {
        for i in self {
            init = f(init, i)?;
        }
        Ok(init)
    }
}
impl<I: Iterator> IterExtFoldResult for I {}
</code>```

and use it like .fold_result(0, apply_decoding_step).

That way fold aborts when f returned an error; if you forward the error in f the compiler might or might not optimize to an early return.

Full example in playground

Title: Fold with closure that returns a Result

Body:
I'm using the regex crate to find some text with this regex:

lazy_static! {
    static ref FIND_STEPS_RE: Regex =
        Regex::new(r"my regex").unwrap();
}

I want to find all possible captures and iterate over them:

FIND_STEPS_RE.captures_iter(script_slice)

Each captured element consists of 2 values: an operation and a number. For example, the output could be:

[("+", "10"), ("-", "20"), ("*", "2")]

I want to iterate over it, parse the numbers and apply the operation.

I tried:

let e = FIND_STEPS_RE.captures_iter(script_slice)
    .fold(0, |sum, value| apply_decoding_step)?;

where apply_decoding_step is:

fn apply_decoding_step(sum: i32, capture: regex::Captures<>) -> Result<i32> {
    let number = parse_number(&capture[2])?;

    match  &capture[1] {
        "+" => Ok(s + number),
        "-" => Ok(s - number),
        "*" => Ok(s * number),
        "/" => Ok(s / number),
        _ => bail!("Unknown step operator"),
    }
}

But I got this error:

error[E0271]: type mismatch resolving `<fn(i32, regex::Captures<'_>) -> std::result::Result<i32, Error> {apply_decoding_step} as std::ops::FnOnce<(i32, regex::Captures<'_>)>>::Output == i32`
   --> src/main.rs:122:10
    |
122 |         .fold(seed, apply_decoding_step);
    |          ^^^^ expected enum `std::result::Result`, found i32
    |
    = note: expected type `std::result::Result<i32, Error>`
               found type `i32`

I assume this is because I'm trying to fold a Result into a i32, but since I need to parse the second capture value and also need that otherwise case in my match, how can I fix that?

Body:
You could extend Iterator by a custom fold_result function like this (using the full path to Result because it seems you're importing a Result type generated by error_chain):

trait IterExtFoldResult: Iterator + Sized {
    #[inline]
    fn fold_result<B, F, E>(self, mut init: B, mut f: F) -> ::std::result::Result<B, E>
    where
        F: FnMut(B, Self::Item) -> ::std::result::Result<B, E>,
    {
        for i in self {
            init = f(init, i)?;
        }
        Ok(init)
    }
}
impl<I: Iterator> IterExtFoldResult for I {}

and use it like .fold_result(0, apply_decoding_step).

That way fold aborts when f returned an error; if you forward the error in f the compiler might or might not optimize to an early return.

Full example in playground


问:
Store config settings for a .NET DLL (not EXE or Web)
I have a .NET 4 class library project, which is used by multiple web projects. In this class library I need to get a DB connection string and it needs to be the same for all the web projects. Currently I've got it as a setting in each web.config file, but this is not ideal. Is there any way I can have that configuration stored with the DLL, but still allow it to be modified at runtime (ie. hardcoding the connection string is out)?

App.config seems to be generally ignored for a DLL, even though it does get renamed to assemblyname.dll.config and copied to the bin directory for the web. I tried making it an "application setting" (ie. using the auto-generated class derived from System.Configuration.ApplicationSettingsBase) and this appeared to work, but changing the value in the DLL .config file at runtime had no effect, so I suspect it's really just using the hardcoded default value of the setting.

答: You can store the setting in the Registry Database if it should be the same for all programs on the machine using your library.</p>