text:
Q: Unable to fetch data from on premise system using s4sdk I followed the tutorial:  https://open.sap.com/courses/s4h13/items/258qEhXx5kdG8b4SXMSJYp
I am able to fetch data from mocked service, but I get an empty array when I add an on premise sap system in my destination.
I am trying to read ProductMaster service (which is available in my sap system).
any guidance or link of correct blog will be much appreciated.
Application logs:-
2019-01-31T09:49:30.98+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:30.980Z","written_ts":3583833066597470,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.container.UserInfoTomcat","thread":"http-bio-0.0.0.0-8080-exec-1","level":"INFO","categories":[],"msg":"Parsing SAP_JWT_TRUST_ACL (value: [{\"clientid\" : \"\", \"identityzone\" : \"\"}])" }
   2019-01-31T09:49:30.98+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:30.980Z","written_ts":3583833067255806,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.container.UserInfoTomcat","thread":"http-bio-0.0.0.0-8080-exec-1","level":"INFO","categories":[],"msg":"Access token of service plan \"application\" received" }
   2019-01-31T09:49:30.98+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:30.980Z","written_ts":3583833067335285,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.commons.SAPVcapServicesParser","thread":"http-bio-0.0.0.0-8080-exec-1","level":"INFO","categories":[],"msg":"VCAP_SERVICES: Only one applicable binding exists, service plan hint \"application\" is not used" }
   2019-01-31T09:49:30.98+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:30.980Z","written_ts":3583833067403879,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.commons.SAPPropertyPlaceholderConfigurer","thread":"http-bio-0.0.0.0-8080-exec-1","level":"INFO","categories":[],"msg":"Got from VCAP_SERVICES: clientid=sb-address-manager-p1942271708trial!t9649" }
   2019-01-31T09:49:37.03+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:37.030Z","written_ts":3583839116771998,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.container.UserInfoTomcat","thread":"http-bio-0.0.0.0-8080-exec-3","level":"INFO","categories":[],"msg":"Parsing SAP_JWT_TRUST_ACL (value: [{\"clientid\" : \"\", \"identityzone\" : \"\"}])" }
   2019-01-31T09:49:37.03+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:37.030Z","written_ts":3583839117339973,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.container.UserInfoTomcat","thread":"http-bio-0.0.0.0-8080-exec-3","level":"INFO","categories":[],"msg":"Access token of service plan \"application\" received" }
   2019-01-31T09:49:37.03+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:37.030Z","written_ts":3583839117412082,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.commons.SAPVcapServicesParser","thread":"http-bio-0.0.0.0-8080-exec-3","level":"INFO","categories":[],"msg":"VCAP_SERVICES: Only one applicable binding exists, service plan hint \"application\" is not used" }
   2019-01-31T09:49:41.02+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.026Z","written_ts":3583843112511705,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.commons.SAPVcapServicesParser","thread":"http-bio-0.0.0.0-8080-exec-10","level":"INFO","categories":[],"msg":"VCAP_SERVICES: Only one applicable binding exists, service plan hint \"application\" is not used" }
   2019-01-31T09:49:41.02+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.026Z","written_ts":3583843112682598,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs2.security.commons.SAPPropertyPlaceholderConfigurer","thread":"http-bio-0.0.0.0-8080-exec-10","level":"INFO","categories":[],"msg":"Got from VCAP_SERVICES: verificationkey=-----BEGIN PUBLIC KEY-----MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAwThn6OO9kj0bchkOGkqYBnV1dQ3zU/xtj7Kj7nDd8nyRMcEWCtVzrzjzhiisRhlrzlRIEY82wRAZNGKMnw7cvCwNixcfcDJnjzgr2pJ+5/yDZUc0IXXyIWPZD+XdL+0EogC3d4+fqyvg/BF/F0t2hKHWr/UTXE6zrGhBKaL0d8rKfYd6olGWigFd+3+24CKI14zWVxUBtC+P9Fhngc9DRzkXqhxOK/EKn0HzSgotf5duq6Tmk9DCNM4sLW4+ERc6xzrgbeEexakabvax/Az9WZ4qhwgw+fwIhKIC7WLwCEJaRsW4m7NKkv+eJR2LKYesuQ9SVAJ3EXV86RwdnH4uAv7lQHsKURPVAQBlranSqyQu0EXs2N9OlWTxe+FyNkIvyZvoLrZl/CdlYc8AKxRm5rn2/88nkrYQ0XZSrnICM5FRWgVF2hn5KfZGwtBN85/D4Yck6B3ocMfyX7e4URUm9lRPQFUJGTXaZnEIge0R159HUwhTN1HvyXrs6uT1ZZmW+c3p47dw1+LmUf/hIf8zd+uvHQjIeHEJqxjqfyA8yqAFKRHKVFrwnwdMHIsRap2EKBhHMfeVf0P2th5C9MggYoGCvdIaIUgMBX3TtCdvGrcWML7hnyS2zkrlA8SoKJnRcRF2KxWKs355FhpHpzqyZflO5l98+O8wOsFjGpL9d0ECAwEAAQ==-----END PUBLIC KEY-----" }
   2019-01-31T09:49:41.02+0530 [APP/PROC/WEB/0] OUT audit/security-events: {"uuid":"f9e8cee3-accc-4ea0-b1a8-8eb0332610c3","user":"armoghan.abbas@gmail.com","time":"2019-01-31T04:19:41.029Z","ip":"52.28.241.88","data":"Successful log on for 'armoghan.abbas@gmail.com' from 52.28.241.88.","tenant":"9f0f4bb3-bb5f-4745-b992-7d41c3100573"}
   2019-01-31T09:49:41.03+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.030Z","written_ts":3583843117462454,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.xs.security.container.XSSecurityAuthenticator","thread":"http-bio-0.0.0.0-8080-exec-10","level":"WARN","categories":[],"msg":"AuditLog service binding is not available. The message will be written in console output.","stacktrace":["com.sap.xs.audit.api.exception.AuditLogNotAvailableException: Cannot send audit log message to the backend. Missing audit log service credentials parameters or binding to an auditlog service instance.","\tat com.sap.xs.audit.client.impl.ConsoleCommunicator.send(ConsoleCommunicator.java:10)","\tat com.sap.xs.audit.client.impl.AuditLogMessageImpl.log(AuditLogMessageImpl.java:85)","\tat com.sap.xs.security.container.XSSecurityAuthenticator.logSecurityEventAuditMessage(XSSecurityAuthenticator.java:112)","\tat com.sap.xs.security.container.XSSecurityAuthenticator.logSuccessfulLogonAuditMessage(XSSecurityAuthenticator.java:97)","\tat com.sap.xs.security.container.XSSecurityAuthenticator.authenticate(XSSecurityAuthenticator.java:45)","\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:566)","\tat com.sap.xs.security.container.XSSecurityAuthenticator.invoke(XSSecurityAuthenticator.java:131)","\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)","\tat com.sap.xs.java.valves.ErrorReportValve.invoke(ErrorReportValve.java:66)","\tat ch.qos.logback.access.tomcat.LogbackValve.invoke(LogbackValve.java:191)","\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)","\tat com.sap.xs.security.UserInfoValve.invoke(UserInfoValve.java:19)","\tat com.sap.xs.statistics.tomcat.valve.RequestTracingValve.invoke(RequestTracingValve.java:43)","\tat com.sap.xs.logging.catalina.RuntimeInfoValve.invoke(RuntimeInfoValve.java:40)","\tat org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:695)","\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)","\tat org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1137)","\tat org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)","\tat org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)","\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)","\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)","\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)","\tat java.lang.Thread.run(Thread.java:836)"] }
   2019-01-31T09:49:41.03+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.034Z","written_ts":3583843120774921,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.s4hana.examples.addressmgr.BusinessPartnerServlet","thread":"http-bio-0.0.0.0-8080-exec-10","level":"INFO","categories":[],"msg":"Retrieving all business partners" }
   2019-01-31T09:49:41.38+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.383Z","written_ts":3583843469583997,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.s4hana.connectivity.ErpConfigContext","thread":"http-bio-0.0.0.0-8080-exec-10","level":"INFO","categories":[],"msg":"Falling back to locale \"en_US\". To specify the locale, set the property on destination \"ErpQueryEndpoint\" or provide the locale as explicit argument. (END OF LOG ENTRY)" }
   2019-01-31T09:49:41.38+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.384Z","written_ts":3583843471009201,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.s4hana.connectivity.ErpConfigContext","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"INFO","categories":[],"msg":"Falling back to locale \"en_US\". To specify the locale, set the property on destination \"ErpQueryEndpoint\" or provide the locale as explicit argument. (END OF LOG ENTRY)" }
   2019-01-31T09:49:41.38+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.386Z","written_ts":3583843472964643,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.odatav2.connectivity.ODataQuery","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"ERROR","categories":[],"msg":"Successfully connected to destination service." }
   2019-01-31T09:49:41.64+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.639Z","written_ts":3583843726319402,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.odatav2.connectivity.cache.metadata.GuavaMetadataCache","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"ERROR","categories":[],"msg":"Error occurred during populating metadata : com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler$ErpODataException: " }
   2019-01-31T09:49:41.64+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.640Z","written_ts":3583843726825327,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.odatav2.connectivity.ODataQuery","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"ERROR","categories":[],"msg":"Successfully connected to destination service." }
   2019-01-31T09:49:41.75+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.751Z","written_ts":3583843838110377,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.odatav2.connectivity.cache.metadata.GuavaMetadataCache","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"ERROR","categories":[],"msg":"Error occurred during populating metadata : com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler$ErpODataException: " }
   2019-01-31T09:49:41.75+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.752Z","written_ts":3583843838680972,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.odatav2.connectivity.ODataQuery","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"ERROR","categories":[],"msg":"Successfully connected to destination service." }
   2019-01-31T09:49:41.86+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.864Z","written_ts":3583843950626395,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.odatav2.connectivity.cache.metadata.GuavaMetadataCache","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"ERROR","categories":[],"msg":"Error occurred during populating metadata : com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler$ErpODataException: " }
   2019-01-31T09:49:41.86+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.864Z","written_ts":3583843950942012,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.odatav2.connectivity.ODataQuery","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"ERROR","categories":[],"msg":"Successfully connected to destination service." }
   2019-01-31T09:49:41.97+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.977Z","written_ts":3583844063669784,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.sdk.odatav2.connectivity.cache.metadata.GuavaMetadataCache","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"ERROR","categories":[],"msg":"Error occurred during populating metadata : com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler$ErpODataException: " }
   2019-01-31T09:49:41.98+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.980Z","written_ts":3583844066956104,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand","thread":"hystrix-com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand#t=#u=-6","level":"WARN","categories":[],"msg":"Fallback called because of exception:","stacktrace":["java.util.concurrent.ExecutionException: com.sap.cloud.sdk.odatav2.connectivity.ODataException: Failed to execute OData Metadata request.","\tat com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:526)","\tat com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:487)","\tat com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:83)","\tat com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly(Uninterruptibles.java:196)","\tat com.google.common.cache.LocalCache$Segment.getAndRecordStats(LocalCache.java:2311)","\tat com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2277)","\tat com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2154)","\tat com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2044)","\tat com.google.common.cache.LocalCache.get(LocalCache.java:3951)","\tat com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4870)","\tat com.sap.cloud.sdk.frameworks.hystrix.CachingCommand.run(CachingCommand.java:178)","\tat com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:302)","\tat com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:298)","\tat rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)","\tat rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)","\tat rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)","\tat rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)","\tat rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)","\tat rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)","\tat rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)","\tat rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)","\tat rx.Observable.unsafeSubscribe(Observable.java:10256)","\tat rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51)","\tat rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)","\tat rx.Observable.unsafeSubscribe(Observable.java:10256)","\tat rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41)","\tat rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30)","\tat rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)","\tat rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)","\tat rx.Observable.unsafeSubscribe(Observable.java:10256)","\tat rx.internal.operators.OperatorSubscribeOn$SubscribeOnSubscriber.call(OperatorSubscribeOn.java:100)","\tat com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:56)","\tat com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:47)","\tat com.sap.xs.threadlocal.hystrix.ThreadLocalCallable.call(ThreadLocalCallable.java:29)","\tat com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction.call(HystrixContexSchedulerAction.java:69)","\tat rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)","\tat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)","\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)","\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)","\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)","\tat java.lang.Thread.run(Thread.java:836)","Caused by: com.sap.cloud.sdk.odatav2.connectivity.ODataException: Failed to execute OData Metadata request.","\tat com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.loadEntriesFromDestination(ODataQuery.java:215)","\tat com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.internalExecute(ODataQuery.java:167)","\tat com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:105)","\tat com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:150)","\tat com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:136)","\tat com.sap.cloud.sdk.s4hana.datamodel.odata.helper.FluentHelperRead.execute(FluentHelperRead.java:197)","\tat com.sap.cloud.sdk.s4hana.datamodel.odata.helper.FluentHelperRead.execute(FluentHelperRead.java:23)","\tat com.sap.cloud.sdk.s4hana.datamodel.odata.helper.FluentHelperBasic.execute(FluentHelperBasic.java:85)","\tat com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand.runCacheable(GetAllProductsCommand.java:53)","\tat com.sap.cloud.s4hana.examples.addressmgr.commands.GetAllProductsCommand.runCacheable(GetAllProductsCommand.java:19)","\tat com.google.common.cache.LocalCache$LocalManualCache$1.load(LocalCache.java:4875)","\tat com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3527)","\tat com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2276)","\t... 35 more","Caused by: com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler$ErpODataException: ","\tat com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler.createException(ODataVdmErrorResultHandler.java:105)","\tat com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler.createError(ODataVdmErrorResultHandler.java:86)","\tat com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler.createError(ODataVdmErrorResultHandler.java:31)","\tat com.sap.cloud.sdk.odatav2.connectivity.internal.ODataConnectivityUtil.checkHttpStatus(ODataConnectivityUtil.java:185)","\tat com.sap.cloud.sdk.odatav2.connectivity.cache.metadata.GuavaMetadataCache.getEdm(GuavaMetadataCache.java:131)","\tat com.sap.cloud.sdk.odatav2.connectivity.cache.metadata.GuavaMetadataCache.getEdm(GuavaMetadataCache.java:110)","\tat com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.loadMetadata(ODataQuery.java:250)","\tat com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.loadEntriesFromDestination(ODataQuery.java:213)","\t... 47 more"] }
   2019-01-31T09:49:41.98+0530 [APP/PROC/WEB/0] OUT { "written_at":"2019-01-31T04:19:41.981Z","written_ts":3583844067895750,"component_id":"ae30fb63-3ddc-42e4-95c9-c190e7c5950e","component_name":"address-manager","DCComponent":"","HOST":"0ca2bbc0-3f71-4dfd-5e4e-8577","organization_name":"-","component_type":"application","space_name":"dev","SERVER":"main","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"71c96992-bd88-41e6-ac83-bdcc94e38fc6","Application":"address-manager","container_id":"10.0.137.101","type":"log","logger":"com.sap.cloud.s4hana.examples.addressmgr.BusinessPartnerServlet","thread":"http-bio-0.0.0.0-8080-exec-10","level":"INFO","categories":[],"msg":"Armoghan says - []" }
   address-manager-grumpy-otter.cfapps.eu10.hana.ondemand.com - [2019-01-31T04:19:41.027+0000] "GET /api/business-partners HTTP/1.1" 200 0 2 "https://approuter-p1942271708trial.cfapps.eu10.hana.ondemand.com/address-manager/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" "-" "10.0.137.101:61002" x_forwarded_for:"-" x_forwarded_proto:"https" vcap_request_id:"4b3e148c-ac4a-444f-5676-00f83c7fda10" response_time:0.963585441 app_id:"ae30fb63-3ddc-42e4-95c9-c190e7c5950e" app_index:"0" x_correlationid:"c3b465c1-cdad-4fe4-7033-9c9b3d8b7971" x_b3_traceid:"ee848c54fc661573" x_b3_spanid:"ee848c54fc661573" x_b3_parentspanid:"-"

A: When connecting against an On-Premise system, you need to have a connectivity service instance bound to your application, in addition to xs-uaa and destination service instances. Also, make sure that you have configured the Cloud Connector correctly.
The following deep dive describes the required prerequisites to connect to S/4HANA OP from SAP Cloud Platform Cloud Foundry (see the abstract Running Business Partner Calls Against S/4HANA On-Premise)

A: I had not put any value in 'Location' field of my destination, I am able to fetch values from a standard OData service now.


text:
Q: How to filter-out error-page links when scraping Ebay product-pages? I built a bot in Python that scrapes eBay product listing links from HTML.
Every link is pointing to the product page.
However, the first one is pointing to an error page like:
https://www.ebay.com/itm/01920391?epid=26039819083&_trkparms=ispr%3D1&hash=item3b542eae7a:g:FQkAAOSwK21gKvEZ&amdata=enc%3AAQAFAAACcBaobrjLl8XobRIiIML1V4Imu%252Fn%252BzU5L90Z278x5ickkrDx%252B2NLp21dg6hHbHAkGMYdiW1E6zjXxnQ0bf7c%252Fx%252Fvs5PW%252FYFw1ZdbGMi8wsGV6qXw8OFLl4Os1ACX3bnQxFkVpRib9hMb5gVyLha4q9L0xiporu5InbX0LrSgg7nCCCwtC7y3vOE3hc8PszsrXWLb5KFdj7%252BD98et12MdkEfMPFhJZuS%252BkFsp2esVTRCYctOhcwzPSdfzCOYprlr2miQc4czCv1Tcfs3LKUPJn8uQyRc%252BAnKY1oyTeYnJ7wYuGkBU%252FSVYjziLBaPhT%252FlVu0hR9ZX6OnAeRaJ1g0iCaDjrRXEXRwUO87riWeI8kExm1zzY7QicPeMnfWZdBvVhg05GOScPOlLTVPHakqGLX0y2GUXV6fkTLua3nSF5YBmLX%252FqdCxT6yS0dutVs5MPWvQYlN474hUzbubkZVAs7Y%252BBBEsHrGjVzCj0szZ6w1%252BHgkV5O9jrXGnyew5%252Bnxy7VCq5xEkUDIt1nSg996AeDksNmSNumhfsIOGltIXbqAbjqEUpPcVO%252BDPymxlh0iMxCZQalYnmljBRzKILYWkES0vfA14Gh5E7KWrztdC6WzEEFtgVuABakQ1eAOZnuEueqK6IakC%252BIfRbXv96Tv01IPDvwPeM8wMo6j8bMjY3D5KHS5EXPVdHKUnjCJiYCcVUqcKwhL6eN2MZ%252Bn9yxmWESUPN394NPrX%252FI2z7t0Bbo7iqmsWNQcyi0EHzDwJPMK%252FNSif8%252F2adRF7dT1JrbL9sryKSN2kv9OsdGQ0fMMC1LV3Ph43HivUJdqkgjGxqEqX5v1xQ%253D%253D%7Ccksum%3A25481541593068896952f4834d93a0bb998f5b5ba5fe%7Campid%3APL_CLK%7Cclp%3A2334524

Code
import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver

browser = webdriver.Chrome('/Users/admin/eBay/chromedriver')

#error = browser.find_element_by_xpath("//*[@id='wrapper']/div[1]/div/div/p")

url = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=New+Big+Frame+Square+Sunglasses+Fashion+Trend+All-match+Women%27s+Sunglasses+Cross-border+Hot+Sale+Sunglasses&_sacat=0"
r = requests.get(url)
soup = BeautifulSoup(r.content, features="lxml")

listings = soup.select("li a")

for a in listings:
    link = a["href"]
    if link.startswith("https://www.ebay.com/itm/"):
        page = browser.get(link)

How can I remove or ignore the error-page link?

A: If you want to skip first link you can use list slicing with [1:]:
...

for a in listings[1:]:  # <--- ignore first link
    link = a["href"]
    if link.startswith("https://www.ebay.com/itm/"):
        page = browser.get(link)

A: I would have gone similar way to @SIM and relied on faster css filtering and using css classes (generally 2nd fastest way of matching on nodes in css after id).
links = [i['href'] for i in soup.select('#srp-river-results .s-item__link')]

The introduction of the leading id limits results to the actual listings block.
If you are somehow worried that urls with other start strings might occur, which seems unlikely given the consistent design of these pages, you can add in a css attribute = value selector with ^ starts with operator:
links = [i['href'] for i in soup.select('#srp-river-results .s-item__link[href^="https://www.ebay.com/itm/"]')]

In case of wanting more info then set listings as
listings = soup.select('#srp-river-results .s-item')

Then access links with:
links = [listing.select_one('.s-item__link[href^="https://www.ebay.com/itm/"]')['href'] for listing in listings]

A: cut out that link using the if statement
import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver

browser = webdriver.Chrome('C:\Program Files (x86)\chromedriver.exe')

#error = browser.find_element_by_xpath("//*[@id='wrapper']/div[1]/div/div/p")

url = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=New+Big+Frame+Square+Sunglasses+Fashion+Trend+All-match+Women%27s+Sunglasses+Cross-border+Hot+Sale+Sunglasses&_sacat=0"
r = requests.get(url)
soup = BeautifulSoup(r.content, features="lxml")

listings = soup.select("li a")
b=1

error_page ='https://www.ebay.com/itm/01920391?epid=26039819083&_trkparms=ispr%3D1&hash=item3b542eae7a:g:FQkAAOSwK21gKvEZ&amdata=enc%3AAQAFAAACcBaobrjLl8XobRIiIML1V4Imu%252Fn%252BzU5L90Z278x5ickkrDx%252B2NLp21dg6hHbHAkGMYdiW1E6zjXxnQ0bf7c%252Fx%252Fvs5PW%252FYFw1ZdbGMi8wsGV6qXw8OFLl4Os1ACX3bnQxFkVpRib9hMb5gVyLha4q9L0xiporu5InbX0LrSgg7nCCCwtC7y3vOE3hc8PszsrXWLb5KFdj7%252BD98et12MdkEfMPFhJZuS%252BkFsp2esVTRCYctOhcwzPSdfzCOYprlr2miQc4czCv1Tcfs3LKUPJn8uQyRc%252BAnKY1oyTeYnJ7wYuGkBU%252FSVYjziLBaPhT%252FlVu0hR9ZX6OnAeRaJ1g0iCaDjrRXEXRwUO87riWeI8kExm1zzY7QicPeMnfWZdBvVhg05GOScPOlLTVPHakqGLX0y2GUXV6fkTLua3nSF5YBmLX%252FqdCxT6yS0dutVs5MPWvQYlN474hUzbubkZVAs7Y%252BBBEsHrGjVzCj0szZ6w1%252BHgkV5O9jrXGnyew5%252Bnxy7VCq5xEkUDIt1nSg996AeDksNmSNumhfsIOGltIXbqAbjqEUpPcVO%252BDPymxlh0iMxCZQalYnmljBRzKILYWkES0vfA14Gh5E7KWrztdC6WzEEFtgVuABakQ1eAOZnuEueqK6IakC%252BIfRbXv96Tv01IPDvwPeM8wMo6j8bMjY3D5KHS5EXPVdHKUnjCJiYCcVUqcKwhL6eN2MZ%252Bn9yxmWESUPN394NPrX%252FI2z7t0Bbo7iqmsWNQcyi0EHzDwJPMK%252FNSif8%252F2adRF7dT1JrbL9sryKSN2kv9OsdGQ0fMMC1LV3Ph43HivUJdqkgjGxqEqX5v1xQ%253D%253D%7Ccksum%3A25481541593068896952f4834d93a0bb998f5b5ba5fe%7Campid%3APL_CLK%7Cclp%3A2334524'
for a in listings:

    link = a["href"]
    if link.startswith("https://www.ebay.com/itm/") and link !=error_page:

        page = browser.get(link)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kestrel vs IIS+Kestrel performance (throughput) using .NET Core 2.2 For the .NET Core 2.2 application deployed on a single AWS EC2 host I am comparing IIS hosting vs plain Kestrel hosting.
For IIS configuration I followed MS documentation.
For Kestrel I simply used:
dotnet app.dll --server.urls http://*:5000

I am running "stress" test with JMeter in order to compare throughput. This test is simply calling app's endpoint with 100 threads for 10 seconds duration (5 seconds warmup). Note, that endpoint is basically getting same data from MSSQL Server database on each call, no caching etc.
As a result, Kestrel fails 75% of requests with socket closed/timeout errors:

QUESTION: What kind of configuration error can lead to such Kestrel behavior? I've tried to use a basic nginx reverse proxy in front of Kestrel, but still getting the same results.

A: It turned out, that described behavior occurs when testing the performance of synchronous endpoint.
By following Thread injection algorithm, CLR will have only minWorkerThreads/minIoThreads to process requests and since "stress" test uses more threads than created at the moment we wait for new threads - which leads to almost linear growth of response time.
Switching to asynchronous eliminates the difference in performance, see:

References:

*

*ASP.NET MVC and Web API - Comparison of Async / Sync Actions

*Official docs on CLR Thread Injection algorithm

*Related SO issue


text:
Q: What do people mean when they say "in memory"? This definitely is a fundamental knowledge gap for me but when people say in memory what do they usually mean?
For example, in my mind it means a running machine and you have some process like redis that starts up on that machine where the data is stored but I'm not sure if that's correct. I'm thinking they don't mean you spin up a web service and have a data structure that stores data or maybe that also is in memory?
Thanks in advance for any clarity.

A: In memory i.e. data loaded to RAM, vs. data stored on storage devices e.g. SSD, HDD.
For example, some databases loads everything to RAM, some other databases load indexes to RAM and some load indexes and enables swapping if they don't fit (on expense of performance when this happens) and there multiple other options too. The point is different databases can be in-memory, partially in-memory or not in-memory.
If you read an entire file to a buffer/string, it's in memory, if you go through it's stream, processing only the current record, then the file does not need to fit in memory.
When you keep something in memory, you can access it faster (the CPU actually loads from it's cache the fastest, then from the RAM, then from storage (where flash is much faster than magnetic) and even with these speed depends on a variety of technologies in play.
In general, RAM is more expensive than storage and it is usually volatile (as in does not keep state when powered down). If you want to store a lot of data in memory, your hardware bills will be higher, however, you can achieve a lower latency.
In memory can refer to what's loaded to RAM in your application or in a database you are sizing (allocating/pricing HW for).


text:
Q: remarks in an alter table I was supposed to do a remarks (in order to add a comment) during my table creation but I forgot.
How can I do it in an alter?
I use postgres

A: https://www.postgresql.org/docs/current/static/sql-comment.html

COMMENT stores a comment about a database object.
Only one comment string is stored for each object, so to modify a
  comment, issue a new COMMENT command for the same object. To remove a
  comment, write NULL in place of the text string.
Examples
Attach a comment to the table mytable:
COMMENT ON TABLE mytable IS 'This is my table.';


text:
Q: PHP foreach(...) question I was wondering if using
foreach(get_some_array() as $boo) do_something...

is slower than
$arr = get_some_array();
foreach($arr as $boo) do_something...

I mean would get_some_array() be called like 10000000 times if the array would have so many elements (in the 1st example) ?

A: No, that function will be called just 1 time.
You can verify this by doing:
<?php
function get()
{
    echo "getting\n";

    return array('a', 'b', 'c', 'd');
}

foreach (get() as $v) {
    echo $v . "\n";
}
?>

Here it outputs:
murilo@mac:regionais$ php -f teste.php
getting
a
b
c
d

A: $arr = get_some_array(); theoretically adds zero time to this equation, so it really wont make a difference what you use here.


text:
Q: SOAP Request in PHP Good morning everybody,
I searched this website for a helpful response for integrating a SOAP Request in PHP, but I didn't find anything that solved my problem.
I'm new to SOAP and can't figure out why I receive following error message as response:
object(stdClass)#3 (1) { ["CU_Check_BalanceResult"]=> object(stdClass)#4 (1) { ["error"]=> string(20) "Wrong Authentication" } }
This is my PHP Script:
<?php

/* Initialize webservice with your WSDL */
$client = new SoapClient("https://loyalty.brain-behind.com/CU_WebAPI.asmx?wsdl");

class CU_Check_Balance{
    public $provider,
    $password,
    $CardID,
    $TerminalID;
    }

$parameters = new CU_Check_Balance();
$parameters->provider = "string";
$parameters->password = "string";
$parameters->CardID = "string";
$parameters->TerminalID = "string";

$response = $client->CU_Check_Balance($parameters);

var_dump($response);

?>

The corresponding WSDL can be found here:
http://loyalty.brain-behind.com/CU_WebAPI.asmx?wsdl
I also tried to implement it in JS, but that didn't work either.
I also installed SOAP UI, made a test project with this wsdl and it worked fine.
This is the example request I got with SOAP UI:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:loy="https://loyalty.brain-behind.com">
   <soapenv:Header>
      <loy:AuthSoapHd3>

         <loy:provider>string</loy:provider><loy:password>string</loy:password>
      </loy:AuthSoapHd3>
   </soapenv:Header>
   <soapenv:Body>
      <loy:CU_Check_Balance>

         <loy:CardID>string</loy:CardID><loy:TerminalID>string</loy:TerminalID>
      </loy:CU_Check_Balance>
   </soapenv:Body>
</soapenv:Envelope>

Please could somebody help me to get this thing working in php.

A: I have been solving this question too, hope this can help, this is workable solution with brain-behind.com. Two variants - test and production credentials.
<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Europe/Prague');

//*
$wsdl = "https://loyalty.brain-behind.com/CU_WebAPI.asmx?wsdl";
/*/
$wsdl = "https://testo.brain-behind.com/CU_WebAPI.asmx?wsdl"; //for your testing credentials, change only this $wsdl address, not $location
//*/
$location = "https://loyalty.brain-behind.com";

$provider = "TESTBB|1111";
$password = "abcdefghijkl";
$cardId = '111111111111111';
$terminalId = 'AA111111';

$login = new stdClass();
$login->provider = $provider;
$login->password = $password;

$params = new stdClass();
$params->CardID = $cardId;
$params->TerminalID = $terminalId;

$dump = array("trace" => 1, "exceptions" => 0);

///////////////////////////////////////////////////////////////////////////////////////////

//*
$soap = new SoapClient($wsdl);
/*/
$soap = new SoapClient($wsdl, $dump); // trace ON, then print LastRequest, LastResponse, LastRequestHeaders
//*/

//var_dump($soap->__getFunctions());
//var_dump($soap->__getTypes());

$header = new SoapHeader($location, 'AuthSoapHd3', $login);
$soap->__setSoapHeaders($header);

try {
    // check balance
    $response = $soap->CU_Check_Balance($params);
    var_dump($response);

    //////////////////////////////////////

    $count = 2;
    $ticketPrice = 28;
    $cashback = 2; //cashback per ticket
    $params->PurchaseDate = date('c'); //UTF format
    $params->PurchaseAmount = $count * $ticketPrice; // in Euros
    $params->BonusAmount = $count * $cashback * 100; // in Eurocents
    $params->Encryption='';

    // add kredit to account
    $response = $soap->CU_Add_Bonus($params);
    var_dump($response);
} catch (Exception $exc) {
    echo 'Exception:
';
    print_r($exc->getTrace());
}

echo '

LastRequest:';
var_dump($soap->__getLastRequest());
echo '

LastResponse:';
var_dump($soap->__getLastResponse());
echo '

LastHeaders:';
var_dump($soap->__getLastRequestHeaders());


text:
Q: MIFARE DESFire EV2 - How to run command InitializeKeySet How to run MIFARE DESFire EV2 command InitializeKeySet (void initializeKeySet(byte ikeySetNo,DESFireEV1.KeyType ksType)?
I get an exception like "Invalid keynumber specified" (error code 0x7E).


text:
Q: backup github repo with client access token we have a customer that wants us to backup his private github repo. He wants us to use a client access token with read only access.
Is this feasible? is it possible to do this on a regular basis with the same token? Any recommendation on the best way to do this ?
Thanks
Evan


text:
Q: How do I measure percent CPU usage using prometheus? I'm trying to use the prometheus measurements to get percent CPU usage for each micro service running in Kubernetes to optimize CPU resources and limits.
I have a setup where for each customer there are 4 micro services running on the server.  Each micro service has a separate memory resource and limit and separate CPU resource and limit.  To get the average from prometheus I am using the following query:
avg_over_time(sum(rate(container_cpu_usage_seconds_total{name=~"^k8s_.", namespace=~"$namespace", container_name!="POD", pod=~"^$Deployment.$"}[5m]))[24h:5m]) /
avg_over_time(sum(container_spec_cpu_quota{name=~"^k8s_.", namespace=~"$namespace",container_name!="POD", pod=~"^$Deployment.$"}/container_spec_cpu_period{name=~"^k8s_.",namespace=~"$namespace", container_name!="POD", pod=~"^$Deployment.$"})[24h:5m]) * 100
To check that the value above is correct, I go into each Kubernetes pod and check the CPU usage using the command:
kubectl -n {namespace} top pod {Deployment}
To check the CPU limit I use the command:
kubectl -n {namespace} describe pod {Deployment}
Where I get the CPU limit.
Then I do the calculation:
CPU usage divided by CPU limit times 100 equals current percent of CPU usage.
The values I get from the CPU usage and limit in Kubernetes are different from the values I get using the prometheus query (Some of the values I get are close and some are quite off).
Here is an example of CPU usage in Percent from Prometheus and from Kubernetes:

Customer
Service
Prometheus
Kubernetes

Customer A
Service 1
0.216
0.2

Service 2
0.137
0.2

Service 3
0.445
0.45

Service 4
0.165
0.2

Customer B
Service 1
0.139
0.2

Service 2
0.0917
0.2

Service 3
0.5739
0.5

Service 4
0.0972
0.2

Anyone have any comments whether I am doing the measurements correctly? Is there a mistake in my prometheus query or how I get the values from Kubernetes? I want to make sure that I am measuring the percent CPU usage correctly using prometheus

A: Can you try the following query for one service and modify the query according your requirement:
sum (rate (container_cpu_usage_seconds_total{id="/"}[1m])) / sum (machine_cpu_cores) * 100
I also track the CPU usage for each pod.
sum (rate (container_cpu_usage_seconds_total{image!=""}[1m])) by (pod_name) I have a complete kubernetes-prometheus solution on GitHub,
maybe can help you with more metrics: https://github.com/camilb/prometheus-kubernetes.
I hope this will help! The result is pretty much the same as the Windows performance manager. So, for CPU % for running services (tasks, processes):
sum by (process,hostname)(irate(wmi_process_cpu_time_total{scaleset="name", process=~


text:
Q: OpenFileDialog is not opening the file I have bound the openFileDialog control with button. On button event, I am calling the openFileDialog control.
Now, when I am running my application, the openFileDialog box gets open but does not select the file. The open button is not working.

Example code:
    private void button1_Click(object sender, EventArgs e)
    {
       openFileDialog1.ShowDialog();

    }

    private void openFileDialog1_FileOk_1(object sender, CancelEventArgs e)
    {
        // logic written here
    }

It was working fine earlier but now its not working.

A: You need to use the DialogResult to get the event of open confirmation by the user. Then you can use a stream to read the file. Here is some sample code (provided by MS in the MSDN - source:https://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog(v=vs.110).aspx):
private void button1_Click(object sender, System.EventArgs e)
{
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\" ;
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            if ((myStream = openFileDialog1.OpenFile()) != null)
            {
                using (myStream)
                {
                    // Some logic here
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Failed to open file. Original error: " + ex.Message);
        }
    }
}

A:
Answer post edits
The included code shows the method openFileDialog1_FileOk_1 the "_1" at the end suggest to me that you had some issues binding the event. Perhaps there was at some point a method openFileDialog1_FileOk caused conflict.
You should check if the method is correctly bound to the event.
For that I will remit you to my answer to How to change the name of an existing event handler?
For abstract you want to see what method is bound to the event. You can do it from the properties panel, or by checking the form designer file (that is named something .Designer.cs for example: Form1.Designer.cs).
Addendum: Consider adding a break point in the event handler. It will allow you to debug step by step what is happening. Also, it will allow you notice if the event handlers is not being executed at all, which would suggest that the method is NOT correctly bound to the event.

Original Answer
OpenFileDialog Does not open files, it barely select thems and makes the selection available for your application to do whatever your applications is intended to do with those files.
The following is the usage pattern from the MSDN article linked above:
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = openFileDialog1.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show
        (
            "Error: Could not read file from disk. Original error: " + ex.Message
        );
    }
}

Now, observe that after cheking the result of ShowDialog - which returns once the dialogs is closed - the codes uses the method OpenFile to actually open the file. The result is a stream that you can process anyway you prefer.
Alternatively you can retrieve the selected files via the property FileNames, which returns an array of strings. If you have configured the dialog to only allow selecting asingle file you are ok to use FileName instead.

Addendum, if by "Open" you mean to invoke the default application associated with the selected file to open the file. You can accomplish that by passing the file path to System.Diagnostics.Process.Start.

A:     if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string name = openFileDialog1.FileName;
object objOpt = Type.Missing;
                var excelApp = new Excel.Application();
                Excel.Workbook wbclass = excelApp.Workbooks.Open(name, objOpt,
                                                                true,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt,
                                                                objOpt);

            }


text:
Q: Django Models: Inline has no ForeignKey to I have read a few of these question on stack already but I can't get my desired results.
I have a simple models.Model class, named Driftwood() in an app named driftwoods. In another app galleries I have the model GalleryPiece which uses a Driftwood() ForeginKey().
I could make Driftwood() have a ForiegnKey() to a GalleryPiece(), which by looking at other code samples should work. But I was wanting to reuse my Driftwood() model in a store app, using a ForeingKey() the same way I do in GalleryPiece(), but with not to ties to the galleries app.
Is this possible or do I have to make a GalleryDriftwood() and a ProductDriftwood() model? I know this makes more sense but I would perfer all my Driftwood() to be in one table.
myproject/driftwoods/models.py
class Size( models.Model ):
    length = models.IntegerField()
    width  = models.IntegerField()
    height = models.IntegerField()

class Driftwood( models.Model ):
    name            = models.CharField( max_length=60, default='driftwood' )
    weight          = models.FloatField()
    size            = models.ForeignKey( Size )
    image           = models.ImageField( upload_to='static/driftwoods/' )

myproject/galleries/models.py
from driftwoods.models import Driftwood

class Gallary( models.Model ):
    name            = models.CharField( max_length=60 )
    image           = models.ImageField( upload_to='static/galleries/' )

class GallaryPiece( models.Model ):
    name            = models.CharField( max_length=60 )
    gallary         = models.ForeignKey( Gallary )
    driftwood       = models.ForeignKey( Driftwood )

I was going to use the store app like so.
from driftwoods.models import Driftwood

class Product( models.Model ):
    driftwood = models.ForeignKey( Driftwood )
    price     = models.FloatField()

The only way I have of adding a Driftwood() model is through an TabularInline class in gallaries/admin.py.
myproject/driftwoods/admin.py
# NOTHING, ADD DRIFTWOOD BY CREATING A GALLEY PIECE

myproject/galleries/admin.py
from driftwoods.models import Driftwood

class DriftwoodInline( admin.TabularInline ):
    model = Driftwood

class GallaryAdmin( admin.ModelAdmin ):
    fieldsets = [
            (None,                  {'fields': ['name']} ),
            ('Date Information',    {'fields': ['pub_date']} ),
            ('Gallary Image',       {'fields': ['image']} ),
    ]

class GallaryPieceAdmin( admin.ModelAdmin ):
    fieldsets = [
            (None,                  {'fields': ['name']} ),
            ('Date Information',    {'fields': ['pub_date']} ),
            ('Description',         {'fields': ['description']} ),
    ]
    inlines = [DriftwoodInline]

admin.site.register( Gallary, GallaryAdmin )
admin.site.register( GallaryPiece, GallaryPieceAdmin )

P.S Im going on a boat right now, so I will be back in about 2-3 hours to pick an answer. As always I appreciate the help (Who doesn't).


text:
Q: What do you have on your (physical) desk? I'm settling in a new office and except the obvious (PC, screen, mouse, keyboard) and the can't-work-without earphones, tissue box, Philips screwdriver and stack (overflow?) of papers my table looks poor, empty and not functional.

 Which tools of the trade do you keep in your desk? What proves useful to keep within an arm's reach?

A: An external hard drive dock always comes along handy.  Such as this one.

A: I always keep one of my own business cards on my desk because I can never seem to remember my own work phone number when I'm on the phone with someone who needs it.
--
bmb

A: *

*My coffee mug

*My laptop on a stand with 2nd monitor

*Baseline desktop machine for testing

*Half a library of IT & programming language reference books

*My coffee mug

*Power strip so I don't have to crawl under my desk to plug all my crap in

*Jug o' Purell hand-sanitizer for fighting off the crud from all of the keyboards in our building that have not been cleaned for a decade

*My coffee mug

*Compressed air.  Never know when you need to blow out a machine or play ping-pong ball hockey

*A small whiteboard with those awesome smelling markers

*Awesome smelling whiteboard cleaner

*My coffee mug

*Screen wipes for those SCHMOES that can't keep their stinkin' fingers off of my monitor when they're showing me something

*Dust bunnies that would choke a cat (in stark contrast to the jug o' Purell)

*Dilbert books

*My coffee mug

*Calvin and Hobbes books

*Fox Trot books

*A Bible

*Oh yeah, and lots and lots of pictures of my wife and kids

And my coffee mug

A: I have the cables necessary to setup and work on a second PC ... monitor, keyboard and mouse, power cable plugged in, ethernet cable plugged in.  That way, when I am in a hurry to fix a problem I can plug the PC and go.

A: One sixth of my 3'x8' desk surface is occupied by a folded blanket that is usually occupied by a big, fat, white cat.  There's something incredibly calming about this animal who has no cares except eating and getting his ears scratched.  Very calming.

A: Those things should be easely reache :

*

*USB Port by an extension cable laying on the desk

*ESata Port by an extension once again, this is more and more current these days

*A good mouse pad with wrist rest padded

*Monitor stand (allsop make a good one) to elevate the monitor so you neck is straight

*A coffe cup and a coffee brewer can also be a good ideas!

A: Books like the below.  Aside from my computer I find that nothing is as helpful has having books to be able grab and open.  My books of course have lots of the Post-It Flags marking important sections.  When the network is down, firing up Google or Safari isn't an option, and I am not able to remember everything.

*

*TCP/IP Network Administration

*Network Troubleshooting Tools

*Learning the bash Shell

*And so on...

A: I also have:

*

*mousepad

*pen

*PostITs

*Thermoisolated tea cup

A: moleskine notebook
Ball of whacks
pencils, keyboard and mouse
...and sometimes m&ms.

A: Pumpkin seeds, peanuts, sunflower seeds, whichever, must have the the 1500 hour snack on hand to keep my head from diving into my keyboard


text:
Q: GeoFire ListView Query doesn't display text in the listview I am creating a Firebase GeoFire Query to display results in a ListView. I have got this ListView example from emanuelet. I have got it working with the gist shared by emanuelet now I also get the values in the logcat for geoQuery.
D/GeoPostsFragment: Key -KMsopZitLFzcxFuPOCn entered the search area at [40.7853889,-122.4056973]
D/GeoPostsFragment: Key -KMu2IcjIyMx5Qpb5Kfh entered the search area at [40.7853889,-122.4056973]
D/GeoPostsFragment: Key -KMz3knxKsAAixlf4ijY entered the search area at [40.7853889,-122.4056973]
D/GeoPostsFragment: Key -KMzXh2Kf7nLdOPqnMpY entered the search area at [40.7853889,-122.4056973]
D/GeoPostsFragment: Key -KN1Z1qZZZzksPlmwG75 entered the search area at [40.7853889,-122.4056973]
D/GeoPostsFragment: Key -KN6ltFbtLgpR5GbPki6 entered the search area at [40.7853889,-122.4056973]
D/GeoPostsFragment: All initial data has been loaded and events have been fired!

This is how I have structured the GeoFire data on firebase:

Here is my fragment for the GeoQuery.
@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(LOG_TAG, "onCreate");
        super.onCreate(savedInstanceState);
        mContext = getActivity();

        settings = PreferenceManager.getDefaultSharedPreferences(mContext);
        setHasOptionsMenu(true);

        mFirebaseRef = FirebaseDatabase.getInstance().getReference().child("posts");
        //I initialize the object that will be used to retrieve the location
        mGeoRef = FirebaseDatabase.getInstance().getReference("GeoFire");
        geoFire = new GeoFire(mGeoRef);

        mItemListAdapter = new ItemListAdapter(mFirebaseRef.equalTo("posts"), post, R.layout.include_post_text, getActivity());
    }

    @Override
    public void onStart() {
        super.onStart();
        center = new GeoLocation(40.7853889, -122.4056973);
        if (center.latitude != 0 && center.longitude != 0 && !mActiveGeoQuery) {
            startGeoQuery();
        } else if (mActiveGeoQuery) {
            Log.d(LOG_TAG, "geoquery already active");
        } else {
            Log.d(LOG_TAG, "center not setted");
            //I first try to set the center at the Last Known Location if retrieved
            if (Double.isNaN(mLatitudeText) && mLatitudeText != 0) {
                Log.d(LOG_TAG, "center setted from fused location");
                center = new GeoLocation(40.7853889, -122.4056973);
                startGeoQuery();

            }
        }
        checkForItems();
    }

    @Override
    public void onResume() {
        super.onResume();
            mItemListAdapter.notifyDataSetChanged();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.geo_fragment, container, false);

        ButterKnife.bind(this, rootView);

        mListView = (ListView) mListContainer.findViewById(R.id.list);
        mListContainer.setViewState(MultiStateView.VIEW_STATE_LOADING);
        mListContainer.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Post cursor = (Post) mListView.getItemAtPosition(i);

                if (cursor != null) {
                    mCallbacks.onItemSelected(cursor, view);
                }
                mPosition = i;
            }
        });
        return rootView;
    }

    private void bindListView() {
        mListView.setAdapter(mItemListAdapter);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    }

    private void startGeoQuery() {
        // safety net in case that for some reasons the returned radius is 0
        query = geoFire.queryAtLocation(new GeoLocation(40.7853889, -122.4056973), 1);
        Log.d(LOG_TAG, "center: " + center.toString() + ", radius: " + 0.2);
        query.addGeoQueryEventListener(new GeoQueryEventListener() {
            @Override
            public void onKeyEntered(String key, GeoLocation location) {
                Log.d(LOG_TAG, "Key " + key + " entered the search area at [" + location.latitude + "," + location.longitude + "]");
                DatabaseReference tempRef = mFirebaseRef.child("posts")
                        .child(key);
                tempRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot snapshot) {
                        // I  add the deal only if it doesn't exist already in the adapter
                        String key = snapshot.getKey();
                        if (!mItemListAdapter.exists(key)) {
                            Log.d(LOG_TAG, "item added " + key);
                            mItemListAdapter.addSingle(snapshot);
                            Log.d(LOG_TAG,"Snapshot added " + snapshot);
                            mItemListAdapter.notifyDataSetChanged();
                            mListContainer.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            //...otherwise I will update the record
                            Log.d(LOG_TAG, "item updated: " + key);
                            mItemListAdapter.update(snapshot, key);
                            mItemListAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError firebaseError) {
                        Log.d(LOG_TAG, "cancelled with error:" + firebaseError.getMessage());
                    }
                });
            }

            @Override
            public void onKeyExited(String key) {
                Log.d(LOG_TAG, "deal " + key + " is no longer in the search area");
                mItemListAdapter.remove(key);
                isListEmpty();
            }

            @Override
            public void onKeyMoved(String key, GeoLocation location) {
                Log.d(LOG_TAG, String.format("Key " + key + " moved within the search area to [%f,%f]", location.latitude, location.longitude));
            }

            @Override
            public void onGeoQueryReady() {
                Log.d(LOG_TAG, "All initial data has been loaded and events have been fired!");
                isListEmpty();
                mActiveGeoQuery = true;
            }

            @Override
            public void onGeoQueryError(DatabaseError error) {
                Log.e(LOG_TAG, "There was an error with this query: " + error);
                mListContainer.setViewState(MultiStateView.VIEW_STATE_ERROR);
                mListContainer.setContentDescription("GeoQueryError");
                mActiveGeoQuery = false;
            }
        });
        bindListView();
    }

This is the ItemListAdapter I am using which extends the custom FirebaseListAdapter.
 @BindView(R.id.post_body)
    TextView exampleView;
    Context context;

    public ItemListAdapter(Query ref,Class<Post> postClass, int layout, Activity activity) {
        super(ref,postClass,layout,activity);
        this.context = activity.getApplicationContext();
    }

    /**
     * Bind an instance of the ExampleObject class to our view. This method is called by FirebaseListAdapter
     * when there is a data change, and we are given an instance of a View that corresponds to the layout that we passed
     * to the constructor, as well as a single ExampleObject instance that represents the current data to bind.
     *
     * @param v    A view instance corresponding to the layout we passed to the constructor.
     * @param model An instance representing the current state of a message
     */

    @Override
    protected void populateView(View v, Post model) {
        ButterKnife.bind(this, v);
        // populate the list element
        exampleView.setText(model.body);
    }

    @Override
    protected List<Post> filters(List<Post> models, CharSequence constraint) {
        List<Post> filterList = new ArrayList<>();
        for (int i = 0; i < models.size(); i++) {
            /* implement your own filtering logic
             * and then call  filterList.add(models.get(i));
             */
            filterList.add(models.get(i));
        }
        return filterList;
    }

    @Override
    protected Map<String, Post> filterKeys(List<Post> mModels) {
        return null;
    }
}

This is the emanuelet's custom FirebaseListAdapter that I am using for GeoQueries.
 public FirebaseListAdapter(Query mRef, Class<T> mModelClass, int mLayout, Activity activity) {
        this.mRef = mRef;
        this.mModelClass = mModelClass;
        this.mLayout = mLayout;
        mInflater = activity.getLayoutInflater();
        mModels = new ArrayList<>();
        mModelKeys = new HashMap<>();
        // Look for all child events. We will then map them to our own internal ArrayList, which backs ListView
        mListener = this.mRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {

                T model = dataSnapshot.getValue(FirebaseListAdapter.this.mModelClass);
                mModelKeys.put(dataSnapshot.getKey(), model);

                // Insert into the correct location, based on previousChildName
                if (previousChildName == null) {
                    mModels.add(0, model);
                } else {
                    T previousModel = mModelKeys.get(previousChildName);
                    int previousIndex = mModels.indexOf(previousModel);
                    int nextIndex = previousIndex + 1;
                    if (nextIndex == mModels.size()) {
                        mModels.add(model);
                    } else {
                        mModels.add(nextIndex, model);
                    }
                }

                notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Log.d(LOG_TAG, "onChildChanged");
                // One of the mModels changed. Replace it in our list and name mapping
                String modelName = dataSnapshot.getKey();
                T oldModel = mModelKeys.get(modelName);
                T newModel = dataSnapshot.getValue(FirebaseListAdapter.this.mModelClass);
                int index = mModels.indexOf(oldModel);

                mModels.set(index, newModel);
                mModelKeys.put(modelName, newModel);

                notifyDataSetChanged();
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Log.d(LOG_TAG, "onChildRemoved");
                // A model was removed from the list. Remove it from our list and the name mapping
                String modelName = dataSnapshot.getKey();
                T oldModel = mModelKeys.get(modelName);
                mModels.remove(oldModel);
                mModelKeys.remove(modelName);
                notifyDataSetChanged();
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
                Log.d(LOG_TAG, "onChildMoved");
                // A model changed position in the list. Update our list accordingly
                String modelName = dataSnapshot.getKey();
                T oldModel = mModelKeys.get(modelName);
                T newModel = dataSnapshot.getValue(FirebaseListAdapter.this.mModelClass);
                int index = mModels.indexOf(oldModel);
                mModels.remove(index);
                if (previousChildName == null) {
                    mModels.add(0, newModel);
                } else {
                    T previousModel = mModelKeys.get(previousChildName);
                    int previousIndex = mModels.indexOf(previousModel);
                    int nextIndex = previousIndex + 1;
                    if (nextIndex == mModels.size()) {
                        mModels.add(newModel);
                    } else {
                        mModels.add(nextIndex, newModel);
                    }
                }
                notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e("FirebaseListAdapter", "Listen was cancelled, no more updates will occur");
            }
        });
    }

    public void cleanup() {
        // We're being destroyed, let go of our mListener and forget about all of the mModels
        mRef.removeEventListener(mListener);
        mModels.clear();
        mModelKeys.clear();
    }

    @Override
    public int getCount() {
        return mModels.size();
    }

    @Override
    public Object getItem(int i) {
        return mModels.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public void remove(String key) {
        T oldModel = mModelKeys.get(key);
        mModels.remove(oldModel);
        mModelKeys.remove(key);
        notifyDataSetChanged();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = mInflater.inflate(mLayout, viewGroup, false);
        }

        T model = mModels.get(i);
        if (model != null) {
            // Call out to subclass to marshall this model into the provided view
            populateView(view, model);
        }
        return view;
    }

    /**
     * Each time the data at the given Firebase location changes, this method will be called for each item that needs
     * to be displayed. The arguments correspond to the mLayout and mModelClass given to the constructor of this class.
     *

     * Your implementation should populate the view using the data contained in the model.
     *
     * @param v     The view to populate
     * @param model The object containing the data used to populate the view
     */
    protected abstract void populateView(View v, T model);

    public void addSingle(DataSnapshot snapshot) {
        T model = snapshot.getValue(FirebaseListAdapter.this.mModelClass);
        mModelKeys.put(snapshot.getKey(), model);

        mModels.add(model);

        notifyDataSetChanged();
    }

    public void update(DataSnapshot snapshot, String key) {
        T oldModel = mModelKeys.get(key);
        T newModel = snapshot.getValue(FirebaseListAdapter.this.mModelClass);
        int index = mModels.indexOf(oldModel);

        if (index >= 0) {
            mModels.set(index, newModel);
            mModelKeys.put(key, newModel);

            notifyDataSetChanged();
        }
    }

    public boolean exists(String key) {
        return mModelKeys.containsKey(key);
    }

    @Override
    public Filter getFilter() {
        if (valueFilter == null) {
            valueFilter = new ValueFilter();
        }
        return valueFilter;
    }

    protected abstract List<T> filters(List<T> models, CharSequence constraint);

    private class ValueFilter extends Filter {

        //Invoked in a worker thread to filter the data according to the constraint.
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (mFilteredModels == null) {
                mFilteredModels = new ArrayList<>(mModels); // saves the original data in mOriginalValues
                mFilteredKeys = new HashMap<>(mModelKeys); // saves the original data in mOriginalValues
            }
            if (constraint != null && constraint.length() > 0) {
                List<T> filtered = filters(mFilteredModels, constraint);

                results.count = filtered.size();
                results.values = filtered;
                mModelKeys = filterKeys(mModels);
            } else {
                results.count = mFilteredModels.size();
                results.values = mFilteredModels;
                mModelKeys = mFilteredKeys;
            }
            return results;
        }

        //Invoked in the UI thread to publish the filtering results in the user interface.
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                                      Filter.FilterResults results) {
            Log.d(LOG_TAG, "filter for " + constraint + ", results nr: " + results.count);
            mModels = (List<T>) results.values;

            notifyDataSetChanged();
        }
    }

    protected abstract Map<String, T> filterKeys(List<T> mModels);
}

This is the Model Class Posts
public Post() {
        // Default constructor required for calls to DataSnapshot.getValue(Post.class)
    }

    public Post(String uid, String author, String title, String body, String location) {
        this.uid = uid;
        this.author = author;
        this.title = title;
        this.body = body;
        this.location = location;
    }

    // [START post_to_map]
    @Exclude
    public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("uid", uid);
        result.put("author", author);
        result.put("title", title);
        result.put("body", body);
        result.put("starCount", starCount);
        result.put("stars", stars);

        return result;
    }
    // [END post_to_map]

}

I am new to firebase environment these GeoQueries are quite different with the Parse structure I am confused please help me sort out this issue. Even I have checked with the xml layout are also correct. It is exactly showing me the number of list items which shown in the Logcat too.


text:
Q: gcc - linking multiple c files to a c++ file How do you link 2 c library files, to a c++ file?
Right now I am doing this:
> gcc -c file1.c (this works fine)

> gcc -c file2.c ( this works fine)

> g++ -c myc++file.cpp (this works fine)

> g++ -o program myc++file.o file1.o file2.o

-> I get an error on this last one saying that their is a undefined reference to a function in myc++file.o, but that function is defined in file2.o. Something is wrong, but I just cant figure it out.
Any ideas?

A: Is this function static?
Did you use extern "C" in myc++file.cpp?
if the answers is no and yes, show us some code.
(By the way, try to check using nm if that function is really in file2.o)

A: You need to use extern "C" on the function's declaration.
When C++ sees an external function, it mangles the name, to identify the parameter and return value types. When trying to link it with C code, the names don't match.
extern "C" tells C++ not to mangle the name, so it would successfully link with C code.


text:
Q: C# - multiple thread start one thread I have 3 threads in 3 classes running in parallel. Each of them, increase Pos or Neg of the Fourthclass by "1". After 3 threads are done, if Fourclass.Pos > Fourclass.Neg, it will run Terminal4.
Q: How can i run the Terminal4 only 1 time. Because putting Fourthclass.Terminal4(); in each Terminal1-2-3 will run the Terminal4 3 times.
Here is what i have done:
public class Firstclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal1()
    {
        if (Pos > Neg)
        {
            Fourthclass.Pos += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public class Secondclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal2()
    {
        if (Pos > Neg)
        {
            Fourthclass.Pos += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public class Thirdclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal3()
    {
        if (Pos > Neg)
        {
            Fourthclass.Neg += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public static class Fourthclass
{
    public static int Pos = 0;
    public static int Neg = 0;
    public static void Terminal4()
    {
        if (Pos > Neg)
        {
            Console.WriteLine("Pos = {0} - Neg = {1}", Pos, Neg);
            Console.WriteLine();
        }
        else { Console.WriteLine("fail"); }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Thread obj1 = new Thread(new ThreadStart(Firstclass.Terminal1));
        Thread obj2 = new Thread(new ThreadStart(Secondclass.Terminal2));
        Thread obj3 = new Thread(new ThreadStart(Thirdclass.Terminal3));
        obj1.Start();
        obj2.Start();
        obj3.Start();
    }
}

A:
Original Answer
By the by... these increments are not thread safe, they may suffer the ABA problem and that is ignoring thread visibility problems.
For that problem, please use Interloked. Interlocked.Increment and Interlocked.Decrement will take care of it.
Now, for making a code block run only once, keep an int variable that will be 1 if it did run, and 0 if it did not. Then use Interlocked.CompareExchange:
int didrun;

// ...

if (Interlocked.CompareExchange(ref didrun, 1, 0) == 0)
{
    // code here will only run once, until you put didrun back to 0
}

There are other ways, of course. This one is just very versatile.

Addendum: Ok, what it does...
Interlocked.CompareExchange will look at the value of the passed variable (didrun) compare it to the second parameter (0) and if it matches, it will change the variable to the value of first parameter (1) [Since it may change the variable, you have to pass it by ref]. The return value is what it found in the variable.
Thus, if it returns 0, you know it found 0, which means that it did update the value to 1. Now, the next time this piece of code is called, the value of the variable is 1, so Interlocked.CompareExchange returns 1 and the thread does not enter the block.
Ok, why do not use a bool instead? Because of thread visibility. A thread may change the value of the variable, but this update could happen in CPU cache only, and not be visible to other threads... Interlocked gets around of that problem. Just use Interlocked. And MSDN is your friend.

That will work regardless if you are using ThreadPool, Task or async/await or just plain old Threads as you do. I mention that because I would like to suggest using those...
Sneaky link to Threading in C#.

Extended Answer
In comment, you ask about a different behavior:

The Terminal4 has cooldown until the next run

Well, if there is a cool down (which I understand as a period) you do not only need to store whatever or not the code did run, but also when was the last time it did.
Now, the conditional cannot be just "run only if it has not run yet" but instead "run if it has not run yet or if the period from the last time it ran to now is greater than the cool down".
We have to check multiple things, that is a problem. Now the check will no longer be atomic (from the Latin atomus which means indivisible, from a- "not" + tomos "a cutting, slice, volume, section").
That is relevant because if the check is not atomic, we are back to the ABA problem.

I will use this case to explain the ABA problem. If we encode the following:
1. Check if the operation has not run (if it has not go to 4)
2. Get the last time it ran
3. Compute the difference from the last run to now (exit if less than cool down)
4. Update the last run time to now
5. Run code

Two threads may do the following:
 |
 t  Thread1: Check if the operation has not run (it has)
 i  Thread2: Check if the operation has not run (it has)
 m  Thread2: Get the last time it ran
 e  Thread1: Get the last time it ran
 |  Thread1: Compute the difference from the last run to now (more than cool down)
 v  Thread2: Compute the difference from the last run to now (more than cool down)
    Thread2: Update the last run time to now
    Thread2: Run code
    Thread1: Update the last run time to now
    Thread1: Run code

As you see, they both Run code.
What we need is a way to check and update in a single atomic operation, that way the act of checking will alter the result of the other thread. That is what we get with Interlocked.
How Interlocked manages to do that is beyond the scope of the question. Suffice to say that there are some special CPU instructions for that.

The new pattern I suggest is the following (pseudocode):
bool canRun = false;
DateTime lastRunCopy;
DateTime now = DateTime.Now;
if (try to set lastRun to now if lastRun is not set, copy lastRun to lastRunCopy)
{
    // We set lastRun
    canRun = true;
}
else
{
    if ((now - lastRunCopy) < cooldown)
    {
        if (try to set lastRun to now if lastRun = lastRunCopy, copy lastRun to lastRunCopy)
        {
            // we updated it
            canRun = true;
        }
    }
    else
    {
            // Another thread got in
    }
}
if (canRun)
{
    // code here will only run once per cool down
}

Notice I have expressed the operations in terms of "try to set X to Y if X is Z, copy X to W" which is how Interlocked.CompareExchange works.
There is a reason I left that in pseudo code, and that is that DateTime is not an atomic type.
In order to make the code work we will have to use DateTime.Ticks. For an unset value we will use 0 (00:00:00.0000000 UTC, January 1, 0001), which is something you have to worry about for a cool down greater than a couple of millennia.
In addition, of course, we will use the overload of Interlocked.CompareExchange that takes long because DateTime.Ticks is of that type.
Note: Ah, we will use TimeSpan.Ticks for the cool down.
The code is as follows:
long lastRun = 0;
long cooldown = TimeSpan.FromSeconds(1).Ticks; // Or whatever, I do not know.

// ...

bool canRun = false;
long lastRunCopy = 0;
long now = DateTime.Now.Ticks;
lastRunCopy = Interlocked.CompareExchange(ref lastRun, now, 0);
if (lastRunCopy == 0)
{
    // We set lastRun
    canRun = true;
}
else
{
    if ((now - lastRunCopy) < cooldown)
    {
        if (Interlocked.CompareExchange(ref lastRun, now, lastRunCopy) == lastRunCopy)
        {
            // we updated it
            canRun = true;
        }
        else
        {
            // Another thread got in
        }
    }
}
if (canRun)
{
    // code here will only run once per cooldown
}

Alternatively, if you want to boil it down to a single conditional:
long lastRun = 0;
long cooldown = TimeSpan.FromSeconds(1).Ticks; // Or whatever, I do not know.

// ...

long lastRunCopy;
var now = DateTime.Now.Ticks;
if
(
    (lastRunCopy = Interlocked.CompareExchange(ref lastRun, now, 0)) == 0
    || now - lastRunCopy < cooldown
    && Interlocked.CompareExchange(ref lastRun, now, lastRunCopy) == lastRunCopy
)
{
    // code here will only run once per cooldown
}

As I said, Interlocked.CompareExchange is versatile. Although, as you can see, you still need to think around the requirements.


text:
Q: QLabel with only one bold line Suppose I have a QLabel with a multiline text in; this multiline text comes from a text file: I open the text file, read a line at a time and put the read line into the QLabel followed by a "\n" (CR).
When I reach the end of file, my QLabel shows all read text line per line.
During the read phase I'm able to detect if the read line contains a searched word: in this case I would put this entire line in Bold character, while all the other lines still remain in no bold font.
How can I do this?

A: If your base text does not contain html code, you could set the format of your QLabel to RichText, using
label.setTextFormat(Qt::RichText);.
This way, it will interprete your text as html.
Surround the line you want to highlight with  - that should do the trick.
Alternatively to setTextFormat(), you could surround your entire text with . See mightBeRichText() documentation as well.
Try setting the text format by calling
ui->InfoTextLabel->setTextFormat(Qt::RichText);
The line you want to make bold should be surrounded with , so you can append it to your text like this:
append("" + line + "\n")
Have a look at the documentation

A: In details, my operation:
1) opening the txt file as qtextstream
Info.open(QIODevice::ReadOnly);
QTextStream in(&Info);

2) look for searched text in every read line and append every lines to complete text for QLabel:
while (!line.isNull())
{
    if (line.contains(mytext)
    {
        // do something to bold the entire line
        ui->InfoTextLabel->setText(totline.append(line + "\n"));
    }
}

3) Final result:
line1
**mytext**
line3

Thus, at the end, only one of the three or more line must be Bold.
I need further indication about.


text:
Q: How to store a BigDecimal correctly in a DB using JPA? I want to save an amount in the database using JPA.
@Column(precision=8, scale=2)
private BigDecimal amount;

But after persisting, the decimal values are always 0.
E.g., when I create the amount with
amount = BigDecimal.valueOf(30.20D);

and store it to the database with em.persist(..), the value in the database is 30,00.
When I use a sql update command, I can set it to any value, no problem.
This seems very strange.
I use EclipseLink and Sybase DB.


text:
Q: Determining acceptable single-pulse heating in a wire coil I'm trying to determine the max heating allowable in an insulated copper inductor. This is a pulsed application where peak current in the 5kA range is delivered over <1ms. My task is to figure out how much higher we can go (theoretically) above 5kA without things blowing up / melting.
The fusing current of, say, #8 copper is 14kA over 32ms, which is an order of magnitude more time than this design's pulse length. (We are only considering a single pulse right now, i.e., assume full cooling to ambient between each pulse.)
Based on that, it seems like fusing current should not be the limiting factor. So would the limiting factor be? The melting point of the insulation around the wire? Standard insulation is ok up to ~100degC...but my intuition says that raising the temperature of my inductor say, 50degC in 300 microseconds would still cause something to go very wrong very fast. Or maybe not! I'd appreciate help thinking this through, I'm not an EE! What factors should I be thinking about when heating at this fast a ∆T, if not the insulation melting point?
At the moment, we're thinking about this without regard to cost - an exotic insulation material might be ok if that solves problems.
(as a note: this is only a back of the envelope calculation to explore the design space - if we were actually going to build this, someone who knows what they're doing would be on board!)

A: *

*Put in 5A DC measure 'C/W rise above ambient at 64% thermal time constant then simulate the real power with actual Z(f) V(t) for each part.

*estimate insulated temp rise of copper from rise in DCR Resistance with the change in current,

*Compute Rjc,then fusing margin from T rise. Done.
The internal wire time constant from current will be
 faster yet higher 'C/W than the exterior using thermocouple which is cooler yet  more mass.

*remember to shunt the current with RC snubber when opening the switch or reduce Vdc slowly.
i prefer falstad's simulator for power measurements.

*

*so the critical constant is the tempcoefficient (tempco) for copper with resistance and the thermal resistance coefficient 'C/W due to insulation.

Next after high duty cycle is external temp.
N.B.  I forgot to mention there will be ahellofalot of energy stored, so there are safer methods using low frequency alternating current limited by square wave and current sense regulation.

A: You can get common insulating materials that are good to 200°C continuous (eg. PTFE). It's available in AWG 8, and you can get high-temperature rated conductors too if you want.
There will be some forces on the wire from pulses of magnitude so if the wire isn't fastened down you'll get some vibration and maybe eventual breakage.
5kA into an AWG 8 conductor does not actually sound all that scary. Fault current in an industrial circuit will be in that range, and nothing happens to the conductors, the CB or fuse opens in tens of ms and all is well. I think  you have not accurately calculated the heat capacity of that chunk of copper if  you think it will increase 50°C in 0.3ms.
Let's do a rough back-of-envelope calculation:
At 5000A a 1m length will dissipate 51.5kW since the resistance will be about 2m\$\Omega\$. In 1ms you have 51.5J. Heat capacity of copper is 0.385 J/g°C   1m of AWG 8 has a mass of 116g so the wire will only increase in temperature by about 1°C in 1ms.
For short pulses, with plenty of time between for the wire to return to room temperature, the heat capacity is what you should be looking at. Fusing current takes into account the increase in resistance with temperature and, of course, the heat loss, neither of which matter much for a short pulse.


text:
Q: Add row but appending extra html to each row I'm facing adding new row using Datatable here.
I expect the newly appended html would remain at the bottom of my tr when I append the every custom html. Strange it refreshed so only the first click is working. I've created a demo below :
https://jsfiddle.net/gvowhrmp/
function appendRow(name, position, office, age, date,salary) {
    var t = $('#example').DataTable();

    var node = t.row.add([
      name,
      position,
      office,
      age,
      date,
      salary,
    ]).draw().node();

    var detail_row = '';

    detail_row = '
Custom HTML
';

    $(node).addClass('result-row');

    node = node.outerHTML += detail_row;

    $(node).hide().fadeIn('normal');
  }


text:
Q: TypeError: Cannot read property 'username' of undefined React JS I'm having some trouble solving this error and I'm not sure where to start. This is the error:

I also don't understand the second window where the arrows are pointing to the line with <Button.
These are the code snippets:
const[username, setUsername] = useState('');

<form className="app__register__login">
        <Input
          placeholder="username"
          type="text"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
        />
/>

{
    posts.map(({id, post}) => (
      <Post key={id} username={post.username} caption={post.caption} imageUrl={post.imageUrl}/>
    ))
}

When I write the following code:
db.collection('posts').onSnapshot(snapshot => {
  setPosts(snapshot.docs.map(doc => doc.data()));
})

{
    posts.map(post) => (
      <Post username={post.username} caption={post.caption} imageUrl={post.imageUrl}/>
    ))
}

I don't get any error message. When I change it to this:
db.collection('posts').onSnapshot(snapshot => {
  setPosts(snapshot.docs.map(doc => ({
    id: doc.id,
    post: doc.data(),
  })));
})

{
    posts.map(({id, post}) => (
      <Post key={id} username={post.username} caption={post.caption} imageUrl={post.imageUrl}/>
    ))
}

I get this TypeError.

A: In my opinion, you are changing the data schema. Try this:
{
posts.map(({id, post}) => (
  <Post key={id} username={post.username} caption={post.post.caption} imageUrl={post.post.imageUrl}/>
))}

If you want to keep the consistency of your data schema, try this:
db.collection('posts').onSnapshot(snapshot => {
   setPosts(snapshot.docs.map(doc => ({
        ...doc.data(),
           id: doc.id
  })));
 })

For more info, please refer to https://medium.com/@oprearocks/what-do-the-three-dots-mean-in-javascript-bc5749439c9a


text:
Q: How to make a mac detect all plugged-in devices? (via USB or otherwise) I have an M1 macbook running Big Sur.
A monitor and a keyboard are plugged-in via a USB-C dongle.
When the laptop goes to sleep, it forgets about the connected devices. After waking it up with keystrokes on the laptop (not the plugged-in keyboard, because it doesn't work), I have to unplug and replug the dongle for it to detect the devices. Usually, I have to restart the monitor too.
I'm wondering if there is a way to ask a mac to check for connected devices without physically touching any cables?
Maybe sending a "wake signal" to the connected devices, too?


text:
Q: Inner for loop in nested for loop in handlebars is not working My outer for loop is working and printing name but inner loop in which i'm trying to iterate through systems is not working.
var executions = [
    {
        name:'Password',
        email:'p@pol.com',
        systems: [
           {system: 'PME1'},
           {system: 'PME2'},
           {system: 'PME2'},
        ],

    }
];

{#each executions}}
  Name : {{name}}

      {{#each systems}}

{{ system }}

     {{/each}}

{{/each}}


text:
Q: Error in Cocoa pod file 'XLPagerTabStrip' in Xcode 10 My Xcode version is 10.0 and Swift 4.2.
When I update my pod file, I am seeing the error as shown in the screenshot.

I think 'XLPagerTabStrip' pod file is not getting updated to latest release. To verify this, I created a sample project and installed 'XLPagerTabStrip' pod file only. There also I can see the same error.

A: try following pod command ==>
pod deintegrate
and after this try following command ==>
pod install
it will take a while but definitely solve the problem.


text:
Q: Add ListFragment to ViewPager? I'm trying to incoporate the Contact List provided in Android Documentation to my View Pager, however I don't understand what's the correct way to do it. Since the Contact List is a ListFragment and not a Fragment I cannot just add it to my ViewPager.
Should I add the contact list to the ViewPager as a ListFragment or should I convert it to a fragment somehow? What's the correct way to add the contact list to my ViewPager?
This is what I am trying:
public class MainActivity extends FragmentActivity implements TextToSpeech.OnInitListener {
    private ViewPager mPager;
    private MyPagerAdapter mPagerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new MyPagerAdapter(getFragmentManager());

    // ADD Fragments
    Dialer dialer = new Dialer();
    mPagerAdapter.addFragment(dialer);
    ContactListFragment contacts = new ContactListFragment();
    mPagerAdapter.addFragment(contacts); // Error:  'addFragment(android.app.fragment) cannot be applied to com.example.android.launcher.ContactListFragment'
    mPager.setAdapter(mPagerAdapter);

}

private class MyPagerAdapter extends FragmentPagerAdapter {
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    public void addFragment(Fragment fragment) {
        fragments.add(fragment);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }
}
// ...

Contacts ListFragment:
public class Contacts extends ListFragment implements AdapterView.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {
    //...

A: When using with ViewPager you are most likely to use FragmentPagerAdapter instead of PagerAdapter. You can Extend the FragmentPagerAdapter class and write a method which adds an Fragment to an ArrayList of Fragments. As a ListFragment is just Extended from Fragment Class there should be nothing to worry about.
You can alter you code to this
public class MainActivity extends FragmentActivity implements TextToSpeech.OnInitListener{
private ViewPager mPager;
private MyPagerAdapter mPagerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());

    // ADD Fragments
    Dialer dialer = new Dialer();
    mPagerAdapter.addFragment(dialer);
    Contacts contacts= new Contacts();
    mPagerAdapter.addFragment(contacts);

    //set the adapter to the View pager
    mPager.setAdapter(mPagerAdapter);
}

private class MyPagerAdapter extends FragmentPagerAdapter {
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return fragments.size();
    }

    public void addFragment(Fragment frag) {
        fragments.add(frag);
    }

}

This is a rough code so please do excuse me.

A: ListFragment extends Fragment, that shouldn't be an issue.
Make sure you are importing android.support.v4.app.ListFragment and not android.app.ListFragment, though.