问:
Configuring datasource with websphere 8.5.5.0 and Spring?
I was trying to figure it out a problem about connection using websphere 8.5  and spring  . I read some questions about in this site and others but nothing seems to work.

In websphere we HAVE TO set the jndi name of the datasource as jdbc/connection0.

Than I'm trying to set the connection in the web application using the web.xml and the spring configuration files.

```<code><resource-ref >
    <description>connection0</description>
    <res-ref-name>connection0</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    <mapped-name>connection0</mapped-name>
</resource-ref>
</code>```

than in the spring-datasource.xml we try to reference the connection:

```<code>        <property name="jndiName" value="jdbc/connection0"/>
        <property name="lookupOnStartup" value="false"/>
        <property name="cache" value="true"/>
        <property name="proxyInterface" value="javax.sql.DataSource"/>
  </bean>
</code>```

i also added the file ibm-web-bnd.xml to refer to the datasource(the file is under the web-inf directory):

< ?xml version="1.0" encoding="UTF-8"?>
  < web-bnd
     xmlns="http://websphere.ibm.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee >http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
     version="1.0" >

we produce an EAR file and we succefully to deploy on the application server.
But when we try to access the database we receive an error this is the stacktrace:

[05/06/17 9.59.33:514 CEST] 0000006f SystemOut     O it.XXXX.sicurezza.db.DbHelper --> openJndiConnection: Not found initCtx.lookup("java:comp/env/url/connection0"). GRAVE!!
  [05/06/17 9.59.33:515 CEST] 0000006f SystemOut     O 05-06-2017 09:59:33 ERROR [WebContainer : 1] it.XXXX.sicurezza.taglib.allow.AllowTag - NamingManager.getURLContext cannot find the factory for this scheme: java
  javax.naming.ConfigurationException: NamingManager.getURLContext cannot find the factory for this scheme: java
    at com.ibm.ws.naming.util.Helpers.checkForUrlContext(Helpers.java:1631)
    at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:160)
    at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:179)
    at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)
    at javax.naming.InitialContext.lookup(InitialContext.java:423)
    at it.XXXX.sicurezza.db.DbHelper.openJndiConnection(DbHelper.java:78)
    at it.XXXX.sicurezza.db.DbHelper.openConnection(DbHelper.java:53)
    at it.XXXX.sicurezza.db.DaoManager.isInternalSecurityEnabled(DaoManager.java:108)
    at it.XXXX.sicurezza.manager.AbilitazioniManagerFactory.getAbilitazioniManager(AbilitazioniManagerFactory.java:29)
    at it.XXXX.sicurezza.taglib.allow.AllowTag.doStartTag(AllowTag.java:116)
    at com.ibm._jsp._editOrdineForm._jspx_meth_allow_allow_8(_editOrdineForm.java:7626)
    at com.ibm._jsp._editOrdineForm._jspx_meth_c_if_39(_editOrdineForm.java:7668)
    at com.ibm._jsp._editOrdineForm._jspService(_editOrdineForm.java:658)
    at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.wsspi.webcontainer.servlet.GenericServletWrapper.handleRequest(GenericServletWrapper.java:122)
    at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionServletWrapper.handleRequest(AbstractJSPExtensionServletWrapper.java:216)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:79)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1385)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:549)
    at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:1045)
    at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:527)
    at org.apache.struts.tiles.TilesUtilImpl.doInclude(TilesUtilImpl.java:99)
    at org.apache.struts.tiles.TilesUtil.doInclude(TilesUtil.java:135)
    at org.apache.struts.taglib.tiles.InsertTag.doInclude(InsertTag.java:760)
    at org.apache.struts.taglib.tiles.InsertTag$InsertHandler.doEndTag(InsertTag.java:892)
    at org.apache.struts.taglib.tiles.InsertTag.doEndTag(InsertTag.java:462)
    at com.ibm._jsp._layout._jspx_meth_tiles_insert_3(_layout.java:451)
    at com.ibm._jsp._layout._jspService(_layout.java:201)
    at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.wsspi.webcontainer.servlet.GenericServletWrapper.handleRequest(GenericServletWrapper.java:122)
    at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionServletWrapper.handleRequest(AbstractJSPExtensionServletWrapper.java:216)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:79)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1385)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:194)
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:240)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:258)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1174)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:901)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:79)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1385)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:194)
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:240)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:258)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1174)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:901)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:97)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:265)
    at it.XXXX.oppe0.allow.filter.AllowFilter.doFilter(AllowFilter.java:125)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:107)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:72)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:124)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at it.XXXX.oppe0.acegi.SessionExpirationFilter.doFilter(SessionExpirationFilter.java:76)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:149)
    at org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:98)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3761)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:976)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:459)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:526)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:312)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)

any suggestions for the setup?

答:
If you have an application that wants to look up the data source as

```<code>java:comp/env/url/connection0
</code>```

And your server configuration defines a data source with JNDI name of

```<code>jdbc/connection0
</code>```

Then your resource reference in web.xml should be

```<code><resource-ref >
    <description>connection0</description>
    <res-ref-name>url/connection0</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</code>```

and you can define the mapping in the bindings file (ibm-web-bnd.xml) as follows:

```<code><resource-ref name="url/connection0" binding-name="jdbc/connection0">
</resource-ref>
</code>```

Body:
I was trying to figure it out a problem about connection using websphere 8.5  and spring  . I read some questions about in this site and others but nothing seems to work.

In websphere we HAVE TO set the jndi name of the datasource as jdbc/connection0.

Than I'm trying to set the connection in the web application using the web.xml and the spring configuration files.

<resource-ref >
    <description>connection0</description>
    <res-ref-name>connection0</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    <mapped-name>connection0</mapped-name>
</resource-ref>

than in the spring-datasource.xml we try to reference the connection:

        <property name="jndiName" value="jdbc/connection0"/>
        <property name="lookupOnStartup" value="false"/>
        <property name="cache" value="true"/>
        <property name="proxyInterface" value="javax.sql.DataSource"/>
  </bean>

i also added the file ibm-web-bnd.xml to refer to the datasource(the file is under the web-inf directory):

< ?xml version="1.0" encoding="UTF-8"?>
  < web-bnd
     xmlns="http://websphere.ibm.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee >http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
     version="1.0" >

we produce an EAR file and we succefully to deploy on the application server.
But when we try to access the database we receive an error this is the stacktrace:

[05/06/17 9.59.33:514 CEST] 0000006f SystemOut     O it.XXXX.sicurezza.db.DbHelper --> openJndiConnection: Not found initCtx.lookup("java:comp/env/url/connection0"). GRAVE!!
  [05/06/17 9.59.33:515 CEST] 0000006f SystemOut     O 05-06-2017 09:59:33 ERROR [WebContainer : 1] it.XXXX.sicurezza.taglib.allow.AllowTag - NamingManager.getURLContext cannot find the factory for this scheme: java
  javax.naming.ConfigurationException: NamingManager.getURLContext cannot find the factory for this scheme: java
    at com.ibm.ws.naming.util.Helpers.checkForUrlContext(Helpers.java:1631)
    at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:160)
    at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:179)
    at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)
    at javax.naming.InitialContext.lookup(InitialContext.java:423)
    at it.XXXX.sicurezza.db.DbHelper.openJndiConnection(DbHelper.java:78)
    at it.XXXX.sicurezza.db.DbHelper.openConnection(DbHelper.java:53)
    at it.XXXX.sicurezza.db.DaoManager.isInternalSecurityEnabled(DaoManager.java:108)
    at it.XXXX.sicurezza.manager.AbilitazioniManagerFactory.getAbilitazioniManager(AbilitazioniManagerFactory.java:29)
    at it.XXXX.sicurezza.taglib.allow.AllowTag.doStartTag(AllowTag.java:116)
    at com.ibm._jsp._editOrdineForm._jspx_meth_allow_allow_8(_editOrdineForm.java:7626)
    at com.ibm._jsp._editOrdineForm._jspx_meth_c_if_39(_editOrdineForm.java:7668)
    at com.ibm._jsp._editOrdineForm._jspService(_editOrdineForm.java:658)
    at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.wsspi.webcontainer.servlet.GenericServletWrapper.handleRequest(GenericServletWrapper.java:122)
    at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionServletWrapper.handleRequest(AbstractJSPExtensionServletWrapper.java:216)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:79)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1385)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:549)
    at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:1045)
    at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:527)
    at org.apache.struts.tiles.TilesUtilImpl.doInclude(TilesUtilImpl.java:99)
    at org.apache.struts.tiles.TilesUtil.doInclude(TilesUtil.java:135)
    at org.apache.struts.taglib.tiles.InsertTag.doInclude(InsertTag.java:760)
    at org.apache.struts.taglib.tiles.InsertTag$InsertHandler.doEndTag(InsertTag.java:892)
    at org.apache.struts.taglib.tiles.InsertTag.doEndTag(InsertTag.java:462)
    at com.ibm._jsp._layout._jspx_meth_tiles_insert_3(_layout.java:451)
    at com.ibm._jsp._layout._jspService(_layout.java:201)
    at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.wsspi.webcontainer.servlet.GenericServletWrapper.handleRequest(GenericServletWrapper.java:122)
    at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionServletWrapper.handleRequest(AbstractJSPExtensionServletWrapper.java:216)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:79)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1385)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:194)
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:240)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:258)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1174)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:901)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:79)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1385)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:194)
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:240)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:258)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1174)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:901)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:97)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:265)
    at it.XXXX.oppe0.allow.filter.AllowFilter.doFilter(AllowFilter.java:125)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:107)
    at org.acegisecurity.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:72)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:124)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at it.XXXX.oppe0.acegi.SessionExpirationFilter.doFilter(SessionExpirationFilter.java:76)
    at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:149)
    at org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:98)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:928)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1025)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3761)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:976)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:459)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:526)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:312)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)

any suggestions for the setup?

Body:
If you have an application that wants to look up the data source as

java:comp/env/url/connection0

And your server configuration defines a data source with JNDI name of

jdbc/connection0

Then your resource reference in web.xml should be

<resource-ref >
    <description>connection0</description>
    <res-ref-name>url/connection0</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

and you can define the mapping in the bindings file (ibm-web-bnd.xml) as follows:

<resource-ref name="url/connection0" binding-name="jdbc/connection0">
</resource-ref>


来源: stackexchange

问:
How to get Element by Id from Another website
I would like to get the content of div by its ID from another site.

Let's say, I have a site and I want to get everything that is inside of div with the id of "mainbar" from this URL - https://stackoverflow.com/questions

Could you tell me, how to make it with native javascript or jquery?

Thanks in advance.

答:
If you have access to the other site and the Access-Control-Allow-Origin header is present, then jQuery can be used like this:

$.get('https://stackoverflow.com/questions').then(function (html) {
    // Success response
    var $mainbar = $(html).find('#mainbar');
    document.write($mainbar.html());
}, function () {
    // Error response
    document.write('Access denied');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Body:
If you have access to the other site and the Access-Control-Allow-Origin header is present, then jQuery can be used like this:

$.get('https://stackoverflow.com/questions').then(function (html) {
    // Success response
    var $mainbar = $(html).find('#mainbar');
    document.write($mainbar.html());
}, function () {
    // Error response
    document.write('Access denied');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
How to add hovering annotations to a plot
I am using matplotlib to make scatter plots. Each point on the scatter plot is associated with a named object. I would like to be able to see the name of an object when I hover my cursor over the point on the scatter plot associated with that object. In particular, it would be nice to be able to quickly see the names of the points that are outliers. The closest thing I have been able to find while searching here is the annotate command, but that appears to create a fixed label on the plot. Unfortunately, with the number of points that I have, the scatter plot would be unreadable if I labeled each point. Does anyone know of a way to create labels that only appear when the cursor hovers in the vicinity of that point?</p>

答:
mpld3 solves it for me.

```<code>import matplotlib.pyplot as plt
import numpy as np
import mpld3

fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100

scatter = ax.scatter(np.random.normal(size=N),
                 np.random.normal(size=N),
                 c=np.random.random(size=N),
                 s=1000 * np.random.random(size=N),
                 alpha=0.3,
                 cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')

ax.set_title("Scatter Plot (with tooltips!)", size=20)

labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)

mpld3.show()
</code>```

You can check this example: https://mpld3.github.io/examples/scatter_tooltip.html

ContentLicense: CC BY-SA 4.0

Body:
mpld3 solves it for me.

import matplotlib.pyplot as plt
import numpy as np
import mpld3

fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100

scatter = ax.scatter(np.random.normal(size=N),
                 np.random.normal(size=N),
                 c=np.random.random(size=N),
                 s=1000 * np.random.random(size=N),
                 alpha=0.3,
                 cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')

ax.set_title("Scatter Plot (with tooltips!)", size=20)

labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)

mpld3.show()

You can check this example: https://mpld3.github.io/examples/scatter_tooltip.html


问:
HDFS file watcher
Can I have file watcher on HDFS?

Scenario:
The files are landing on HDFS continuously.I want to start a Spark Job once the number of files reached a threshold(it can be number of files or size of the files).

Is it possible to implement file watcher on HDFS to achieve this . If yes, then can anyone suggest the way to do it?What are the different options available? Can the Zookeeper or the Oozie do it?

Any help will be appreciated.Thanks.

答: Oozie coordinator can do this. Oozie coordinator actions can be triggered based on data availability. Write a data triggered coordinator. The coordinator actions are triggered based on the done-flag. done-flag is nothing but an empty file. So when your threshold is reached write an empty file into the directory.</p>

Title: HDFS file watcher


问:
Executing multiple commands from a Windows cmd script
I'm trying to write a Windows cmd script to perform several tasks in series.
However, it always stops after the first command in the script.

The command it stops after is a maven build (not sure if that's relevant).

How do I make it carry on and run each task in turn please?

Installing any software or configuring the registry etc is completely out of the question - it has to work on a vanilla Windows XP installation I'm afraid.

Ideally I'd like the script to abort if any of the commands failed, but that's a "nice to have", not essential.

Thanks.

答:
If you are running in Windows you can use the following command.

Drive:

```<code>cd "Script location"
schtasks /run /tn "TASK1"
schtasks /run /tn "TASK2"
schtasks /run /tn "TASK3"
exit
</code>```

OwnerDisplayName: boncey

ContentLicense: CC BY-SA 2.5

Body:
If you are running in Windows you can use the following command.

Drive:

cd "Script location"
schtasks /run /tn "TASK1"
schtasks /run /tn "TASK2"
schtasks /run /tn "TASK3"
exit


问:
Using Factor Variables to Facet a Histogram Beside a Scatter Plot in R
Is it possible to use a factor variable to facet a histogram below or beside a scatter plot in ggplot2 in R (such that the histograms are of the x- and y-components of the data)?

The reason I ask whether this could be done with a factor variable is because faceting seems to be more general than the available packages that address this issue, where, for example with faceting, facet labels can be turned on or off, and also faceting has a more standard appearance where publication may be a concern. (Faceting also by default preserves the use of the same axes).

So far I haven't been able to get this to work because it seems like all faceted data have to be of the same number of dimensions (e.g., the scatterplot data is 2D, the histogram data are 1D).

答:
Consider the use of geom_rug.

```<code>ggplot(mtcars, aes(wt, mpg)) +
  geom_point() + geom_rug()
</code>```

Body:
Consider the use of geom_rug.

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() + geom_rug()


问:
conditional expression, its syntax and evaluation
Could someone clarify why does the procedure return 22? it is clear that this statement is not written correctly but anyway why does it return 22?

thank you in advance.

```<code>(define (proc x)
      (cond (= x 22)
            (display 3)
            (display 4)
      )
)
(proc 3)
</code>```

答:
You forgot a couple of parentheses. In this code:

```<code>(define (proc x)
  (cond (= x 22)
        (display 3)
        (display 4)))
</code>```

You're testing if the = procedure is true - which it is, because in Scheme everything is truthy, except #f, which is false. And given that = is true, the last value corresponding to that condition is returned, in this case: 22. The correct syntax for cond is as follows:

```<code>(define (proc x)
  (cond ((= x 22)
         (display 3)
         (display 4))
        (else 'error)))

(proc 22)
=> 34
(proc 3)
=> 'error
</code>```

Body:
Could someone clarify why does the procedure return 22? it is clear that this statement is not written correctly but anyway why does it return 22?

thank you in advance.

(define (proc x)
      (cond (= x 22)
            (display 3)
            (display 4)
      )
)
(proc 3)

Body:
You forgot a couple of parentheses. In this code:

(define (proc x)
  (cond (= x 22)
        (display 3)
        (display 4)))

You're testing if the = procedure is true - which it is, because in Scheme everything is truthy, except #f, which is false. And given that = is true, the last value corresponding to that condition is returned, in this case: 22. The correct syntax for cond is as follows:

(define (proc x)
  (cond ((= x 22)
         (display 3)
         (display 4))
        (else 'error)))

(proc 22)
=> 34
(proc 3)
=> 'error


问:
Define Java POJO so Gson does not write value double quoted
Note is this example javascript

```<code><html>
<head>
<script type="text/javascript">
window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title: {
            text: "Using labelFormatter function of axisY"
        },
        axisY:{
            labelFormatter: function(e){
                return  "Y: " + e.value;
            }
        },
        data: [
        {
            type: "spline",
            dataPoints: [
                { y: 5  },
                { y: 9  },
                { y: 17 },
                { y: 32 },
                { y: 22 },
                { y: 14 },
                { y: 25 },
                { y: 18 },
                { y: 20 }
            ]
        }
        ]
    });
    chart.render();
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
</code>```

from http://canvasjs.com/docs/charts/chart-options/axisy/label-formatter/ that the value of labelFormatter field is not double quoted, and if I modify it to be double quoted then the code does not work.

I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

I am trying to generate such code from Java using Gson, how do I create my POJO so that its value is not double quoted when output to json. Currently it is just defined as type String and therefore gets double quoted.

e.g

```<code>public class AxisY
{
    private boolean reversed;
    private int     labelMaxWidth;
    private boolean labelWrap;
    private String  title;
    private int     viewportMinimum = 0;
    private int     viewportMaximum;
    private int     interval;
    private String  labelFormatter;

    public boolean isReversed()
    {
        return reversed;
    }

    public void setReversed(boolean reversed)
    {
        this.reversed = reversed;
    }

    public int getLabelMaxWidth()
    {
        return labelMaxWidth;
    }

    public void setLabelMaxWidth(int labelMaxWidth)
    {
        this.labelMaxWidth = labelMaxWidth;
    }

    public boolean isLabelWrap()
    {
        return labelWrap;
    }

    public void setLabelWrap(boolean labelWrap)
    {
        this.labelWrap = labelWrap;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getViewportMinimum()
    {
        return viewportMinimum;
    }

    public void setViewportMinimum(int viewportMinimum)
    {
        this.viewportMinimum = viewportMinimum;
    }

    public int getViewportMaximum()
    {
        return viewportMaximum;
    }

    public void setViewportMaximum(int viewportMaximum)
    {
        this.viewportMaximum = viewportMaximum;
    }

    public int getInterval()
    {
        return interval;
    }

    public void setInterval(int interval)
    {
        this.interval = interval;
    }

    public String getLabelFormatter()
    {
        return labelFormatter;
    }

    public void setLabelFormatter(String labelFormatter)
    {
        this.labelFormatter = labelFormatter;
    }
}

  <!DOCTYPE HTML>
    <html>
    <head>
    <script type="text/javascript">
    window.onload = function () {
        var chart = new CanvasJS.Chart("chartContainer",
        {
            title: {
                text: "Using labelFormatter function of axisY"
            },
            axisY:{
                labelFormatter: function(e){
                    return  "Y: " + e.value;
                }
            },
            data: [
            {
                type: "spline",
                dataPoints: [
                    { y: 5  },
                    { y: 9  },
                    { y: 17 },
                    { y: 32 },
                    { y: 22 },
                    { y: 14 },
                    { y: 25 },
                    { y: 18 },
                    { y: 20 }
                ]
            }
            ]
        });
        chart.render();
    }
    </script>
    <script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
    </head>
    <body>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
    </body>
    </html>
</code>```

答:
You can send the JSON double quoted like it is supposed to be and there you use this lib https://github.com/jcoc611/cassandraMAP</p>

```<code>cassandraMAP.stringify({"key": "value"}); // => "{'key':'value'}"
cassandraMAP.parse("{'key':'value'}"); // => {"key": "value"}
</code>```

Body:
Note is this example javascript

from http://canvasjs.com/docs/charts/chart-options/axisy/label-formatter/ that the value of labelFormatter field is not double quoted, and if I modify it to be double quoted then the code does not work.

I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

I am trying to generate such code from Java using Gson, how do I create my POJO so that its value is not double quoted when output to json. Currently it is just defined as type String and therefore gets double quoted.

e.g

public class AxisY
{
    private boolean reversed;
    private int     labelMaxWidth;
    private boolean labelWrap;
    private String  title;
    private int     viewportMinimum = 0;
    private int     viewportMaximum;
    private int     interval;
    private String  labelFormatter;

    public boolean isReversed()
    {
        return reversed;
    }

    public void setReversed(boolean reversed)
    {
        this.reversed = reversed;
    }

    public int getLabelMaxWidth()
    {
        return labelMaxWidth;
    }

    public void setLabelMaxWidth(int labelMaxWidth)
    {
        this.labelMaxWidth = labelMaxWidth;
    }

    public boolean isLabelWrap()
    {
        return labelWrap;
    }

    public void setLabelWrap(boolean labelWrap)
    {
        this.labelWrap = labelWrap;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getViewportMinimum()
    {
        return viewportMinimum;
    }

    public void setViewportMinimum(int viewportMinimum)
    {
        this.viewportMinimum = viewportMinimum;
    }

    public int getViewportMaximum()
    {
        return viewportMaximum;
    }

    public void setViewportMaximum(int viewportMaximum)
    {
        this.viewportMaximum = viewportMaximum;
    }

    public int getInterval()
    {
        return interval;
    }

    public void setInterval(int interval)
    {
        this.interval = interval;
    }

    public String getLabelFormatter()
    {
        return labelFormatter;
    }

    public void setLabelFormatter(String labelFormatter)
    {
        this.labelFormatter = labelFormatter;
    }
}

  <!DOCTYPE HTML>

Body:
You can send the JSON double quoted like it is supposed to be and there you use this lib https://github.com/jcoc611/cassandraMAP

cassandraMAP.stringify({"key": "value"}); // => "{'key':'value'}"
cassandraMAP.parse("{'key':'value'}"); // => {"key": "value"}


问:
GDB Cannot insert breakpoint, Cannot access memory at address XXX?
I wrote a really simple program:

```<code>ebrahim@ebrahim:~/test$ cat main.c
int main() {
    int i = 0;
    return i;
}
</code>```

And the I compiled it with -s for stripped mode:

ebrahim@ebrahim:~/test$ gcc -s main.c -o f3
ebrahim@ebrahim:~/test$ file f3
f3: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=4dc6b893fbae8b418ca41ddeef948df1fcb26d3d, stripped
```

<p>Now, I'm trying to find out the main function start address using GDB:</p>

<pre class="lang-none prettyprint-override"><code>ebrahim@ebrahim:~/test$ gdb -nh f3
GNU gdb (Ubuntu 7.11.90.20161005-0ubuntu2) 7.11.90.20161005-git
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from f3...(no debugging symbols found)...done.
</code>```

As there is no Symbol info inside the file, I need to put a break at the file entry point and the disassemble it and find the start address of main function. So I used info file command to find the file entry point address:

(gdb) info file
Symbols from "/home/ebrahim/test/f3".
Local exec file:
    `/home/ebrahim/test/f3', file type elf64-x86-64.
    Entry point: 0x530     <<<<=============
    0x0000000000000238 - 0x0000000000000254 is .interp
    0x0000000000000254 - 0x0000000000000274 is .note.ABI-tag
    0x0000000000000274 - 0x0000000000000298 is .note.gnu.build-id
    0x0000000000000298 - 0x00000000000002b4 is .gnu.hash
    0x00000000000002b8 - 0x0000000000000360 is .dynsym
    0x0000000000000360 - 0x00000000000003f1 is .dynstr
    0x00000000000003f2 - 0x0000000000000400 is .gnu.version
    0x0000000000000400 - 0x0000000000000420 is .gnu.version_r
    0x0000000000000420 - 0x00000000000004f8 is .rela.dyn
    0x00000000000004f8 - 0x000000000000050f is .init
    0x0000000000000510 - 0x0000000000000520 is .plt
    0x0000000000000520 - 0x0000000000000528 is .plt.got
    0x0000000000000530 - 0x00000000000006e2 is .text
    0x00000000000006e4 - 0x00000000000006ed is .fini
    0x00000000000006f0 - 0x00000000000006f4 is .rodata
    0x00000000000006f4 - 0x0000000000000728 is .eh_frame_hdr
    0x0000000000000728 - 0x000000000000081c is .eh_frame
    0x0000000000200de0 - 0x0000000000200de8 is .init_array
    0x0000000000200de8 - 0x0000000000200df0 is .fini_array
    0x0000000000200df0 - 0x0000000000200df8 is .jcr
    0x0000000000200df8 - 0x0000000000200fb8 is .dynamic
    0x0000000000200fb8 - 0x0000000000201000 is .got
    0x0000000000201000 - 0x0000000000201010 is .data
    0x0000000000201010 - 0x0000000000201018 is .bss
```

<p>As we expected the entry point is the start of <code>.text</code> section. So I put a breakpoint on this address:</p>

<pre class="lang-none prettyprint-override"><code>(gdb) b *0x0000000000000530
Breakpoint 1 at 0x530
(gdb) r
Starting program: /home/ebrahim/test/f3
Warning:
Cannot insert breakpoint 1.
Cannot access memory at address 0x530

(gdb)
</code>```

The question is why GDB cannot insert this breakpoint?

答:
The problem is that you're attempting to debug a shared object as though it were an executable.  In particular your file reported:

ELF 64-bit LSB shared object

Because it's a shared object rather than an executable, you will probably need to start with an actual program.  In this particular case, you would need to link that shared object file with another program of your own making.  For example, I've created a simple shared object:

snoot.c

```<code>#include <stdio.h>

int square(int test) {
    return test*test;
}

int func() {
    n = 7;
    printf("The answer is %d\n", square(n)-5);
}
</code>```

Compile with

```<code>gcc -shared -fpic snoot.c -o libsnoot.so
strip libsnoot.so
</code>```

Now we have the equivalent of your stripped shared library.  If we do objdump -T libsnoot.so we get this:

```<code>libsnoot.so:     file format elf64-x86-64

DYNAMIC SYMBOL TABLE:
0000000000000580 l    d  .init  0000000000000000              .init
0000000000000000  w   D  *UND*  0000000000000000              _ITM_deregisterTMCloneTable
0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5 printf
0000000000000000  w   D  *UND*  0000000000000000              __gmon_start__
0000000000000000  w   D  *UND*  0000000000000000              _Jv_RegisterClasses
0000000000000000  w   D  *UND*  0000000000000000              _ITM_registerTMCloneTable
0000000000000000  w   DF *UND*  0000000000000000  GLIBC_2.2.5 __cxa_finalize
0000000000201028 g    D  .got.plt   0000000000000000  Base        _edata
00000000000006e0 g    DF .text  0000000000000010  Base        square
0000000000201030 g    D  .bss   0000000000000000  Base        _end
0000000000201028 g    D  .bss   0000000000000000  Base        __bss_start
0000000000000580 g    DF .init  0000000000000000  Base        _init
0000000000000724 g    DF .fini  0000000000000000  Base        _fini
00000000000006f0 g    DF .text  0000000000000032  Base        func
</code>```

The only two symbols in the .text section are the two functions we defined.  Unfortunately, there's no general way to determine how to call the functions (that is, no way to recover the original C function prototype) but we can simply guess.  If we guess wrong, the stack will be off.  For example, let's try to link to square with this program:

testsnoot.c

```<code>extern void square(void);

int main() {
    square();
}
</code>```

Assuming the so file is in the same directory, we can compile and link like so:

```<code>gcc testsnoot.c -o testsnoot -L. -lsnoot
</code>```

Now we can debug normally, since this test driver is under our control:

LD_LIBRARY_PATH="." gdb ./testsnoot

Note that we need to set LD_LIBRARY_PATH or else the library we're working with won't be loaded and execution will terminate.

```<code>(gdb) b square
Breakpoint 1 at 0x400560
(gdb) r
Starting program: /home/edward/test/testsnoot
Missing separate debuginfos, use: dnf debuginfo-install glibc-2.24-4.fc25.x86_64

Breakpoint 1, 0x00007ffff7bd56e4 in square () from ./libsnoot.so
(gdb) x/20i $pc
=> 0x7ffff7bd56e4 <square+4>:   mov    %edi,-0x4(%rbp)
   0x7ffff7bd56e7 <square+7>:   mov    -0x4(%rbp),%eax
   0x7ffff7bd56ea <square+10>:  imul   -0x4(%rbp),%eax
   0x7ffff7bd56ee <square+14>:  pop    %rbp
   0x7ffff7bd56ef <square+15>:  retq
   0x7ffff7bd56f0 <func>:   push   %rbp
   0x7ffff7bd56f1 <func+1>: mov    %rsp,%rbp
   0x7ffff7bd56f4 <func+4>: sub    $0x10,%rsp
   0x7ffff7bd56f8 <func+8>: movl   $0x7,-0x4(%rbp)
   0x7ffff7bd56ff <func+15>:    mov    -0x4(%rbp),%eax
   0x7ffff7bd5702 <func+18>:    mov    %eax,%edi
   0x7ffff7bd5704 <func+20>:    callq  0x7ffff7bd55b0 <square@plt>
   0x7ffff7bd5709 <func+25>:    sub    $0x5,%eax
   0x7ffff7bd570c <func+28>:    mov    %eax,%esi
   0x7ffff7bd570e <func+30>:    lea    0x18(%rip),%rdi        # 0x7ffff7bd572d
   0x7ffff7bd5715 <func+37>:    mov    $0x0,%eax
   0x7ffff7bd571a <func+42>:    callq  0x7ffff7bd55c0 <printf@plt>
   0x7ffff7bd571f <func+47>:    nop
   0x7ffff7bd5720 <func+48>:    leaveq
   0x7ffff7bd5721 <func+49>:    retq
</code>```

Now you can see the disassembly of the function and see what it's doing.  In this case, since we see that there is a reference to -0x4(%rbp) it's clear that this function is actually expecting an argument although we don't really know what kind.

We can rewrite the test drive function and iteratively approach debugging until we gain an understanding of what the stripped library is doing.

I'm assuming you can take it from there, now that I've showed the general procedure.

Body:
I wrote a really simple program:

ebrahim@ebrahim:~/test$ cat main.c
int main() {
    int i = 0;
    return i;
}

And the I compiled it with -s for stripped mode:

ebrahim@ebrahim:~/test$ gcc -s main.c -o f3
ebrahim@ebrahim:~/test$ file f3
f3: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=4dc6b893fbae8b418ca41ddeef948df1fcb26d3d, stripped

Now, I'm trying to find out the main function start address using GDB:

ebrahim@ebrahim:~/test$ gdb -nh f3
GNU gdb (Ubuntu 7.11.90.20161005-0ubuntu2) 7.11.90.20161005-git
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from f3...(no debugging symbols found)...done.

As there is no Symbol info inside the file, I need to put a break at the file entry point and the disassemble it and find the start address of main function. So I used info file command to find the file entry point address:

(gdb) info file
Symbols from "/home/ebrahim/test/f3".
Local exec file:
    `/home/ebrahim/test/f3', file type elf64-x86-64.
    Entry point: 0x530     <<<<=============
    0x0000000000000238 - 0x0000000000000254 is .interp
    0x0000000000000254 - 0x0000000000000274 is .note.ABI-tag
    0x0000000000000274 - 0x0000000000000298 is .note.gnu.build-id
    0x0000000000000298 - 0x00000000000002b4 is .gnu.hash
    0x00000000000002b8 - 0x0000000000000360 is .dynsym
    0x0000000000000360 - 0x00000000000003f1 is .dynstr
    0x00000000000003f2 - 0x0000000000000400 is .gnu.version
    0x0000000000000400 - 0x0000000000000420 is .gnu.version_r
    0x0000000000000420 - 0x00000000000004f8 is .rela.dyn
    0x00000000000004f8 - 0x000000000000050f is .init
    0x0000000000000510 - 0x0000000000000520 is .plt
    0x0000000000000520 - 0x0000000000000528 is .plt.got
    0x0000000000000530 - 0x00000000000006e2 is .text
    0x00000000000006e4 - 0x00000000000006ed is .fini
    0x00000000000006f0 - 0x00000000000006f4 is .rodata
    0x00000000000006f4 - 0x0000000000000728 is .eh_frame_hdr
    0x0000000000000728 - 0x000000000000081c is .eh_frame
    0x0000000000200de0 - 0x0000000000200de8 is .init_array
    0x0000000000200de8 - 0x0000000000200df0 is .fini_array
    0x0000000000200df0 - 0x0000000000200df8 is .jcr
    0x0000000000200df8 - 0x0000000000200fb8 is .dynamic
    0x0000000000200fb8 - 0x0000000000201000 is .got
    0x0000000000201000 - 0x0000000000201010 is .data
    0x0000000000201010 - 0x0000000000201018 is .bss

As we expected the entry point is the start of .text section. So I put a breakpoint on this address:

(gdb) b *0x0000000000000530
Breakpoint 1 at 0x530
(gdb) r
Starting program: /home/ebrahim/test/f3
Warning:
Cannot insert breakpoint 1.
Cannot access memory at address 0x530

(gdb)

The question is why GDB cannot insert this breakpoint?

Body:
The problem is that you're attempting to debug a shared object as though it were an executable.  In particular your file reported:

ELF 64-bit LSB shared object

Because it's a shared object rather than an executable, you will probably need to start with an actual program.  In this particular case, you would need to link that shared object file with another program of your own making.  For example, I've created a simple shared object:

snoot.c

#include <stdio.h>

int square(int test) {
    return test*test;
}

int func() {
    n = 7;
    printf("The answer is %d\n", square(n)-5);
}

Compile with

gcc -shared -fpic snoot.c -o libsnoot.so
strip libsnoot.so

Now we have the equivalent of your stripped shared library.  If we do objdump -T libsnoot.so we get this:

libsnoot.so:     file format elf64-x86-64

DYNAMIC SYMBOL TABLE:
0000000000000580 l    d  .init  0000000000000000              .init
0000000000000000  w   D  *UND*  0000000000000000              _ITM_deregisterTMCloneTable
0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5 printf
0000000000000000  w   D  *UND*  0000000000000000              __gmon_start__
0000000000000000  w   D  *UND*  0000000000000000              _Jv_RegisterClasses
0000000000000000  w   D  *UND*  0000000000000000              _ITM_registerTMCloneTable
0000000000000000  w   DF *UND*  0000000000000000  GLIBC_2.2.5 __cxa_finalize
0000000000201028 g    D  .got.plt   0000000000000000  Base        _edata
00000000000006e0 g    DF .text  0000000000000010  Base        square
0000000000201030 g    D  .bss   0000000000000000  Base        _end
0000000000201028 g    D  .bss   0000000000000000  Base        __bss_start
0000000000000580 g    DF .init  0000000000000000  Base        _init
0000000000000724 g    DF .fini  0000000000000000  Base        _fini
00000000000006f0 g    DF .text  0000000000000032  Base        func

The only two symbols in the .text section are the two functions we defined.  Unfortunately, there's no general way to determine how to call the functions (that is, no way to recover the original C function prototype) but we can simply guess.  If we guess wrong, the stack will be off.  For example, let's try to link to square with this program:

testsnoot.c

extern void square(void);

int main() {
    square();
}

Assuming the so file is in the same directory, we can compile and link like so:

gcc testsnoot.c -o testsnoot -L. -lsnoot

Now we can debug normally, since this test driver is under our control:

LD_LIBRARY_PATH="." gdb ./testsnoot

Note that we need to set LD_LIBRARY_PATH or else the library we're working with won't be loaded and execution will terminate.

(gdb) b square
Breakpoint 1 at 0x400560
(gdb) r
Starting program: /home/edward/test/testsnoot
Missing separate debuginfos, use: dnf debuginfo-install glibc-2.24-4.fc25.x86_64

Breakpoint 1, 0x00007ffff7bd56e4 in square () from ./libsnoot.so
(gdb) x/20i $pc
=> 0x7ffff7bd56e4 <square+4>:   mov    %edi,-0x4(%rbp)
   0x7ffff7bd56e7 <square+7>:   mov    -0x4(%rbp),%eax
   0x7ffff7bd56ea <square+10>:  imul   -0x4(%rbp),%eax
   0x7ffff7bd56ee <square+14>:  pop    %rbp
   0x7ffff7bd56ef <square+15>:  retq
   0x7ffff7bd56f0 <func>:   push   %rbp
   0x7ffff7bd56f1 <func+1>: mov    %rsp,%rbp
   0x7ffff7bd56f4 <func+4>: sub    $0x10,%rsp
   0x7ffff7bd56f8 <func+8>: movl   $0x7,-0x4(%rbp)
   0x7ffff7bd56ff <func+15>:    mov    -0x4(%rbp),%eax
   0x7ffff7bd5702 <func+18>:    mov    %eax,%edi
   0x7ffff7bd5704 <func+20>:    callq  0x7ffff7bd55b0 <square@plt>
   0x7ffff7bd5709 <func+25>:    sub    $0x5,%eax
   0x7ffff7bd570c <func+28>:    mov    %eax,%esi
   0x7ffff7bd570e <func+30>:    lea    0x18(%rip),%rdi        # 0x7ffff7bd572d
   0x7ffff7bd5715 <func+37>:    mov    $0x0,%eax
   0x7ffff7bd571a <func+42>:    callq  0x7ffff7bd55c0 <printf@plt>
   0x7ffff7bd571f <func+47>:    nop
   0x7ffff7bd5720 <func+48>:    leaveq
   0x7ffff7bd5721 <func+49>:    retq

Now you can see the disassembly of the function and see what it's doing.  In this case, since we see that there is a reference to -0x4(%rbp) it's clear that this function is actually expecting an argument although we don't really know what kind.

We can rewrite the test drive function and iteratively approach debugging until we gain an understanding of what the stripped library is doing.

I'm assuming you can take it from there, now that I've showed the general procedure.


问:
MYSQL SELECT WITH LEFT JOIN LIMIT 1
I have a problem:
I want to select all babble-rooms where user1 or user2 are a specific user id. (SELECT * FROM babble WHERE user1 = '$user' OR user2 = '$user')

But I also want to get the last entry of babble_messages where the babble ID is equal to babble_id.

My database structure:

Table babble:

     ID | user1 | user2 | created

Table babble_messages:

     ID | sender | babble_id | created | seen | message

My attempt is:

```<code>SELECT
    *
FROM
    babble
LEFT JOIN (
    SELECT
        babble_messages.ID AS last_id,
        babble_messages.sender AS last_sender,
        babble_messages.babble_id,
        babble_messages.created AS last_created,
        babble_messages.seen AS last_seen,
        babble_messages.message AS last_message
    FROM
        babble_messages
    ORDER BY
        created DESC LIMIT 1
    ) babble_messages ON
    babble.ID = babble_messages.babble_id
WHERE
    user1 = '$user' OR user2 = '$user'
ORDER BY
    last_created DESC
</code>```

This outputs empty entries for the LEFT JOIN table. I think this happens because I select in the subquery just the last entry of babble_messages...
I tried to add a WHERE tag into the subquery but that throws an error:

```<code>SELECT
    *
FROM
    babble
LEFT JOIN (
    SELECT
        babble_messages.ID AS last_id,
        babble_messages.sender AS last_sender,
        babble_messages.babble_id,
        babble_messages.created AS last_created,
        babble_messages.seen AS last_seen,
        babble_messages.message AS last_message
    FROM
        babble_messages
    WHERE
        babble.ID = babble_messages.babble_id*
    ORDER BY
        created DESC
    LIMIT
        1
    ) babble_messages ON
    babble.ID = babble_messages.babble_id
WHERE
    user1 = '$user' OR user2 = '$user'
ORDER BY
    last_created DESC
</code>```

In the subquery mysql does not know the "babble.ID".
How can I select just the last entry of babble_messages?

Of course I can use multiple request but I want to make just one request, because it is faster.

I hope this is enough information. :D
Thanks for reading and hopefully answering :)

Have a nice day hadome

答:
try to using table instance in your mysql query like babble b and babble_message bm

```<code>SELECT
   b.*
FROM
   babble b
LEFT JOIN (
    SELECT
       bm.ID AS last_id,
       bm.sender AS last_sender,
       bm.babble_id,
       bm.created AS last_created,
       bm.seen AS last_seen,
       bm.message AS last_message
    FROM
       babble_messages bm
    WHERE
       b.ID = bm.babble_id
    ORDER BY
       created DESC
    LIMIT
       1
    ) bm ON
    b.ID = bm.babble_id
  WHERE
    user1 = '$user' OR user2 = '$user'
  ORDER BY
    last_created DESC
</code>```

I hope this may be helpful to you.

Title: MYSQL SELECT WITH LEFT JOIN LIMIT 1

Body:
I have a problem:
I want to select all babble-rooms where user1 or user2 are a specific user id. (SELECT * FROM babble WHERE user1 = '$user' OR user2 = '$user')

But I also want to get the last entry of babble_messages where the babble ID is equal to babble_id.

My database structure:

Table babble:

     ID | user1 | user2 | created

Table babble_messages:

     ID | sender | babble_id | created | seen | message

My attempt is:

SELECT
    *
FROM
    babble
LEFT JOIN (
    SELECT
        babble_messages.ID AS last_id,
        babble_messages.sender AS last_sender,
        babble_messages.babble_id,
        babble_messages.created AS last_created,
        babble_messages.seen AS last_seen,
        babble_messages.message AS last_message
    FROM
        babble_messages
    ORDER BY
        created DESC LIMIT 1
    ) babble_messages ON
    babble.ID = babble_messages.babble_id
WHERE
    user1 = '$user' OR user2 = '$user'
ORDER BY
    last_created DESC

This outputs empty entries for the LEFT JOIN table. I think this happens because I select in the subquery just the last entry of babble_messages...
I tried to add a WHERE tag into the subquery but that throws an error:

SELECT
    *
FROM
    babble
LEFT JOIN (
    SELECT
        babble_messages.ID AS last_id,
        babble_messages.sender AS last_sender,
        babble_messages.babble_id,
        babble_messages.created AS last_created,
        babble_messages.seen AS last_seen,
        babble_messages.message AS last_message
    FROM
        babble_messages
    WHERE
        babble.ID = babble_messages.babble_id*
    ORDER BY
        created DESC
    LIMIT
        1
    ) babble_messages ON
    babble.ID = babble_messages.babble_id
WHERE
    user1 = '$user' OR user2 = '$user'
ORDER BY
    last_created DESC

In the subquery mysql does not know the "babble.ID".
How can I select just the last entry of babble_messages?

Of course I can use multiple request but I want to make just one request, because it is faster.

I hope this is enough information. :D
Thanks for reading and hopefully answering :)

Have a nice day hadome

Body:
try to using table instance in your mysql query like babble b and babble_message bm

SELECT
   b.*
FROM
   babble b
LEFT JOIN (
    SELECT
       bm.ID AS last_id,
       bm.sender AS last_sender,
       bm.babble_id,
       bm.created AS last_created,
       bm.seen AS last_seen,
       bm.message AS last_message
    FROM
       babble_messages bm
    WHERE
       b.ID = bm.babble_id
    ORDER BY
       created DESC
    LIMIT
       1
    ) bm ON
    b.ID = bm.babble_id
  WHERE
    user1 = '$user' OR user2 = '$user'
  ORDER BY
    last_created DESC

I hope this may be helpful to you.


问:
How to kill background process from system function call
How can I kill a background process that was executed using a system function call in C language. Like for example I have a compiled application call "fooprocess". Then I want to write a program that will execute the fooprocess application in the background using the system function, please kindly see below the code,

```<code>const char app[] = "fooprocess &";
system(app);
</code>```

As you can see there is a "&" character so that I can run the fooprocess application in the background. How can I kill this fooprocess?

Many thanks.

答:
You absolutely cannot use system("foo &"); to create background processes that you can later monitor/kill. Any such use has a gigantic inherent bug: even if you know the pid, there is no way to tell if the process with that pid is the process you originally ran, or a completely different process that happened to get the same pid later.

To solve this problem (and countless other problems you don't want to think about or it will make your head hurt) you should forget you ever learned about the system function and create your child processes with fork and exec, or posix_spawn. This will result in a direct child process (your current method is creating grandchildren which get orphaned and taken in by the init process) which you can wait/waitpid on, and until you perform a wait operation, the child process's pid belongs to you and cannot be reused, so it's safe to send signals to it, etc.

Body:
How can I kill a background process that was executed using a system function call in C language. Like for example I have a compiled application call "fooprocess". Then I want to write a program that will execute the fooprocess application in the background using the system function, please kindly see below the code,

const char app[] = "fooprocess &";
system(app);

As you can see there is a "&" character so that I can run the fooprocess application in the background. How can I kill this fooprocess?

Many thanks.


问:
jquery on beforeSubmit not called on Safari
I've created a payment form with Stripe that needs to interact with their API in order to get a token before my form can be submitted. Everything was tested and working in Chrome, but yesterday a user said it's not working in Safari.

I've been able to narrow down the cause to Safari submitting the form before the following code is executed:

```<code>$('#payment-form').on('beforeSubmit', function(event) {
                    if (isCcNeeded()) {

                        // Disable the submit button to prevent repeated clicks:
                        $('#payment-form').find('.submit').prop('disabled', true);

                        // Request a token from Stripe:
                        Stripe.card.createToken({
                                number: $('input#stripe-card-number').val(),
                                cvc: $('input#stripe-cvc').val(),
                                exp_month: getExpMonth(),
                                exp_year: getExpYear(),
                                address_zip: $('input#stripe-address-zip').val()
                        }, stripeResponseHandler);

                        // Prevent the form from being submitted:
                        return false;
                    }
                });
</code>```

Does anyone know why it's skipping this?

答:
Okay! So the solution was actually a combination of a few things that I was trying. As the comments to my original post stated, I first needed to change to using 'submit' rather than 'beforeSubmit' (I think this is a Yii2 specific thing).

However, I had to take that one step further. In order for it to actually work, I had to also call preventDefault() on the event.

I also ended up migrating from stripe.js v2 to v3 while I was messing around with this code, so I'm not sure if that helped or not as well.

The final solution came to...

```<code>            var form = document.getElementById('payment-form');
            $('#payment-form').on('submit', function(e) {
                e.preventDefault();
                createToken();
            });
</code>```

Thank you for the help everyone!

Body:
I've created a payment form with Stripe that needs to interact with their API in order to get a token before my form can be submitted. Everything was tested and working in Chrome, but yesterday a user said it's not working in Safari.

I've been able to narrow down the cause to Safari submitting the form before the following code is executed:

$('#payment-form').on('beforeSubmit', function(event) {
                    if (isCcNeeded()) {

                        // Disable the submit button to prevent repeated clicks:
                        $('#payment-form').find('.submit').prop('disabled', true);

                        // Request a token from Stripe:
                        Stripe.card.createToken({
                                number: $('input#stripe-card-number').val(),
                                cvc: $('input#stripe-cvc').val(),
                                exp_month: getExpMonth(),
                                exp_year: getExpYear(),
                                address_zip: $('input#stripe-address-zip').val()
                        }, stripeResponseHandler);

                        // Prevent the form from being submitted:
                        return false;
                    }
                });

Does anyone know why it's skipping this?

Body:
Okay! So the solution was actually a combination of a few things that I was trying. As the comments to my original post stated, I first needed to change to using 'submit' rather than 'beforeSubmit' (I think this is a Yii2 specific thing).

However, I had to take that one step further. In order for it to actually work, I had to also call preventDefault() on the event.

I also ended up migrating from stripe.js v2 to v3 while I was messing around with this code, so I'm not sure if that helped or not as well.

The final solution came to...

            var form = document.getElementById('payment-form');
            $('#payment-form').on('submit', function(e) {
                e.preventDefault();
                createToken();
            });

Thank you for the help everyone!


问:
Unpack dict from list where key is not None
Trying to unpack the dicts which are not None from a list:

```<code>In [4]: unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]
</code>```

Tried a dict comprehension

```<code>In [5]: {key: value for (key, value) in unpack_dict if (key, value) is not None}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-ec0e44b95586> in <module>()
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

<ipython-input-5-ec0e44b95586> in <dictcomp>(.0)
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

ValueError: not enough values to unpack (expected 2, got 1)
</code>```

And a list comprehension:

```<code>In [6]: {**[x for x in [unpack_dict] if x is not None]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ac36898d39a1> in <module>()
----> 1 {**[x for x in [unpack_dict] if x is not None]}

TypeError: 'list' object is not a mapping
</code>```

Expected result:

```<code>{'key': 'a', 'key_2': 'b'}
</code>```

What is the right syntax?

答:
You are trying to unpack either a dictionary or None to two variables (key and value). You can't unpack either type in this way. None is not iterable, and iteration over a dict would yield only the keys, not the values.

Loop over the dictionary items if there is a dictionary, otherwise loop over an empty sequence, and unpack the iteration results:

```<code>{key: value for d in unpack_dict for key, value in (d.items() if d else ())}
</code>```

The d.items() if d else () expression produces either an iterable of (key, value) pairs from a (non-empty) dictionary, or an empty tuple (causing that nested iteration to stop immediately).

Demo:

```<code>>>> unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]
>>> {key: value for d in unpack_dict for key, value in (d.items() if d else ())}
{'key': 'a', 'key_2': 'b'}
</code>```

Body:
Trying to unpack the dicts which are not None from a list:

In [4]: unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]

Tried a dict comprehension

In [5]: {key: value for (key, value) in unpack_dict if (key, value) is not None}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-ec0e44b95586> in <module>()
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

<ipython-input-5-ec0e44b95586> in <dictcomp>(.0)
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

ValueError: not enough values to unpack (expected 2, got 1)

And a list comprehension:

In [6]: {**[x for x in [unpack_dict] if x is not None]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ac36898d39a1> in <module>()
----> 1 {**[x for x in [unpack_dict] if x is not None]}

TypeError: 'list' object is not a mapping

Expected result:

{'key': 'a', 'key_2': 'b'}

What is the right syntax?

Body:
You are trying to unpack either a dictionary or None to two variables (key and value). You can't unpack either type in this way. None is not iterable, and iteration over a dict would yield only the keys, not the values.

Loop over the dictionary items if there is a dictionary, otherwise loop over an empty sequence, and unpack the iteration results:

{key: value for d in unpack_dict for key, value in (d.items() if d else ())}

The d.items() if d else () expression produces either an iterable of (key, value) pairs from a (non-empty) dictionary, or an empty tuple (causing that nested iteration to stop immediately).

Demo:

>>> unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]
>>> {key: value for d in unpack_dict for key, value in (d.items() if d else ())}
{'key': 'a', 'key_2': 'b'}


问:
Nodejs application monitor mongodb performance
I am using nodejs to running my application with mongodb host in composeio.
I would like to have the tool can help me analysis the query performance executed by my application. For example query time execution, memory usage that consume of database, slowness query, count of query execution for each time frame.
Similar with Newrelic</p>

答:
You can use any APM tool which supports Node.js for this. It really depends on what level of depth you need. The common ones would be AppDynamics, Dynatrace Ruxit, and New Relic. They actually do a lot more than your requirements but will help you diagnose issues.

Some of the tools such as AppDynamics can also monitor the MongoDB runtime as well. There are some specialist tools for node.js as well, such as Risingstack.


问:
C# Mediaplayer doesn't play mp3 file from resources
Mediaplayer didn't work for me, so I moved to a simple test project (C# Console App). I added my .mp3 file to the project like this:

Right click project name (test) in solution explorer

add folder resources

Right click the resources folder in solution explorer

Add my warn.mp3 file

left click the warn.mp3 file

Changed Build Action to Resource in the properties window.

Sadly, this code doesnt work:

```<code>namespace test
{
    class Program
    {
        public static void Main(string[] args)
        {
            MediaPlayer player = new MediaPlayer();
            player.Open(new Uri("resources/warn.mp3", UriKind.Relative));
            player.Play();
            Console.ReadKey();
        }
    }
}
</code>```

However, this one does:

```<code>namespace test
{
    class Program
    {
        public static void Main(string[] args)
        {
            MediaPlayer player = new MediaPlayer();
            player.Open(new Uri("C:\\Users\\Krepsy3\\Documents\\Programs\\OOP\\test\\test\\resources\\warn.mp3", UriKind.Absolute));
            player.Play();
            Console.ReadKey();
        }
    }
}
</code>```

Any idea about what is wrong?

答: You cannot use MediaPlayer from a internal exe/dll resource. You should choose another player component or write it to disk. If you can choose another player, looks like System.Media.SoundPlayercould do the trick. Search for stack overflow Play wav/mp3 from memory there should give some results

Body:
Mediaplayer didn't work for me, so I moved to a simple test project (C# Console App). I added my .mp3 file to the project like this:

Right click project name (test) in solution explorer

add folder resources

Right click the resources folder in solution explorer

Add my warn.mp3 file

left click the warn.mp3 file

Changed Build Action to Resource in the properties window.

Sadly, this code doesnt work:

namespace test
{
    class Program
    {
        public static void Main(string[] args)
        {
            MediaPlayer player = new MediaPlayer();
            player.Open(new Uri("resources/warn.mp3", UriKind.Relative));
            player.Play();
            Console.ReadKey();
        }
    }
}

However, this one does:

namespace test
{
    class Program
    {
        public static void Main(string[] args)
        {
            MediaPlayer player = new MediaPlayer();
            player.Open(new Uri("C:\\Users\\Krepsy3\\Documents\\Programs\\OOP\\test\\test\\resources\\warn.mp3", UriKind.Absolute));
            player.Play();
            Console.ReadKey();
        }
    }
}

Any idea about what is wrong?


问:
How to remove multiple filed laravel?
I have my table data:

```<code>id  song_id   playlist_id
1     2          5
2     2          4
</code>```

I want to remove it by if I give

```<code>song_id playlist_id
2          4         success
2          3          fail
</code>```

Please help me thanks
Noted: I use laravel custom query builder

答:
You can use </p>

```<code>\DB::('table')->where('song_id',2)->where('playlist_id',4)->delete();
</code>```

Title: How to remove multiple filed laravel?

Body:
I have my table data:

id  song_id   playlist_id
1     2          5
2     2          4

I want to remove it by if I give

song_id playlist_id
2          4         success
2          3          fail

Please help me thanks
Noted: I use laravel custom query builder

Body:
You can use

\DB::('table')->where('song_id',2)->where('playlist_id',4)->delete();


问:
hibernate validator LengthValidator of truncated string
Is there a similar annotation to @Length in hibernate validator but it restricted on a trimmed string.

For example:

I have

```<code>@Length(max= 2);
String str;
</code>```

when:
str = " ab";

--> it will pass ok.

Thanks,

答: I don't think so, but you can easily implement one with javax.validation, by extending the LengthValidator

Body:
Is there a similar annotation to @Length in hibernate validator but it restricted on a trimmed string.

For example:

I have

@Length(max= 2);
String str;

when:
str = " ab";

--> it will pass ok.

Thanks,


问:
How to validate Google reCAPTCHA v3 on server side?
I've just set up the new google recaptcha with checkbox, it's working fine on front end, however I don't know how to handle it on server side using PHP. I've tried to use the old code below but the form is sent even if the captcha is not valid.</p>

```<code>require_once('recaptchalib.php');
$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,
        $_SERVER["REMOTE_ADDR"],
        $_POST["recaptcha_challenge_field"],
        $_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
 $errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';}
</code>```

答:
Here you have simple example. Just remember to provide secretKey and siteKey from google api.

```<code><?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';

if($_POST['submit']){
    $username = $_POST['username'];
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response = file_get_contents($url);
    $response = json_decode($response);
    if($response->success){
        echo "Verification is correct. Your name is $username";
    } else {
        echo "Verification failed";
    }
} ?>

<html>
<meta>
    <title>Google ReCaptcha</title>
</meta>
<body>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
        <input type="submit" name="submit" value="send"/>
    </form>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</body>
</code>```

Body:
I've just set up the new google recaptcha with checkbox, it's working fine on front end, however I don't know how to handle it on server side using PHP. I've tried to use the old code below but the form is sent even if the captcha is not valid.

require_once('recaptchalib.php');
$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,
        $_SERVER["REMOTE_ADDR"],
        $_POST["recaptcha_challenge_field"],
        $_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
 $errCapt='
The CAPTCHA Code wasnot entered correctly.
';}

Body:
Here you have simple example. Just remember to provide secretKey and siteKey from google api.

<?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';

if($_POST['submit']){
    $username = $_POST['username'];
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response = file_get_contents($url);
    $response = json_decode($response);
    if($response->success){
        echo "Verification is correct. Your name is $username";
    } else {
        echo "Verification failed";
    }
} ?>

<html>
<meta>
    <title>Google ReCaptcha</title>
</meta>
<body>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
        <input type="submit" name="submit" value="send"/>
    </form>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</body>


问:
Move files from Azure storage to a local directory
I want to move all the files that in a File share on azure. I can do it at the moment by following way using:

Use "net" command to connect to the network drive and assign it a drive letter

Then there's a bat file that uses "move" command like move g:\files\* c:\files to then move the files which runs every hour to check if there are files and move them using windows task scheduler.

But I don't want to use this way because:

The drive will be disconnected if the Machine needs a restart and hence the process doesn't remain automated as someone will have to mount the drive again

The "move" command doesn't moves folders, it moves only files.

Is there a better way of managing this? We don't want to install tools like AzCopy but using Powershell is feasible.

答:
The issue was resolved using the following approach:

Delete any existing mapped drive to the drive letter we are using with the net use <drive_letter> /delete command. This is done to make sure the drive was detached since the last time script ran

Map the drive again using the net use command

Copy all the files using robocopy

After that delete all the files using del command

Disconnect the drive now using the net use <drive_letter> /delete command


问:
How to send file name to the listener using execution context?
I am reading  xml files , gathering records and storing it in DB.My objective is to log the file name if there is any exeception when storing record of this xml in DB. I was hoping to the execution context at listner level where I can get the file name.But I think spring batch does not have the feature.

I wish to pass the file name to the listener using execution context from partitioner.

this partitinor we have give executioncontext to send the file name has string to the item writer listener.

```<code>public class MultiFileResourcePartitioner implements Partitioner {

private String inboundDir;

@Override
public Map<String, ExecutionContext> partition(int gridSize) {

    Map<String, ExecutionContext> partitionMap = new HashMap<String, ExecutionContext>();
    File payloadFileDir = new File(inboundDir);

    if (payloadFileDir.isDirectory()) {
        File[] payloadFiles = payloadFileDir.listFiles();

        for (File payloadFile : payloadFiles) {

            ExecutionContext context = new ExecutionContext();
            context.putString("name", "Thread" +payloadFile.getName());
            context.putString("payloadfile", payloadFile.getName());
            context.put("fileResource", payloadFile.toURI().toString());
            partitionMap.put(payloadFile.getName(), context);

            }

    }
    //System.out.println("partitionMap::"+partitionMap.size());
    return partitionMap;
}

public String getInboundDir() {
    return inboundDir;
}

public void setInboundDir(String inboundDir) {
    this.inboundDir = inboundDir;
}
</code>```

}

this is item listener class for which it has filename has string datatype and it will take the file name from step execution context.

```<code>public class CustomItemWriterListener implements ItemWriteListener<ItemMaintenance> {
private String filename;
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;

@Override
public void beforeWrite(List<? extends ItemMaintenance> items) {
    System.out.println("ItemWriteListener - beforeWrite");
}

@Override
public void afterWrite(List<? extends ItemMaintenance> items) {
    System.out.println("ItemWriteListener - afterWrite:"+items.size());

}

@Override
public void onWriteError(Exception exception, List<? extends ItemMaintenance> items) {

    try {
        fh = new FileHandler("D:/temp/ErrorWriter.txt");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.info("duplicate record"+"::"+exception.getMessage().subSequence(450, 453)+filename);
    }

     catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
</code>```

}

this bean will take file name from step execution context.

```<code> <bean id="CustomItemWriterListener"
      class="com.listeners.CustomItemWriterListener">
      <property name="filename" value="#{stepExecutionContext['payloadfile']}" />
      </bean>
</code>```

答:
You need to put your CustomItemWriterListener bean into Step scope to have visibility to the step's ExecutionContext.

```<code><!-- note: scope="step" -->
<bean id="CustomItemWriterListener" scope="step"
             class="com.listeners.CustomItemWriterListener" >
    <property name="filename" value="#{stepExecutionContext['payloadfile']}" />
</bean>
</code>```

Body:
I am reading  xml files , gathering records and storing it in DB.My objective is to log the file name if there is any exeception when storing record of this xml in DB. I was hoping to the execution context at listner level where I can get the file name.But I think spring batch does not have the feature.

I wish to pass the file name to the listener using execution context from partitioner.

this partitinor we have give executioncontext to send the file name has string to the item writer listener.

public class MultiFileResourcePartitioner implements Partitioner {

private String inboundDir;

@Override
public Map<String, ExecutionContext> partition(int gridSize) {

    Map<String, ExecutionContext> partitionMap = new HashMap<String, ExecutionContext>();
    File payloadFileDir = new File(inboundDir);

    if (payloadFileDir.isDirectory()) {
        File[] payloadFiles = payloadFileDir.listFiles();

        for (File payloadFile : payloadFiles) {

            ExecutionContext context = new ExecutionContext();
            context.putString("name", "Thread" +payloadFile.getName());
            context.putString("payloadfile", payloadFile.getName());
            context.put("fileResource", payloadFile.toURI().toString());
            partitionMap.put(payloadFile.getName(), context);

            }

    }
    //System.out.println("partitionMap::"+partitionMap.size());
    return partitionMap;
}

public String getInboundDir() {
    return inboundDir;
}

public void setInboundDir(String inboundDir) {
    this.inboundDir = inboundDir;
}

}

this is item listener class for which it has filename has string datatype and it will take the file name from step execution context.

public class CustomItemWriterListener implements ItemWriteListener<ItemMaintenance> {
private String filename;
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;

@Override
public void beforeWrite(List<? extends ItemMaintenance> items) {
    System.out.println("ItemWriteListener - beforeWrite");
}

@Override
public void afterWrite(List<? extends ItemMaintenance> items) {
    System.out.println("ItemWriteListener - afterWrite:"+items.size());

}

@Override
public void onWriteError(Exception exception, List<? extends ItemMaintenance> items) {

    try {
        fh = new FileHandler("D:/temp/ErrorWriter.txt");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.info("duplicate record"+"::"+exception.getMessage().subSequence(450, 453)+filename);
    }

     catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

this bean will take file name from step execution context.

 <bean id="CustomItemWriterListener"
      class="com.listeners.CustomItemWriterListener">
      <property name="filename" value="#{stepExecutionContext['payloadfile']}" />
      </bean>

Body:
You need to put your CustomItemWriterListener bean into Step scope to have visibility to the step's ExecutionContext.

<!-- note: scope="step" -->
<bean id="CustomItemWriterListener" scope="step"
             class="com.listeners.CustomItemWriterListener" >
    <property name="filename" value="#{stepExecutionContext['payloadfile']}" />
</bean>


问:
Connect from a Docker container to port of another docker container
I have two docker containers running on a linux host.

One with a DATABASE and one with an APPLICATION.

How can I connect from container APPLICATION to container DATABASE port 5432?

For example:
I start DATABASE container and bind port 5432 to hosts localhost with "-p5432:5432. But how can I acces this port from APPLICATION? I cannot bind port 5432 to host localhost because this port is now already used.

Docker version 1.12.6

update

I used now

```<code>sudo docker network create --subnet=172.20.0.0/16 --gateway=172.20.0.100   --ip-range=172.20.1.0/24 my-network
sudo docker run --name postgres  --network=my-network --ip=172.20.0.10 -d postgres
sudo docker run --name application --network=my-network --ip=172.20.0.15 -d application
</code>```

and configured app in APPLICATION container to look for ip 172.20.0.10

https://docs.docker.com/engine/userguide/networking/work-with-networks/

答:
Alternatively you can use docker networks, easy to achieve with docker-compose. In my example you can point from your app container to postgres-container as this: postgres-container:5432

docker-compose.yml:

```<code>version: "3"

services:
  app:
    image: postgres
    command: sh -c 'sleep 10; echo \\l | PGPASSWORD=mysecretpassword psql -U postgres -h postgres-container'
  postgres-container:
    image: postgres
    environment:
      - POSTGRES_PASSWORD=mysecretpassword
</code>```

Command:

```<code>docker-compose up
</code>```

Output:

```<code>Attaching to postgresql_app_1, postgresql_postgres-container_1
(...)
postgres-container_1  | server started
(...)
app_1                 |                                  List of databases
app_1                 |    Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
app_1                 | -----------+----------+----------+------------+------------+-----------------------
app_1                 |  postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
app_1                 |  template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
app_1                 |            |          |          |            |            | postgres=CTc/postgres
app_1                 |  template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
app_1                 |            |          |          |            |            | postgres=CTc/postgres
app_1                 | (3 rows)
app_1                 |
</code>```

Body:
I have two docker containers running on a linux host.

One with a DATABASE and one with an APPLICATION.

How can I connect from container APPLICATION to container DATABASE port 5432?

For example:
I start DATABASE container and bind port 5432 to hosts localhost with "-p5432:5432. But how can I acces this port from APPLICATION? I cannot bind port 5432 to host localhost because this port is now already used.

Docker version 1.12.6

update

I used now

sudo docker network create --subnet=172.20.0.0/16 --gateway=172.20.0.100   --ip-range=172.20.1.0/24 my-network
sudo docker run --name postgres  --network=my-network --ip=172.20.0.10 -d postgres
sudo docker run --name application --network=my-network --ip=172.20.0.15 -d application

and configured app in APPLICATION container to look for ip 172.20.0.10

https://docs.docker.com/engine/userguide/networking/work-with-networks/

Body:
Alternatively you can use docker networks, easy to achieve with docker-compose. In my example you can point from your app container to postgres-container as this: postgres-container:5432

docker-compose.yml:

version: "3"

services:
  app:
    image: postgres
    command: sh -c 'sleep 10; echo \\l | PGPASSWORD=mysecretpassword psql -U postgres -h postgres-container'
  postgres-container:
    image: postgres
    environment:
      - POSTGRES_PASSWORD=mysecretpassword

Command:

docker-compose up

Output:

Attaching to postgresql_app_1, postgresql_postgres-container_1
(...)
postgres-container_1  | server started
(...)
app_1                 |                                  List of databases
app_1                 |    Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
app_1                 | -----------+----------+----------+------------+------------+-----------------------
app_1                 |  postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
app_1                 |  template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
app_1                 |            |          |          |            |            | postgres=CTc/postgres
app_1                 |  template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
app_1                 |            |          |          |            |            | postgres=CTc/postgres
app_1                 | (3 rows)
app_1                 |