text:
Q: SSL Error while connecting to MQTT Broker I am trying to connect an MQTT Client to an MQTT Broker using TLS. The library I am using is Paho MQTT C library: https://github.com/eclipse/paho.mqtt.c
However, the connection between the broker and the client doesn't succeed and hence I need more clarification and help to solve this issue.
According to the Paho MQTT C documentation for SSL Options:
https://www.eclipse.org/paho/files/mqttdoc/MQTTAsync/html/struct_m_q_t_t_async___s_s_l_options.html
I need to fill this structure with the correct file handles and configuration and pass it to Connection Options structure.
I have a mosquitto broker running on my machine(localhost).
Here is the configuration file:
# =================================================================
# Default listener
# =================================================================

# IP address/hostname to bind the default listener to. If not
# given, the default listener will not be bound to a specific
# address and so will be accessible to all network interfaces.
# bind_address ip-address/host name
#bind_address

# Port to use for the default listener.
port 8883

# -----------------------------------------------------------------
# Certificate based SSL/TLS support
# -----------------------------------------------------------------
# The following options can be used to enable SSL/TLS support for
# this listener. Note that the recommended port for MQTT over TLS
# is 8883, but this must be set manually.
#
# See also the mosquitto-tls man page.

# At least one of cafile or capath must be defined. They both
# define methods of accessing the PEM encoded Certificate
# Authority certificates that have signed your server certificate
# and that you wish to trust.
# cafile defines the path to a file containing the CA certificates.
# capath defines a directory that will be searched for files
# containing the CA certificates. For capath to work correctly, the
# certificate files must have ".crt" as the file ending and you must run
# "openssl rehash <path to capath>" each time you add/remove a certificate.
#capath
cafile /etc/mosquitto/ca_certificates/mqttRSACA.crt

# Path to the PEM encoded server certificate.
certfile /etc/mosquitto/certs/mqttrsabroker.crt

# Path to the PEM encoded keyfile.
keyfile /etc/mosquitto/certs/mqttrsabroker.key

# If you have require_certificate set to true, you can create a certificate
# revocation list file to revoke access to particular client certificates. If
# you have done this, use crlfile to point to the PEM encoded revocation file.
#crlfile

# If you wish to control which encryption ciphers are used, use the ciphers
# option. The list of available ciphers can be obtained using the "openssl
# ciphers" command and should be provided in the same format as the output of
# that command.
# If unset defaults to DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:@STRENGTH
#ciphers DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:@STRENGTH

# To allow the use of ephemeral DH key exchange, which provides forward
# security, the listener must load DH parameters. This can be specified with
# the dhparamfile option. The dhparamfile can be generated with the command
# e.g. "openssl dhparam -out dhparam.pem 2048"
#dhparamfile

# By default a TLS enabled listener will operate in a similar fashion to a
# https enabled web server, in that the server has a certificate signed by a CA
# and the client will verify that it is a trusted certificate. The overall aim
# is encryption of the network traffic. By setting require_certificate to true,
# the client must provide a valid certificate in order for the network
# connection to proceed. This allows access to the broker to be controlled
# outside of the mechanisms provided by MQTT.
#require_certificate false

# This option defines the version of the TLS protocol to use for this listener.
# The default value allows all of v1.3, v1.2 and v1.1. The valid values are
# tlsv1.3 tlsv1.2 and tlsv1.1.
tls_version tlsv1.2

I followed this link:
http://www.steves-internet-guide.com/mosquitto-tls/
I have an mqtt client with the following configuration:
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    conn_opts.onSuccess = onConnect;
    conn_opts.onFailure = onConnectFailure;
    conn_opts.context = (void*)&mqtt_ctx;
    conn_opts.ssl = &ssl_opts;

    // Set SSL options
    ssl_opts.struct_version = 1;
    ssl_opts.keyStore = key_store_file;
    ssl_opts.trustStore = trust_store_file;
    ssl_opts.sslVersion = MQTT_SSL_VERSION_TLS_1_2;

The key_store_file and trust_store_file are read by environment variables pointing to:
key_store_file: mqttrsaclient.key
trust_store_file: mqttrsaclient.crt
Both files are in PEM format.
I have set MQTT_C_CLIENT_TRACE=ON and this is what I observe:
Starting Up!
Broker IP: ssl://127.0.0.1:8883
=========================================================
                   Trace Output
Product name: Eclipse Paho Asynchronous MQTT C Client Library
Version: 1.3.0
Build level: Wed Jul 31 15:23:35 PDT 2019
OpenSSL version: OpenSSL 1.1.1  11 Sep 2018
OpenSSL flags: compiler: gcc -fPIC -pthread -m64 -Wa,--noexecstack -Wall -Wa,--noexecstack -g -O2 -fdebug-prefix-map=/build/openssl-cn9tZy/openssl-1.1.1=. -fstack-protector-strong -Wformat -Werror=format-security -DOPENSSL_USE_NODELETE -DL_ENDIAN -DOPENSSL_PIC -DOPENSSL_CPUID_OBJ -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DKECCAK1600_ASM -DRC4_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DGHASH_ASM -DECP_NISTZ256_ASM -DX2
OpenSSL build timestamp: built on: Thu Jun 20 17:36:28 2019 UTC
OpenSSL platform: platform: debian-amd64
OpenSSL directory: OPENSSLDIR: "/usr/lib/ssl"
/proc/version: Linux version 4.15.0-55-generic (buildd@lcy01-amd64-029) (gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)) #60-Ubuntu SMP Tue Jul 2 18:22:20 UTC 2019

=========================================================
19691231 160000.000 (299804416)  (1)> Socket_outInitialize:131
19691231 160000.000 (299804416)   (2)> SocketBuffer_initialize:94
19691231 160000.000 (299804416)   (2)< SocketBuffer_initialize:98
19691231 160000.000 (299804416)  (1)< Socket_outInitialize:144
19691231 160000.000 (299804416)  (1)> SSLSocket_initialize:443
19691231 160000.000 (299804416)   (2)> SSL_create_mutex:343
19691231 160000.000 (299804416)   (2)< SSL_create_mutex:349 (0)
19691231 160000.000 (299804416)   (2)> SSL_create_mutex:343
19691231 160000.000 (299804416)   (2)< SSL_create_mutex:349 (0)
19691231 160000.000 (299804416)  (1)< SSLSocket_initialize:487 (1)
19691231 160000.000 (299804416)  (1)> MQTTStrncpy:848
19691231 160000.000 (299804416)  (1)< MQTTStrncpy:858
19691231 160000.000 (299804416)  (1)> MQTTStrncpy:848
19691231 160000.000 (299804416)  (1)< MQTTStrncpy:858
19691231 160000.000 (299804416)  (1)> MQTTPersistence_create:52
19691231 160000.000 (299804416)  (1)< MQTTPersistence_create:98 (0)
19691231 160000.000 (299804416)  (1)> MQTTPersistence_initialize:113
19691231 160000.000 (299804416)  (1)< MQTTPersistence_initialize:121 (0)
19691231 160000.000 (299804416)  (1)> MQTTAsync_restoreCommands:936
20190827 183834.980 0 commands restored for client am65x-ti-0
20190827 183834.980 (299804416)  (1)< MQTTAsync_restoreCommands:974 (0)
20190827 183834.980 (299804416)  (1)> MQTTPersistence_restoreMessageQueue:714
20190827 183834.980 0 queued messages restored for client am65x-ti-0
20190827 183834.980 (299804416)  (1)< MQTTPersistence_restoreMessageQueue:753 (0)
20190827 183834.980 (299804416) (0)< MQTTAsync_createWithOptions:593 (0)
20190827 183834.980 (299804416) (0)> MQTTAsync_setCallbacks:2426
20190827 183834.980 (299804416) (0)< MQTTAsync_setCallbacks:2440 (-1)
20190827 183834.980 (299804416) (0)> MQTTAsync_connect:2738
20190827 183834.980 (299804416)  (1)> Thread_start:69
20190827 183834.980 (299804416)  (1)< Thread_start:79
20190827 183834.980 (299804416)  (1)> Thread_start:69
20190827 183834.980 (291411712) (0)> MQTTAsync_sendThread:1784
20190827 183834.980 (299804416)  (1)< Thread_start:79
20190827 183834.980 (283019008) (0)> MQTTAsync_receiveThread:2064
20190827 183834.980 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183834.980 (283019008)   (2)> Socket_getReadySocket:237
20190827 183834.980 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183834.980 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183834.980 (299804416)  (1)> MQTTStrncpy:848
20190827 183834.981 (299804416)  (1)< MQTTStrncpy:858
20190827 183834.981 (291411712)  (1)> Thread_wait_cond:411
20190827 183834.981 (299804416)  (1)> MQTTStrncpy:848
20190827 183834.981 (299804416)  (1)< MQTTStrncpy:858
20190827 183834.981 (299804416)  (1)> MQTTAsync_addCommand:984
20190827 183834.981 (299804416)   (2)> Thread_signal_cond:393
20190827 183834.981 (299804416)   (2)< Thread_signal_cond:398 (0)
20190827 183834.981 (299804416)  (1)< MQTTAsync_addCommand:1018 (0)
20190827 183834.981 (299804416) (0)< MQTTAsync_connect:3039 (0)
Connection Attempt Return Code: 0
20190827 183834.981 (291411712)  (1)< Thread_wait_cond:419 (0)
20190827 183834.981 (291411712)  (1)> MQTTAsync_checkTimeouts:1730
20190827 183834.981 (291411712)  (1)< MQTTAsync_checkTimeouts:1778
20190827 183834.981 (291411712)  (1)> MQTTAsync_processCommand:1324
20190827 183834.981 Connecting to serverURI 127.0.0.1:8883 with MQTT version 4
20190827 183834.981 (291411712)   (2)> MQTTProtocol_connect:114
20190827 183834.981 (291411712)    (3)> MQTTProtocol_addressPort:58
20190827 183834.981 (291411712)    (3)< MQTTProtocol_addressPort:90
20190827 183834.981 (291411712)    (3)> Socket_new:668
20190827 183834.981 New socket 3 for 127.0.0.1:8883, port 8883
20190827 183834.981 (291411712)     (4)> Socket_addSocket:173
20190827 183834.981 (291411712)      (5)> Socket_setnonblocking:85
20190827 183834.981 (291411712)      (5)< Socket_setnonblocking:90 (0)
20190827 183834.981 (291411712)     (4)< Socket_addSocket:196 (0)
20190827 183834.981 Connect pending
20190827 183834.981 (291411712)    (3)< Socket_new:785 (115)
20190827 183834.981 (291411712)   (2)< MQTTProtocol_connect:156 (115)
20190827 183834.981 (291411712)   (2)> MQTTProperties_free:366
20190827 183834.981 (291411712)   (2)< MQTTProperties_free:389
20190827 183834.981 (291411712)  (1)< MQTTAsync_processCommand:1660 (1)
20190827 183834.981 (291411712)  (1)> Thread_wait_cond:411
20190827 183834.981 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183834.981 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183834.981 (283019008)    (3)> MQTTProtocol_keepalive:608
20190827 183834.981 (283019008)    (3)< MQTTProtocol_keepalive:641
20190827 183834.981 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183834.981 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183834.981 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183834.981 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183834.981 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183834.981 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.081 (283019008)    (3)> Socket_continueWrites:928
20190827 183835.081 (283019008)    (3)< Socket_continueWrites:952 (0)
20190827 183835.081 (283019008)    (3)> isReady:213
20190827 183835.081 (283019008)    (3)< isReady:218 (1)
20190827 183835.081 (283019008)   (2)< Socket_getReadySocket:309 (3)
20190827 183835.081 m->c->connect_state = 1
20190827 183835.081 (283019008)   (2)> MQTTAsync_connecting:3513
20190827 183835.081 (283019008)    (3)> MQTTProtocol_addressPort:58
20190827 183835.081 (283019008)    (3)< MQTTProtocol_addressPort:90
20190827 183835.081 (283019008)    (3)> SSLSocket_setSocketForSSL:647
20190827 183835.081 (283019008)     (4)> SSLSocket_createContext:521
20190827 183835.081 (283019008)      (5)> SSLSocket_error:97
20190827 183835.081 SSLSocket error (151584876) in SSL_CTX_use_certificate_chain_file for socket 3 rc 0 errno 2 No such file or directory

20190827 183835.081 (283019008)      (5)< SSLSocket_error:117 (151584876)
20190827 183835.081 (283019008)     (4)< SSLSocket_createContext:637 (0)
20190827 183835.081 (283019008)    (3)< SSLSocket_setSocketForSSL:686 (0)
20190827 183835.081 (283019008)    (3)> nextOrClose:1667
20190827 183835.081 (283019008)     (4)> MQTTAsync_checkConn:467
20190827 183835.081 (283019008)     (4)< MQTTAsync_checkConn:470 (1)
20190827 183835.081 (283019008)     (4)> MQTTAsync_closeOnly:2559
20190827 183835.082 (283019008)      (5)> MQTTProtocol_checkPendingWrites:1138
20190827 183835.082 (283019008)      (5)< MQTTProtocol_checkPendingWrites:1155
20190827 183835.082 (283019008)      (5)> WebSocket_close:397
20190827 183835.082 (283019008)      (5)< WebSocket_close:450
20190827 183835.082 (283019008)      (5)> SSLSocket_close:852
20190827 183835.082 (283019008)       (6)> SSLSocket_destroyContext:839
20190827 183835.082 (283019008)       (6)< SSLSocket_destroyContext:843
20190827 183835.082 (283019008)      (5)< SSLSocket_close:864 (1)
20190827 183835.082 (283019008)      (5)> Socket_close:613
20190827 183835.082 (283019008)       (6)> Socket_close_only:587
20190827 183835.082 (283019008)       (6)< Socket_close_only:601 (0)
20190827 183835.082 (283019008)       (6)> Socket_abortWrite:895
20190827 183835.082 (283019008)       (6)< Socket_abortWrite:913 (0)
20190827 183835.082 (283019008)       (6)> SocketBuffer_cleanup:136
20190827 183835.082 (283019008)       (6)< SocketBuffer_cleanup:148
20190827 183835.082 Removed socket 3
20190827 183835.082 (283019008)      (5)< Socket_close:640
20190827 183835.082 (283019008)     (4)< MQTTAsync_closeOnly:2581
20190827 183835.082 Connect failed, more to try
20190827 183835.082 (283019008)     (4)> MQTTAsync_addCommand:984
20190827 183835.082 (283019008)      (5)> Thread_signal_cond:393
20190827 183835.082 (283019008)      (5)< Thread_signal_cond:398 (0)
20190827 183835.082 (283019008)     (4)< MQTTAsync_addCommand:1018 (0)
20190827 183835.082 (283019008)    (3)< nextOrClose:1720
20190827 183835.082 (283019008)   (2)< MQTTAsync_connecting:3652 (-1)
20190827 183835.082 m->c->connect_state = 0
20190827 183835.082 CONNECT sent, *rc is -1
20190827 183835.082 (291411712)  (1)< Thread_wait_cond:419 (0)
20190827 183835.082 (291411712)  (1)> MQTTAsync_checkTimeouts:1730
20190827 183835.082 (291411712)  (1)< MQTTAsync_checkTimeouts:1778
20190827 183835.082 (291411712)  (1)> MQTTAsync_processCommand:1324
20190827 183835.082 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.082 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.082 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.082 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.082 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.082 Connecting to serverURI 127.0.0.1:8883 with MQTT version 3
20190827 183835.082 (291411712)   (2)> MQTTProtocol_connect:114
20190827 183835.082 (291411712)    (3)> MQTTProtocol_addressPort:58
20190827 183835.082 (291411712)    (3)< MQTTProtocol_addressPort:90
20190827 183835.083 (291411712)    (3)> Socket_new:668
20190827 183835.083 New socket 3 for 127.0.0.1:8883, port 8883
20190827 183835.083 (291411712)     (4)> Socket_addSocket:173
20190827 183835.083 (291411712)      (5)> Socket_setnonblocking:85
20190827 183835.083 (291411712)      (5)< Socket_setnonblocking:90 (0)
20190827 183835.083 (291411712)     (4)< Socket_addSocket:196 (0)
20190827 183835.083 Connect pending
20190827 183835.083 (291411712)    (3)< Socket_new:785 (115)
20190827 183835.083 (291411712)   (2)< MQTTProtocol_connect:156 (115)
20190827 183835.083 (291411712)   (2)> MQTTProperties_free:366
20190827 183835.083 (291411712)   (2)< MQTTProperties_free:389
20190827 183835.083 (291411712)  (1)< MQTTAsync_processCommand:1660 (1)
20190827 183835.083 (291411712)  (1)> Thread_wait_cond:411
20190827 183835.083 Error from MQTTAsync_cycle() - removing socket 3
20190827 183835.083 (283019008)  (1)> nextOrClose:1667
20190827 183835.083 (283019008)   (2)> MQTTAsync_checkConn:467
20190827 183835.083 (283019008)   (2)< MQTTAsync_checkConn:470 (0)
20190827 183835.083 (283019008)   (2)> MQTTAsync_closeSession:2587
20190827 183835.083 (283019008)    (3)> MQTTAsync_closeOnly:2559
20190827 183835.083 (283019008)     (4)> MQTTProtocol_checkPendingWrites:1138
20190827 183835.083 (283019008)     (4)< MQTTProtocol_checkPendingWrites:1155
20190827 183835.083 (283019008)     (4)> WebSocket_close:397
20190827 183835.083 (283019008)     (4)< WebSocket_close:450
20190827 183835.083 (283019008)     (4)> SSLSocket_close:852
20190827 183835.083 (283019008)      (5)> SSLSocket_destroyContext:839
20190827 183835.083 (283019008)      (5)< SSLSocket_destroyContext:843
20190827 183835.083 (283019008)     (4)< SSLSocket_close:864 (1)
20190827 183835.083 (283019008)     (4)> Socket_close:613
20190827 183835.083 (283019008)      (5)> Socket_close_only:587
20190827 183835.083 (283019008)      (5)< Socket_close_only:601 (0)
20190827 183835.083 (283019008)      (5)> Socket_abortWrite:895
20190827 183835.083 (283019008)      (5)< Socket_abortWrite:913 (0)
20190827 183835.083 (283019008)      (5)> SocketBuffer_cleanup:136
20190827 183835.083 (283019008)      (5)< SocketBuffer_cleanup:148
20190827 183835.083 Removed socket 3
20190827 183835.083 (283019008)     (4)< Socket_close:640
20190827 183835.083 (283019008)    (3)< MQTTAsync_closeOnly:2581
20190827 183835.083 (283019008)    (3)> MQTTAsync_cleanSession:2616
20190827 183835.083 (283019008)     (4)> MQTTPersistence_clear:160
20190827 183835.083 (283019008)     (4)< MQTTPersistence_clear:164 (0)
20190827 183835.084 (283019008)     (4)> MQTTProtocol_emptyMessageList:809
20190827 183835.084 (283019008)     (4)< MQTTProtocol_emptyMessageList:818
20190827 183835.084 (283019008)     (4)> MQTTProtocol_emptyMessageList:809
20190827 183835.084 (283019008)     (4)< MQTTProtocol_emptyMessageList:818
20190827 183835.084 (283019008)     (4)> MQTTAsync_emptyMessageQueue:1820
20190827 183835.084 (283019008)     (4)< MQTTAsync_emptyMessageQueue:1834
20190827 183835.084 (283019008)     (4)> MQTTAsync_removeResponsesAndCommands:1844
20190827 183835.084 0 responses removed for client am65x-ti-0
20190827 183835.084 0 commands removed for client am65x-ti-0
20190827 183835.084 (283019008)     (4)< MQTTAsync_removeResponsesAndCommands:1929
20190827 183835.084 (283019008)    (3)< MQTTAsync_cleanSession:2632 (0)
20190827 183835.084 (283019008)   (2)< MQTTAsync_closeSession:2594
20190827 183835.084 Calling connect failure for client am65x-ti-0
Connect failed, rc -1
20190827 183835.084 (283019008)  (1)< nextOrClose:1720
20190827 183835.084 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.084 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.084 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.084 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183835.084 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183835.084 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.184 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.184 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.184 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.184 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.184 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.184 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.184 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.184 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183835.184 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183835.184 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.184 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.184 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.184 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.184 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.184 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.184 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.184 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.184 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183835.184 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183835.184 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.385 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.385 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.385 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.385 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.385 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.385 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.385 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.385 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183835.385 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183835.385 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.385 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.385 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.385 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.385 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.385 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.385 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.385 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.385 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183835.385 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183835.385 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.585 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.585 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.585 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.585 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.585 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.585 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.585 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.585 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183835.585 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183835.585 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.585 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.585 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.585 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.585 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.585 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.585 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.585 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.585 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183835.585 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183835.585 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.786 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.786 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.786 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.786 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.786 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.786 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.786 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.786 (283019008)   (2)> MQTTAsync_sleep:420
20190827 183835.786 (283019008)   (2)< MQTTAsync_sleep:426
20190827 183835.786 (283019008)   (2)> MQTTAsync_retry:3495
20190827 183835.786 (283019008)    (3)> MQTTProtocol_retry:727
20190827 183835.786 (283019008)    (3)< MQTTProtocol_retry:746
20190827 183835.786 (283019008)   (2)< MQTTAsync_retry:3505
20190827 183835.786 (283019008)  (1)< MQTTAsync_cycle:3810 (-1)
20190827 183835.786 (283019008)  (1)> MQTTAsync_cycle:3663
20190827 183835.786 (283019008)   (2)> Socket_getReadySocket:237
20190827 183835.786 (283019008)   (2)< Socket_getReadySocket:309 (0)
20190827 183835.786 (283019008)   (2)> MQTTAsync_sleep:420

Looking specifically at this line:
20190827 183835.081 SSLSocket error (151584876) in SSL_CTX_use_certificate_chain_file for socket 3 rc 0 errno 2 No such file or directory

And on the broker side:
1566956315: New connection from 127.0.0.1 on port 8883.
1566956315: Socket error on client <unknown>, disconnecting.

I am not exactly sure what I am missing.
An insight into setting up the SSL Options correctly would be greatly helpful.
-----------------EDIT---------------
As suggested by Marco in comments I ran strace -e trace=open,openat,stat,fstat -s200 ./mqttTest
`
I tried it with your suggested command and here is the output (I turned off the trace for MQTT).
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=148012, ...}) = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=144976, ...}) = 0
openat(AT_FDCWD, "/usr/local/lib/libpaho-mqtt3as.so.1", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=609680, ...}) = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=2030544, ...}) = 0
openat(AT_FDCWD, "/usr/lib/x86_64-linux-gnu/libssl.so.1.1", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=577312, ...}) = 0
openat(AT_FDCWD, "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=2917216, ...}) = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libdl.so.2", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=14560, ...}) = 0
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0
Starting Up!
Broker IP: ssl://127.0.0.1:8883
Connection Attempt Return Code: 0
Connect failed, rc -1

A: I installed the kernel module for srandom and all the errors went away.
https://github.com/josenk/srandom


text:
Q: Linear vs non-linear Correlation How do i check that two random variables satisfy the requirements for computing correlation  via Pearson or Spearman? If the data is non-linear/ non-Monotonic, are there other tests i could use to compute a correlation coefficient?

A: Distance correlation takes also nonlinear correlations into account.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Recursively defined sequence (a) Consider the recursively defined sequence $y_1 = 1$,
$y_{n+1} = 3−y_n$,
and set $y = \lim y_{n}$. Because $(y_n)$ and $(y_{n+1})$ have the same limit, taking the limit across the recursive equation gives $y = 3−y$. Solving for y, we conclude $\lim y_n = 3/2$.
What is wrong with this argument?
(b) This time set $y_1 = 1$ and $y_{n+1} = 3− 1/y_{n}$ . Can the strategy in (a) be applied to compute the limit of this sequence?
My solution:
(a) The argument incorrectly assumes that the limit of (yn) exists,
which is not true.
(b) I know that I have to show by induction that $y_{n+1}\geq y_n
\geq 1$ but I don't know how to illustrate this.

A: (i) First we show  that $y_n\ge 1$ for all $n$. The result certainly holds at $n=1$. Suppose the result holds at $n=k$. We show the result holds at $n=k+1$. This is easy, for
$$y_{k+1}=3-\frac{1}{y_k}\ge 3-\frac{1}{1}=2\ge 1.$$
(ii) Next we show that our sequence is bounded above by $3$. In principle this is done by induction. The result is true at $1$. If the result is true at $k$, it is true at $k+1$. For $y_{k+1}=3-\frac{1}{y_k}\le 3$ since $y_k$ is positive. Note that we did not even use the induction hypothesis! The only thing we used is the result of (i): because $y_k\ge 1$, in particular $y_k$ is positive.
(iii) Finally we show that the sequence $(y_n)$ is non-decreasing. It is clear that $y_2\ge y_1$. Suppose that for a certain $k$ we have $y_{k+1}\ge y_k$. We show that $y_{k+2}\ge y_{k+1}$.
We have
$$y_{k+2}=3-\frac{1}{y_{k+1}}\ge 3-\frac{1}{y_k}=y_{k+1},$$
completing the induction step.
We have shown that our sequence is non-decreasing and bounded above. It follows that the sequence converges.
Since the limit exists, and is non-zero, we can suppose it is $L$ and conclude that $L=3-\frac{1}{L}$. To find $L$ we need to solve a quadratic equation.


text:
Q: Highcharts xAxis date issue on Safari or Chrome for Ipad I'm having an issue displaying date on highcharts on Safari or Chrome for IPad.
Using the following code to set the format:
// Convert sharepoint date to MMM YYYY format
    for (i = 0; i < customerSortedData.length; i++) {
        if (moment(customerSortedData[i].Date, "ddd MMM DD YYYY HH:mm:ss", 'br', true).isValid())
        {
            customerSortedData[i].MonthYear = moment(customerSortedData[i].Date, "ddd MMM DD YYYY HH:mm:ss", 'br', true).format('MMM YYYY');
        }
    }

, it shows correctly on windows Chrome browser, like 'Apr 2017', 'May 2017'.....'Feb 2018', 'Mar 2018".
The same chart on IPad shows: 'Aug 2017', 'Feb 2018', 'Dec 2017', 'Oct 2017', 'Jan 2018', 'Apr 2017' and then 'Invalid date'. It is expected to show last 12 months in order, but it shows 6 dates only.
Could you please help me to figure out how to fix it?

A: If your customerSortedData array is not sorted by customerSortedData.Date , it could be the source of the problem. Highcharts needs the x values to be sorted.
See this question for further details : Highcharts error 15


text:
Q: Which pins should I connect to program a PIC chip using the SNAP programmer? this seems like this question has an obvious answer but despite looking through the datasheet of the PIC MCU I'm going to be using (the PIC18F45K22), and the SNAP programmer user guide, I can't find the answer.
I want to program the microcontroller using this programmer, but I'm not sure what pins on the chip should connect to which pins on the SNAP. The most relevant information I can find in the user guide is the "ISCP (MCHP)" column in the "Pinouts for Debug Interfaces" table on page 38:

According to this table, it would seem that if I want to program my microcontroller using ICSP (which I believe I do), I would connect pin 1 of the SNAP to MCLR, for example. This I can do. But, where it says to connect pin 6 to AUX I get confused, because nowhere in the datasheet for the microcontroller is such a pin mentioned.
ICSP (MCHP) seems to be the most relevant of all of the columns in that table, so I'm confused as to how the pins don't seem to match up with what is said in the datasheet.

A: The PIC18F K series uses the old Microchip PGC/PGD, it's not a JTAG part.
You need to use the ICSP column. Don't worry about the AUX pin, it's only use in certain low-voltage programming situation as programming trigger.
The problem is that Microchip is buying everyone so it has many different controller families, each one with its own interface.


text:
Q: How to add SSH Private Key to Intellij for Git When I use Git, I usually use the command line. so to push changes to the server. I add the public key to the SSH session using:
$ eval "$(ssh-agent -s)"
ssh-add "D:/Dev/Books Spaces/Version Control with Git and GitHub/SSH/key"
Enter passphrase for D:/Dev/Books Spaces/Version Control with Git and GitHub/SSH/key:
Identity added: D:/Dev/Books Spaces/Version Control with Git and GitHub/SSH/key (me*****d@outlook.com)

Now I would like to use intellij using SSH. How Can I add the private key to intellij? Right now it prints the message:

A: Since you ssh key is not a standard one (in %USERPROFILE%\.ssh\id_rsa), you would need to make a %USERPROFILE%\.ssh\config file in order to reference said key
Host github
  Hostname github.com
  User git
  IdentityFile "D:/Dev/Books Spaces/Version Control with Git and GitHub/SSH/key"

Then try the origin remote URL github:xxxx/tacos01.git


text:
Q: C# Timer For Event Handler I currently have the following event handler
WqlEventQuery query = new WqlEventQuery("__InstanceModificationEvent",
new TimeSpan(0, 0, 1), "TargetInstance ISA \"Win32_NetworkAdapterConfiguration\"");

        ManagementEventWatcher eventWatcher = new ManagementEventWatcher(query);
        eventWatcher.EventArrived += new EventArrivedEventHandler(eventArrived);
        eventWatcher.Start();

 private void eventArrived(object sender, EventArrivedEventArgs e)
 {
    //Event Codes
 }

I need help in developing a (one time) timer. Here is how it should work.

*

*When there is an event,the timer would start to run!

*Because there may be many occurrences of the event,if the timer has started,do not start the timer again ! (one time)

*Timer Duration Shall Be 5 seconds

*During the time(5seconds),the timer event must enumerate if the connection status of the network adapters.

Everyone's advice/help/suggestions/solution regarding this question would be deeply appreciated. I am confused with the mechanism of a (one time) timer !

A: Maybe this pseudo code helps:
myTimer.Interval = 5000;//5s
private void eventArrived(object sender, EventArrivedEventArgs e)
{
   if(!myTimer.Enabled) //if timer not running
      myTimer.Start();
}

private void myTimer_Tick(object sender, System.EventArgs e)
{
   //enumerate statuses every 5s
}


text:
Q: Grub Customizer taking over 5 minutes to start Since updating 12.04 to 12.10, the Grub Customizer now takes over 5 minutes to appear on screen after clicking on icon. I have tried reinstalling it. Any other suggestions as 5 minutes+ seems far too long to wait.

A: My Grub Customizer was working normally on my 64bit 12.10, previously.
Now though after a few un-related updates, it changed to the 5 minutes later behaviour - as above.
So with a bit of lateral thinking I decided to delve into the BIOS.
I had recently updated the BIOS to fit a PCIe x16 graphics card.
This had in turn removed the MAIN section option which DISABLES the Legacy Floppy Drive!
So the delay is due to a fruitless search for the non-existent floppy drive.
Change your BIOS Legacy Floppy Drive Option to DISABLE


text:
Q: Irreducibility Implication between $\mathbb{Q}[x]$, $\mathbb{Z}[x]$, and $\mathbb{Z_p}[x]$ These following questions might be pretty easy, but I am really confused about them.
Let $f(x)$ $\in \mathbb{Z}[x]$, $p=$prime.
1- Does irreducibility of $f(x)$ in  $\mathbb{Z_p}[x]$ imply irreducibility of $f(x)$ in  $\mathbb{Q}[x]$ ?
2- Does irreducibility of $f(x)$ in  $Z[x]$ imply irreducibility of $f(x)$  in $\mathbb{Z_p}[x]$?
3- Does irreducibility of $f(x)$ in $\mathbb{Q}[x]$  imply irreducibility of $f(x)$ in $\mathbb{Z_p}[x]$ ?

A: It is a theorem that $f(x) \in \mathbb Z[x]$ reducible over $\mathbb Q$ implies $f$ is reducible over $\mathbb Z$.
As a consequence, if $f$ is not reducible over $\mathbb Z$ it is also not reducible over $\mathbb Q$.
As for the other cases: do you assume $\operatorname{deg}{(f)} \ge 1$?
And what assumptions do you make on the degree of $\overline{f}$ (that is, $f$ with coefficients reduced $\mod p$)?

A: If $f(x)$  is irreducible in  $\mathbb{Z_p}[x]$, it does not imply that  $f(x)$ is irreducible  in $\mathbb{Z}[x]$ and  $\mathbb{Q}[x]$.
For example, let $f(x)= px^{2}+x$, then: $f(x)= x$ in  $\mathbb{Z_p}[x]$ and so is irreducible in  $\mathbb{Z_p}[x]$, while   $f(x)= px^{2}+x=x(px+1)$ in $\mathbb{Z}[x]$ and  $\mathbb{Q}[x]$, and so is reducible in $\mathbb{Z}[x]$ and  $\mathbb{Q}[x]$. But if $f(x)$ is monic  and irreducible in  $\mathbb{Z_p}[x]$, then it is irreducible in $\mathbb{Z}[x]$ and  $\mathbb{Q}[x]$.


text:
Q: Sortable jQuery UI to replace the element position I want to change the grid order using jQuery UI Sortable.
The way that I am trying to drag the elements over the grid but assume that If I drop 1 to 12, I need top get the grid 12 to 1 automatically instead of default sorting. How can we sort on this way?

$("div.reorder-photos-list").sortable({
    tolerance: 'pointer',
    start: function(event, ui) {

   },
 change: function(event, ui) {
     /*var start_pos = ui.item.data('start_pos');
     var index = ui.placeholder.index();
     console.log('Change ' + start_pos);*/

 },
 update: function(event, ui) {

   //alert(ui.placeholder.index());
   var start_pos = ui.item.index();
   console.log('Update ' + start_pos);

   var id = $(ui.item).attr('cur-id');
   var cp = $(ui.item).attr('cur-pos', start_pos+1);

   console.log("ID " + $(ui.item).attr('cur-id') + "Pos " + $(ui.item).attr('cur-pos'));

 }

   });

A: Finally I found the Answer,
Check on my JSFiddle
https://jsfiddle.net/5fyqz9f6/1/
If anyone needs to make changes in order of a grid system it's useful.
reorder-photos-list = Main Div
col-md-4 = Loop Divs
In My JavaScript
$(document).ready(function() {
    var droppableParent;

    $('.reorder-photos-list .widget-user').draggable({
        revert: 'invalid',
        revertDuration: 200,
        start: function() {
            droppableParent = $(this).parent();
            droppableParent.addClass('being-dragged');
        },
        stop: function() {
            droppableParent.removeClass('being-dragged');
        }
    });

    $('.reorder-photos-list .col-md-4').droppable({
        hoverClass: 'drop-hover',
        drop: function(event, ui) {
            var draggable = $(ui.draggable[0]),
                draggableOffset = draggable.offset(),
                container = $(event.target),
                containerOffset = container.offset();

            //draggable.addClass('animated shake');

            setTimeout(function() {
                var pos = draggable.parent().index();
                var cid = draggable.attr('cid');
                var ctype = draggable.attr('ctype');
                var posFinal = pos + 1;
                var aUrl = "";

                alert("cid : " + cid + " pos : " + posFinal);

            }, 500);

            $('.widget-user', event.target).appendTo(droppableParent).css({
                opacity: 0
            }).animate({
                opacity: 1
            }, 200);

            draggable.appendTo(container).css({
                left: draggableOffset.left - containerOffset.left,
                top: draggableOffset.top - containerOffset.top
            }).animate({
                left: 0,
                top: 0
            }, 200);
        }
    });
});


text:
Q: grunt serve aborted due to warnings in yeoman mean I was following a tutorial on mean.io, and in it, i had to install yo angular
after sometime everything was installed and finally the i had to run `grunt serve'
then this error/warning comes
mukund@mukund-ThinkPad-Edge-E431:~/MeanApp/client$ grunt serve
Running "serve" task

Running "clean:server" (clean) task
>> 0 paths cleaned.

Running "wiredep:app" (wiredep) task

Running "wiredep:test" (wiredep) task

Running "wiredep:sass" (wiredep) task

Running "concurrent:server" (concurrent) task
Warning: Running "compass:server" (compass) task
Warning: Command failed: /bin/sh -c compass --version
/bin/sh: 1: compass: not found
 Use --force to continue.

Aborted due to warnings.

Execution Time (2015-07-16 10:01:13 UTC)
loading tasks                  10ms  ▇▇▇▇ 12%
loading grunt-contrib-compass  33ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇ 40%
compass:server                 38ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 46%
Total 82ms Use --force to continue.

    Aborted due to warnings.

Execution Time (2015-07-16 10:01:12 UTC)
loading tasks                 10ms  ▇ 1%
loading grunt-contrib-clean   10ms  ▇ 1%
clean:server                   9ms  ▇ 1%
wiredep:app                  185ms  ▇▇▇▇▇▇▇▇ 24%
wiredep:test                  10ms  ▇ 1%
wiredep:sass                  12ms  ▇ 2%
loading grunt-concurrent       9ms  ▇ 1%
concurrent:server            515ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 67%
Total 766ms
mukund@mukund-ThinkPad-Edge-E431:~/MeanApp/client$

I followed this tutorial https://www.youtube.com/watch?v=OhPFgqHz68o
Ans when i ran with this command grunt serve --force
I got the required page @ htttp://localhost/9000/#/ page with without any style

A: You need to install compass. It is used by the SASS which is included in the angular yeoman generator.
If you have ruby installed you can do.
gem install compass

And don't use --force ever. Its not really meant for all the cases but grunt throws it for every error/warning except fatal errors.


text:
Q: How to login to instagram using Rails? Need to login to instagram with login and password, and then get a token.
At what address to send a request?

A: I assume you already registered on www.instagram.com/developer, and got an access token for your account via:
https://www.instagram.com/oauth/authorize/?client_id=[CLIENT_ID]&redirect_uri=http://localhost&response_type=token
. If this is the case, you probably want your app users to login through instagram, so you can retrieve their access_token to make requests through the instagram API.
For this I suggest adding the following gems to your gem file
gem 'omniauth-instagram'
gem 'instagram'

Next, you need to create an initializer for OAuth, if you're using devise for authentication, go to config/initializers and edit the devise.rb. Add the following line to the code
config.omniauth :instagram, ENV["INSTAGRAM_CLIENT_ID"], ENV["INSTAGRAM_CLIENT_SECRET"]

Remember to tell devise about omniauthable in your user model
devise :omniauthable, :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable

If you're using devise for authentication, there are a bunch of railscast videos, that do justice to the topic, I suggest you go through those.
For the remaining steps using the API via the instagram gem see: https://stackoverflow.com/a/30362907

A: Consider using the official Instagram Ruby gem.
First step is to register yourself here and get the authentication token.
Once you have installed the gem using:
gem install instagram

and got your authentication token. Initialize Instagram in config/initializers
require "instagram"
Instagram.configure do |config|
  config.client_id = "client_id goes here"
  config.access_token = "access_token goes here"
end

Following this you can access user media as follows:
@instagram = Instagram.user_recent_media("user_id_here", {:count => 1})

This is just one simple example. Refer docs for details.


text:
Q: How to open Acrobat.exe and use pywinauto to scan PDF files I am having trouble finding a way to do this and am new to the pywinauto world.  I can't get acrobat to open with this code.
from pywinauto import *

app = application.Application()

app.start('notepad.exe')

I am trying things like this:
app.start('acrobat.exe')

or app.start('filepath to acrobat').  I do not understant why start acrobat.exe will run the program from the windows cmd shell but is rejected by pywinauto.
I would then like to select file > create > PDF from scanner > color document.  I am aware this is user-like thinking and not programmer-like thinking, but I think it is the quickest and easiest way to start get the PDF's I need.
Please help!  I am grateful for any direction or input to help get things going.  I also can't seem to find any syntax tutorials for pywinauto...Thanks!

A: Clint, I am new to pywinauto, also.  Below is the code to open Acrobat:
import pywinauto
from pywinauto.application import Application
app = Application().Start(cmd_line=u'"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" ')
app.Kill_()
Vasily Ryabov is correct, you cannot get to the Menu items in Adobe.  I thought of using Tabs to try to navigate the menu (but this is a hacky solution).  You need to specify the path of the application you are trying to automate.  Well there is my 2 cents.  Hope it helps !!
Below is a link to PyWinAuto documentation [Release 0.6.0]:
https://media.readthedocs.org/pdf/pywinauto/uia/pywinauto.pdf

A: Try this
If you using python 3.7 install Pywinauto version 0.5.4
Add your AcroRd.exe path
from pywinauto.application import Application
import time
app = Application().start(r"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe")


text:
Q: Is it possible to have a stable small community? I recently started a few new games where I can have about 30-50 people in my town. I got a stable economy with enough food and ressources. But about 30-40 people I always get the problem of having townsfolk who are all too old and rotting away.
If I build new houses in time, my people would expand too big, but if I don't they are all getting old and I have to deal with 10-12 workers, heavily on surviving, until the new generation is finally old enough to work.
Is there a way to interveine this problem?

A: You'll never be completely stable, but there are a few tricks.
You can "demolish" houses but not have any builders.  This will cause the family to be kicked out (or if its empty it will stay empty).  If you have a few empty houses, you can close them.  This will slow your growth, as new couples will be unable to use them to move in and produce children.  When your growth is too low, reopen the houses by stopping the demolish.
In general, you want to keep the population about 70-15-15% adults, students, children.  That way you have enough children to replace workers.  If you have this ratio maintaining a stable population should be more natural and less work.
An important note is your build up to the 30-50 range will make a difference in how stable your pop is.  Increase your pop very slowly, trying to stay at or below 15% children.  A huge growth period will cause all your children to be the same age, causing a mass die off later, causing a mass birth later, causing population instability.
If I'm increasing my housing (you actually need more houses than you'd think for an age-spread town) I pause it right before it finishes and wait until I need it for reproduction before I let them build last few percent.
Another hint is to use the town hall graphs!  You'll see (and understand) the natural ebb and flow of your pop.  If you have a population bust or boom try to find out why so you don't repeat the mistake (too many houses, too closely aged pop).  Two important non-graph numbers are the number of families and the number of houses.
Things I don't know:

*

*What the minimum stable town size is

*How tight of a control you can achieve

Source:
To get the 200 years achievement I kept my pop under 100 for the first 125 years or so.  30-50 seems about as low... but I believe it should be possible.  It might need to be 30-60 range though.


text:
Q: Prolog: Count number of times e appears in a list in odd positions I can't figure out why this is constantly returning false. I can count the number of element "e" in a list in odd positions if I call another function, but I want to do it in a more clean and compact way. Here is the code:
count(_,[],0).
count(E,[E,_|T],C) :-
    count(E,T,D),
    C is D+1.
count(E,[H,_|T],C) :-
    E\=H,
    count(E,T,C).

A: @Sergey's answer is it. But you might want to know how you can find out such problem yourself. Prolog actually can help you to fully understand your Prolog programs. Much more than other languages are able to explain themselves. Here is how:
Use pure, monotonic Prolog
Your program is almost a pure, monotonic program. Except for the (\=)/2 which should be replaced by dif/2 or dif_si/2. See this answer why.
count(_,[],0).
count(E,[E,_|T],C) :-
    count(E,T,D),
    C is D+1.
count(E,[H,_|T],C) :-
    dif(E,H),        % replaces E \= H
    count(E,T,C).

Use the most general query
You have complained that your program is "constantly" returning false. Is this really the case? What test cases have you considered? Is there a way to prove this? In traditional, value oriented programming languages1 the answer would be that you need to resort to some analyzer. But there is no way to prove it within the language. Maybe you are lucky to find test cases that are true. Maybe not.
Not so in Prolog! Here, you can always give a query that will be true, provided there is some test case that is true2. And you don't need to do any thinking (OK, pretend you are thinking). Simply use for each argument a different new variable. So, given your predicate count/3, aah, let me think, please stop this noisy typing, I have to understand it (feign-fake-feign), .... it is:
?- count(E, Xs, M).

For, should there be any other query that succeeds, it would be an instance of this query. Thus, it would be more specific than this one. And thanks to monotonicity the more general query has to be true as well. And, we get now lavishly counterexample after counterexample served on a silver plate, er, top-level shell:
?- count(E, Xs, N).
   Xs = [], N = 0
;  Xs = [E,_A], N = 1
;  Xs = [E,_A,E,_B], N = 2
;  Xs = [E,_A,E,_B,E,_C], N = 3
;  Xs = [E,_A,E,_B,E,_C,E,_D], N = 4
; ... .

So you complained that your predicate is false, but we have so far received 5 answers that are true. And those answer contain infinitely many solutions. To get all solutions, replace all remaining variables by whatever ground term you like. Like count(1,[1,1],1), count(hi,[hi,u],1) etc.
Are these all answers/solutions? Will Prolog enumerate all of them, provided our computing resources are not exhausted? Think how you can enumerate all integers:

0, 1, 2, 3, ... -3, -2, -1.

Well, for us finite beings, it does not work that way. We would have to start

0, 1, -1, 2, -2, 3, -3, ...

so it is fine to have one infinite sequence, but if we are unlucky we might have some values "behind" one.
Enforce fair enumeration
But we are not out of luck! There are situations where we do get nice infinite sequences. Think of:
?- length(Xs, L).
   Xs = [], L = 0
;  Xs = [_A], L = 1
;  Xs = [_A,_B], L = 2
;  Xs = [_A,_B,_C], L = 3
;  Xs = [_A,_B,_C,_D], L = 4
;  Xs = [_A,_B,_C,_D,_E], L = 5
;  ... .

And now, combined with our original query:
?- length(Xs, L), count(E, Xs, N).
   Xs = [], L = 0, N = 0
;  Xs = [E,_A], L = 2, N = 1
;  Xs = [_A,_B],  L = 2,  N = 0, prolog:dif(E,_A)
;  Xs = [E,_A,E,_B], L = 4, N = 2
;  Xs = [E,_A,_B,_C], L = 4, N = 1, prolog:dif(E,_B)
;  ... .

These are all answers, sorted by length of the list. Once we see an increase in value for L, we know that all lengths below it have been enumerated already!
Let's look at the values for L! They are 0, 2, 2, 4, 4, 4, 4, 6, ...  Where are the odd lengths? Evidently they are missing. And thus your program is too specialized. Maybe start with the smallest possible example...
Conclusion-wise reading
Another way to understand the problem is to read the arrows right-to-left, that is exactly in the direction the :- is pointing.
From the fact we know that Xs = [], from both rules we can conclude from this to Xs = [_,_] and then Xs = [_,_,_,_]. Thus, only even lengths are enumerated.
Finally, here is another way to write count/3:
count(_E, [], 0).
count(E, [E|Xs], N0) :-
   count1(E, Xs, N1),
   N0 is N1+1.
count(E, [X|Xs], N) :-
   dif(E, X),
   count1(E, Xs, N).

count1(_E, [], 0).
count1(E, [_|Xs], N) :-
  count(E, Xs, N).

Ah, and I forgot to mention library(clpfd) which could be used as well. See clpfd

Fine print
1 It is easy to spot value oriented programming languages: Their variables are at runtime always values!
2 Certain restrictions apply:
Actually that is only the case in a pure monotonic program, that's why I insisted on that property in the first place. And then, the result might be overshadowed by non-termination or errors.

A: If your Prolog system supports clpfd, you can use the following
definition of count/3. The code shown here is both efficient (avoiding the creation of useless choicepoints) and logically pure.
count(E,Xs,C) :-
   C #>= 0,
   list_item_count(Xs,E,C).

list_item_count([],_,0).
list_item_count([X,_|Xs],E,C) :-
   if_(E=X, C0+1 #= C, C0 = C),
   list_item_count(Xs,E,C0).

Moving on to some queries:
?- count(1,[1,2,3,1,2],C).            % fails: list has wrong length
false.

?- count(1,[1,2,3,1,2,1],C).
C = 1.                                % succeeds deterministically

?- count(E,[1,2,3,1,2,1],C).          % now some more general query!
E = C, C = 1 ;                        % this must be non-deterministic ...
E = 3, C = 1 ;                        % ... lest we lose solutions!
E = 2, C = 1 ;
C = 0, dif(E,2), dif(E,3), dif(E,1).

?- length(Xs,_),count(X,Xs,C).        % even more general; fair enumeration
C = 0, Xs = []                                      ;
C = 1, Xs = [X,_A]                                  ;
C = 0, Xs = [_A,_B],            dif(X,_A)           ;
C = 2, Xs = [X,_A,X,_B]                             ;
C = 1, Xs = [X,__A,_B,_C],      dif(X,_B)           ;
C = 1, Xs = [_A,_B, X,_C],      dif(X,_A)           ;
C = 0, Xs = [_A,_B,_C,_D],      dif(X,_A),dif(X,_B) ;
C = 3, Xs = [X,_A, X,_B, X,_C]                      ;
C = 2, Xs = [X,_A, X,_B,_C,_D], dif(X,_C)           ...

A: Your current formulation is correct when the list has even number of elements:
?- count(x, [x, y, x, x], C).
C = 2

But it will fail if the number of elements is odd.
To correct this you can just add couple of rules for one-element lists:
count(E,[E],1).
count(E,[H], 0):-
    E\=H.

Now it works for lists with odd number of elements:
?- count(x, [x, y, x, x, x], C).
C = 3

?- count(y, [x, y, x, x, x], C).
C = 0

?- count(x, [y, y, y, y, x], C).
C = 1


text:
Q: Cannot access to dom tree after dynamically loaded page Welcome
I have a problem with landing in jquery.
I remove all from the div using a empty() or remove() functions.
The problem is when the page is loaded dynamically into that div i can not access to any loaded elements inside of that div using jquery.
data from the get response is the same as below

link [E]

link [E]

link [E]

$('#menu').empty()

$.get('.php?id=get_menu', function(data)
      {
     $('#menu').append(data);
      });

And after load if i click e (edit) jquery do nothing
This a jquery script i using

$('.form').submit(function(event) {
  var $form = $(this);
  var $inputs = $form.find("input, select, button, textarea");
  var serializedData = $form.serialize();

  request = $.ajax({
 url: "check.php?id=update_menu",
 type: "post",
 data: serializedData
  });

  request.done(function (response, textStatus, jqXHR){
    $('#menu').empty('

');
    $.get('admin_index.php?id=get_menu', function(data) {
  $('#menu').append(data);
    });
  });

  request.always(function () {
    $('.preloader-big').fadeOut();
  });
});

The php script is output ready to use formated html code
THE ANSWER FOR MY POST
This code gets php datas after clicki'n on the letter e

    $('.optedit').on('click', function() {

      $.get('admin_index.php?id=get_menu_edit&mid='+menu_id[1], function(data) {

        $('#link_name').val(res[2]);
        $('#link_title').val(res[3]);
        $('#mid').val(res[1]);
        )};
    )};

I just pack him into a some function i called her update_menu();
and repeat the function after

$.get('.php?id=get_menu', function(data) {
  $('#menu').append(data);
  update_menu();
})

Thats update jquery code to use code that just was added.
Everything works ok.
Thanks for Your help :)

A: empty() removes not only child (and other descendant) elements, but also any text within the set of matched elements.
If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use .detach() instead.

A: seems to be working here, check your result from .php?id=get_menu

     $('#ammend').on('click',function(){
          $('#menu').append('

hello

there

');
          });
$('#empty').on('click',function(){
          $('#menu').empty();
          });

<button id="ammend">Ammend</button>
<button id="empty">Empty</button>

link [E]

link [E]

link [E]

A: There seems to be no problem with your code. You have to check the url used in your call .php?id=get_menu. This seems incomplete.
Also, you might like to check jQuery's load instead of get to simplify things up.
here's how to use it:
$("#menu").load("content_generator.php");

And if you want to fire up an event on success:
$("#menu").load("content_generator.php", function(){
    console.log("Successful")
});

Let me know if this clear things up.
jQuery load documentation

A: I paste above my jquery code.
This do the work to contact with php and output some html code


text:
Q: fsockopen blocked on ports 25&587 I have a very simple snippet of code which connects to a SMTP server using fsockopen (or alternatively stream_socket-client) that looks like this:
<?php
$url = gethostbyname("mx6.go2.pl");
echo $url;
$fp = fsockopen($url, 587, $errno, $errstr, 10);
if (!$fp) {
echo "port is closed or blocked"
} else {
echo "port is open and available";
fclose($fp);
}
?>

Unfortunately, I cannot connect to any of the standard ports like 25,587 or 2525 because my both host providers are blocking any outbound connections using those ports. (I can only connect to internal SMTP server or localhost via 25 or 587)
Is there a way to go round this problem using different code or ports (I mean programmatically and not something like installing my own server).

A: If your provider blocks those outbound ports, there is nothing you can do about that.  Those are the standard SMTP ports, so it is unlikely that the SMTP server is accepting connections on other ports.  Your only hope is to either ask your provider to unblock those ports for your account, or else find an external HTTP-based proxy server to connect to on port 80 (unless your provider blocks that outbound port as well).
Why can't you use the provider's internal SMTP server?  That is what you should be doing.  Let it relay your messages to the other SMTP server for you.  More and more, SMTP servers are being locked down nowadays to prevent spamming and other abuses, so you are likely to run into SMTP servers that do not allow you to connect directly to them even if you can reach their ports, because you are not a provider on that server's whitelist.


text:
Q: ASP.NET 5 project dependency cannot be resolved I have a solution with 2 projects and I want to add a project reference pointing to my Core project

I get an error message

The dependency Yugasat.Core>=4.0.0-* cannot be resolved

Here is the dependencies section in my project.json file

Am I missing something here?

A: You are adding the project reference incorrect.

Project references are resolved using peer folders to the current project or project paths specified using a global.json file at the solution level

Check the documentation link about how to reference project dependencies.
Update
I've updated the link.


text:
Q: Why Jackson wrap the string containing comma when rebuilding the configuration schema for building a record line for a CSV? I'm getting data from a repository and put it into a CSV. For building a record line I use Jackson. My goal is to wrap a field (String type) with double quotes if that field value contains comma. So the output should look like this:
some-uuid-value,some string without comma, SOMETHING, 123456, www.some.url, etc
some-uuid-value,"some string, but with comma", SOMETHING, 123456, www.some.url, etc
some-uuid-value,some string without comma, SOMETHING, 123456, www.some.url, etc
I came up with this code:
private String toCsvString(EntityCsvRecord entity) {

        CsvMapper mapper = new CsvMapper();
        CsvSchema schema = mapper.schemaFor(EntityCsvRecord.class).withoutQuoteChar();

        if (entity.getName() == null) {
            entity.setName("");
        }

        if (entity.getName().contains(",")) {
            String columnName = "name";
            int nameColumnIndex = schema.column(columnName).getIndex();
            schema = mapper
                .configure(CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING, true)
                .schemaFor(EntityCsvRecord.class)
                .rebuild()
                .replaceColumn(nameColumnIndex, new CsvSchema.Column(nameColumnIndex, columnName))
                .build();
        }

        try {
            return mapper.writer(schema).writeValueAsString(entity);
        } catch (Exception e) {
            ...
        }
    }

However, I don't understand why it works like that, I couldn't find any descent clues within the documentation.
Could someone shed a light on this mystery?

A: The whole trick is you enable CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING feature. From documentation:

Feature that determines how much work is done before determining that
  a column value requires quoting: when set as true, full check is made
  to only use quoting when it is strictly necessary; but when false, a
  faster but more conservative check is made, and possibly quoting is
  used for values that might not need it. Trade-offs is basically
  between optimal/minimal quoting (true), and faster handling (false).
  Faster check involves only checking first N characters of value, as
  well as possible looser checks.
Note, however, that regardless setting, all values that need to be quoted will be: it is just that
  when set to false, other values may also be quoted (to avoid having to
  do more expensive checks).
Default value is false for "loose" (approximate, conservative)
  checking.

All other configuration for schema and mapper you can remove and it will work in the same way. You can simplify it to below code:
class CsvEntityGenerator {

    private final CsvMapper mapper;
    private final CsvSchema schema;

    public CsvEntityGenerator(Class clazz) {
        mapper = new CsvMapper();
        mapper.enable(CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING);

        schema = mapper.schemaFor(clazz).withNullValue("");
    }

    public String toCsvString(Object entity) throws IOException {
        return mapper.writer(schema).writeValueAsString(entity);
    }
}

And simple usage:
CsvEntityGenerator gen = new CsvEntityGenerator(EntityCsvRecord.class);
System.out.print(gen.toCsvString(new EntityCsvRecord("Na,me")));
System.out.print(gen.toCsvString(new EntityCsvRecord(null)));
System.out.print(gen.toCsvString(new EntityCsvRecord("Name")));

prints:
8b572b1b-17c1-429d-887b-ec9af1c30d05,"Na,me",SOMETHING,123456,www.some.url
e86eacb1-d45e-4614-91bb-45f0d8840ea9,,SOMETHING,123456,www.some.url
e9627c32-6736-44a5-8eb2-7d153f86af20,Name,SOMETHING,123456,www.some.url

As you can see, we create CsvMapper and CsvSchema only once and reuse it when we want to serialise entities. It is much faster approach.


text:
Q: Not able to get exact latest records with two columns having same value - in SQL Server I am trying to get distinct records for a specific department from the table employee.
I have tried with this code in SQL Server, and I'm getting this error:

Error: employeeId is invalid in the select list because it is not contained in either aggregate function or the GROUP BY clause.

My code:
SELECT
    name, department, MAX(jointime) LatestDate, employeeId
FROM
    employee
WHERE
    department = 'Mechanical'
GROUP BY
    name

Records in DB:
name    department           joinTime            EmployeeId
-----------------------------------------------------------
Erik    Mechanical           2019-07-06 11:59:59    456
Tom     Mechanical           2019-07-06 11:59:59    789
Erik    Computer             2019-07-05 11:59:59    222
Erik    Computer             2019-07-04 11:59:59    111
Erik    Mechanical           2019-07-01 11:59:59    123

I want to achieve the result when a query for 'Mechanical' is executed. The latest record should be fetched from DB for a particular department.
name    department           joinTime            EmployeeId
-----------------------------------------------------------
Erik    Mechanical    2019-07-06 11:59:59     456
Tom     Mechanical    2019-07-06 11:59:59     789

A: Assuming the key is [Name] and not [EmployeeId]
One option is the WITH TIES clause, and thus no need for aggregation
Example
Select Top 1 with ties *
 From  employee
 Where department='Mechanical'
 Order By Row_Number() over (Partition By [Name] order by joinTime Desc)

Returns
name    department  joinTime                 EmployeeId
Erik    Mechanical  2019-07-06 11:59:59.000  456
Tom     Mechanical  2019-07-06 11:59:59.000  789

A: You can use EXISTS:
SELECT e.*
FROM employee e
WHERE e.department='Mechanical'
AND NOT EXISTS (
  SELECT 1 FROM employee
  WHERE department = e.department
  AND name = e.name AND joinTime > e.joinTime
)

See the demo.
Results:
> name | department | joinTime            | EmployeeId
> :--- | :--------- | :------------------ | ---------:
> Erik | Mechanical | 2019-07-06 11:59:59 |        456
> Tom  | Mechanical | 2019-07-06 11:59:59 |        789

A: You can use ROW_NUMBER to mark the latest row for each employee, or CROSS APPLY to run a correlated subquery for each employee.
with q as
(
    SELECT name, department, jointime, employeeId,
           row_number() over (partition by name, order by joinTime desc) rn
    FROM employee where  department='Mechanical'
)
select name, department, jointime, employeeId
from q
where rn = 1

or
with emp as
(
  select distinct name from employee
)
select e.*
from q
cross apply
(
  select top 1 *
  from employee e2
  where e2.name = q.name
  order by joinDate desc
) e

A: You need to use AGGREGATE Functions for fields which are used in SELECT statement:
SELECT name,
  MIN(department)
, MAX(jointime) LatestDate,
, MIN(employeeId)
FROM employee where  department='Mechanical'
GROUP BY name

SQL server finds all records with names Tom or Erik, but SQL Server does not know what one value from multiple rows should be chosen for the fields such as department or employeeId. By using aggregrate functions, you are advising SQL Server to get the MIN, MAX, SUM, COUNT values of that columns.
OR use those columns to the GROUP BY clause to get all unique rows:
SELECT name
    , department
    , jointime
    , employeeId
    FROM employee where  department='Mechanical'
    GROUP BY  name
            , department
            , jointime
            , employeeId

A: Just add department,employeeId to the GROUP BY
SELECT name , department,   MAX(jointime) LatestDate , employeeId
FROM employee where  department='Mechanical'
GROUP BY name, department, employeeId


text:
Q: Using Atomics and Float32Array in JavaScript The Atomics.store/load methods (and others? didn't look) do not support Float32Array.
I read that this is to be consistent with the fact that it also doesn't support Float64Array for compatibility reasons (some computers don't support it).
Aside from the fact that I think this is stupid, does this also mean I must cast every float I want to use into an unsigned int?
Not only will this result in ugly code, it will also make it slower.
E.g.:
let a = new Float32Array(1); // Want the result here

Atomics.store(a, 0, 0.5); // Oops, can't use Float32Array

let b = new Float32Array(1); // Want the result here

let uint = new Uint32Array(1);
let float = new Float32Array(uint.buffer);

float[0] = 0.5;

Atomics.store(b, 0, uint[0]);

A: As you discovered, the Atomics methods doesn't support floating point values as argument:

Atomics.store(typedArray, index, value)
typedArray
      A shared integer typed array. One of Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array,
      or Uint32Array.

You can can read the IEEE754 representation as integer from the underlying buffer as you do in the example code you posted

var buffer = new ArrayBuffer(4);         // common buffer
var float32 = new Float32Array(buffer);  // floating point
var uint32 = new Uint32Array(buffer);    // IEEE754 representation

float32[0] = 0.5;
console.log("0x" + uint32[0].toString(16));

uint32[0] = 0x3f000000;   /// IEEE754 32-bit representation of 0.5
console.log(float32[0]);

or you can use fixed numbers if the accuracy isn't important. The accuracy is of course determined by the magnitude.
Scale up when storing:
Atomics.store(a, 0, Math.round(0.5 * 100)); // 0.5 -> 50 (max two decimals with 100)

read back and scale down:
value = Atomics.load(a, 0) * 0.01;          // 50 -> 0.5

A: The other answer didn't help me much and it took awhile for me to figure out a solution, but here's how I solved the same issue:
var data = new SharedArrayBuffer(LEN * 8);
var data_float = new Float32Array(data);
var data_int = new Uint32Array(data);
data_float[0] = 2.3; //some pre-existing data

var tmp = new ArrayBuffer(8);
var tmp_float = new Float32Array(tmp);
var tmp_int = new Uint32Array(tmp);

tmp_int[0] = Atomics.load(data_int, 0);
tmp_float[0] += 1.1; //some math
Atomics.store(data_int, 0, tmp_int[0]);

console.log(data_float[0]);


text:
Q: Values won't update after api call with axios I'm trying to fetch data with axios using React's useEffect in two steps:
1- Get the access token with a POST request
2- Use the token on another POST request to get the desired data
After the first post request, the response returns as expected, but the state value doesn't update. So it sends undefined as the token for the second request.
const [infos, setInfos] = useState(null)
const [token, setToken] = useState('')

  useEffect(() => {
    const getToken = async () => {
      try {
        const response = await axios.post(
          'adress',
          {
            username: 'root',
            password: 'i_want_my_token',
          }
        )

        setToken(response.data.access)
      } catch (error) {
        console.log(error)
      }
    }

    getToken()

    const getCatalogo = async () => {
      try {
        let data = { id: 6 }
        let configCatalogo = {
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`,
          },
        }
        const catalogoResponse = await axios
          .post(
            'adress',
            data,
            configCatalogo
          )
       setInfos(res.data)
      } catch (error) {
           console.log(error) }
    }

    getCatalogo()
  }, [])

A: Since the function to get/set your token is asynchronous, you need to use two different useEffects: one to fetch the token and one to use that token once it is set.
const [infos, setInfos] = useState(null)
const [token, setToken] = useState('')

  useEffect(() => {
    const getToken = async () => {
      try {
        const response = await axios.post(
          'adress',
          {
            username: 'root',
            password: 'i_want_my_token',
          }
        )

        setToken(response.data.access)
      } catch (error) {
        console.log(error)
      }
    }

    getToken()
  }, []);

  useEffect(() => {
    const getCatalogo = async () => {
      try {
        let data = { id: 6 }
        let configCatalogo = {
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`,
          },
        }
        const catalogoResponse = await axios
          .post(
            'adress',
            data,
            configCatalogo
          )
       setInfos(res.data)
      } catch (error) {
           console.log(error) }
    }

    getCatalogo()
  }, [token]);


text:
Q: Cakephp 2.0: Same application, two tabs, two different values of a session variable? Suppose that we have a session variable, x, with a value, x=2. In our application there's a link which opens, in another tab, another instance of our application with the only difference that our variable has a different value, say 3 (x=3). Is it possible to maintain the value 2 in the first tab continuing our work and the value 3 in the second and if yes how could I achieve it?

A: Help me out here. why can't this be done via arrays ?
x['firstTab'] = 2;
x['secondTab'] = 3;
As far your question is concerned I am pretty much sure that you can not have two same variables in single session instance. If you create another session instance you will loose your previous session.


text:
Q: Sencha Touch ViewPort rendering issue onTap I have a fully functional Sencha Touc 2.1.1 app bundled in Phonegap 2.5. In it, I have several lists that I use to spawn form panels for data entry and other sundry activities.
An example one is as follows (it happens on all my form panels that get opened via a list tap):
I have a list with an item template is rendered in this container:
Ext.define('EvaluateIt.view.Push', {
        extend: 'Ext.Container',
        fullscreen: true,
        //requires: ['Ext.TitleBar'],
        alias: 'widget.pushview',

        config: {
            layout: 'vbox',
            layout: 'fit',
            //id: 'pushview',
            items: [
                {
                    xtype: 'toolbar',
                    docked: 'top',
                    items: [
                        {
                            xtype: 'button',
                            itemId: 'loginButton',
                            text: 'Login',
                            iconCls: 'arrow_right',
                            iconMask: true
                        },
                        {
                            xtype: 'button',
                            itemId: 'logOutButton',
                            text: 'Logout',
                            iconCls: 'arrow_right',
                            iconMask: true
                        }

                    ]

                },
                {
                    flex: 1,
                    xtype: 'pushList'
                }

        ],
        listeners: [{
            delegate: '#logOutButton',
            event: 'tap',
            fn: 'onLogOutButtonTap'
        }]
    },
    onLogOutButtonTap: function () {
        this.fireEvent('onSignOffCommand');
    }

});

The list is:
Ext.define('EvaluateIt.view.PushList', {
    extend: 'Ext.dataview.List', //'Ext.tab.Panel',
    alias : 'widget.pushList',
    config: {
        width: Ext.os.deviceType == 'Phone' ? null : 300,
        height: Ext.os.deviceType == 'Phone' ? null : 500,
        xtype: 'list',
        store: 'SiteEvaluations', //getRange(0, 9),
        itemTpl: [
            '
Address: {address}
 '
        ],
        variableHeights: false
    }

});

And the form that is opened on tapping an address rendered in the itemTpl is:
Ext.define('EvaluateIt.view.PushForm', {
    extend: 'Ext.form.Panel',
    alias : 'widget.pushForm',
    requires: [
        'Ext.form.Panel',
        'Ext.form.FieldSet',
        'Ext.field.Number',
        'Ext.field.DatePicker',
        'Ext.field.Select',
        'Ext.field.Hidden'
    ],
    config: {

    // We give it a left and top property to make it floating by default
        left: 0,
        top: 0,

        // Make it modal so you can click the mask to hide the overlay
        modal: true,
        hideOnMaskTap: true,

        // Set the width and height of the panel
        //width: 400,
        //height: 330,
        width: Ext.os.deviceType == 'Phone' ?  screen.width : 350,
        height: Ext.os.deviceType == 'Phone' ?  screen.height : 500,
        scrollable: true,
        layout: {
            type: 'vbox'
        },
        defaults: {
            margin: '0 0 5 0',
            labelWidth: '40%',
            labelWrap: true
        },
        items: [
            {
                xtype: 'textfield',
                name: 'address',
                readOnly: true
            },
            /*{
                xtype: 'checkboxfield',
                id: 'addImage',
                label: 'Upload Image'
            },*/

            {
                xtype: 'button',
                itemId: 'save',
                text: 'Push to server'
            }

        ]
    }
});

This is called as a ViewPort via the following method in my controller:
onSelectPush: function(view, index, target, record, event) {

    console.log('Selected a SiteEvaluation from the list');
    var pushForm = Ext.Viewport.down('pushForm');

    if(!pushForm){
        pushForm = Ext.widget('pushForm');
    }
    pushForm.setRecord(record);
    pushForm.showBy(target);

    console.log('Selected a Push from the list ' + index + ' ' + record.data.address);
}

This usually works as expected:

*

*Open Push view

*Tap on address in list

*PushForm opens for user to do their thang.

However! Occasionally, when the user taps on the address, instead of the PushForm opening a black arrow shows up underneath the address in the list (see attached image)
.
It is unpredictable when this will happen, but it does. So far, its only happened on my Android device, not on an emulator or in a Web browser (I have not yet heard from any of my iOS users about this yet).
Note: The only way to get the app to function "normally" again is to either do a complete restart or a force close of the application.
Any ideas what is causing it? Grazie!!


text:
Q: iOS how to change push notification title when app is running in foreground? I'm using Urban airship in my app to receive push notifications and all works as expected.
The problem is that when my app is running in foreground and a push received it shows Notification as title along with info in payload.But i want to show title as Notis instead Notification i tried this-
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    if ( application.applicationState == UIApplicationStateActive )
    {
        NSDictionary* aps = [userInfo valueForKey:@"aps"];
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Notis" message:[aps valueForKey:@"alert"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];

    }
    else
    {
         UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
        tabBarController.selectedIndex=2;
     [self loadStatisticsInBackground];
       [[UAPush shared] handleNotification:userInfo applicationState:application.applicationState];
    }

    [[UAPush shared] resetBadge];
}

But it shows two alerts one that i defined and another is system defined.
Any help would be appreciated.
Edit: Ok.. if it is not possible to change title of push notification then Is there any way that we can prevent push alert when app is running in foreground?I don't want to show when my app is running in foreground?

A: You can just detect if your app is running in foreground and if it does, you don't pass the notification to UAPush in -application:didReceiveRemoteNotification:.


text:
Q: Access nested params in Rails - attributes from checkbox I'm trying to access the users array that I get from a check box, to add to an HABTM association between a Reservation and User model.
The params hash is the following:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"vx0dTg8Q2XpyFcXpmmiwbwtFwNiRO25CQImGBasArDZjEbOmjh2lkBSdQGl8Z2Sgr7+kF2qveergEFjZr63AHQ==", "reservation"=>{"name"=>"daads", "phone"=>"", "email"=>"", "number_people"=>"1", "duration"=>"1", "address"=>"", "description"=>"", "users"=>["", "3", "2"]}, "commit"=>"Create Reservation", "date"=>"2016-10-30", "hour"=>"01:30", "id"=>"1"}

My method code is:
def add_reservation
  @business = Business.find(params[:id])
  @reservation = Reservation.new(reservation_params)
  init_date = params[:date].to_s + " " + params[:hour].to_s + ":00"

  @reservation.date = init_date.to_datetime
  @reservation.date_end = (@reservation.date.to_time + @reservation.duration.hours).to_datetime

  user_reservation_params[:users].each do |u|
    @reservation.users << u
  end

  @business.reservations << @reservation

  flash[:success] = "Reservation added!"
  redirect_to business_path(@business)
end

My helpers are defined as:
private
def reservation_params
  params.require(:reservation).permit(:name, :email, :address, :phone, :duration, :date, :date_end, :number_people, :description)
end

private
def user_reservation_params
  params.require(:reservation).permit(:users => [])
end

The way I'm currently accessing the users part of params hash gives me empty variables... How am I supposed to access those values?

A: You can access them simply as params[:reservation][:users], no need to use strong params for this, since they are not used in mass assignment.


text:
Q: Which part of the Android source code determines initial Android time when there is no time source? I am an engineer currently working with the Android P's system time setting/synchronization.
When we build Android and load it for the very first time we can see an initial time has already been set(whether it is correct time or not). I have no idea where to look at for getting the initial time setting without any time source activated(wifi, GPS, etc.). Rough guess is that maybe this time reference can be obtained from the linux time info, but as I said it is a just a guess and I do not know how I can prove/check the code for this also.
Can someone give me an enlightenment?
Thanks.

A: As an electronics engineer, I will try to answer this question in more realistic way.
There is a special part in main board (called RTC) which is designed just to keep track of time. As @Lie Ryan stated, it has its own battery and relatively larger capacitor. In addition there is a special chip, which basically functions as a counter. You can initialize it, load new data, etc. That chip is powered by the special battery (usually very small). The chip can get input from a crystal and CPU. Once the system is assembled and the battery is placed, even the main system has no battery, it starts counting. The value stored in it keeps increasing. It takes crystal frequency as a reference frequency, makes it a clock signal, and uses it as its reference clock. The value of the counter increases at each fixed number of crystal oscillations (clock signal). When you power on the system, assuming the system is set to read the real time from RTC, it reads the value stored in that chip and decodes it in a format the system was set.
If the value you get is wrong, after the time is set from internet or manually, you load new data, and the chip continues counting from that new reference. Because of the imperfections of the real world system (crystal oscillation frequency is given with percentage error), if you don't set the time for long enough period, the time of your system might not be synchronized with real time (as you might have practiced). Or if you wait long enough, the battery gets out of power and the system does not work.

A: Pretty much any modern CPU/motherboard have an RTC (real time clock), this is a component that maintains time independently of any external time source. In absence of an external time synchronisation source, this is the source of truth about time.
The RTC is usually powered by its own battery/supercapacitor, so it will keep running even if you disconnect the main battery.
In the underlying Linux device filesystem, this device is usually exposed as /dev/rtc*. Documentation.


text:
Q: how to access realm result and iterate through the results I am trying to get the realm object results and iterate through the results like an array. Here is my code
 func getStore(){

    let user = realmApp.currentUser()
    let partitionValue = "depth"

    Realm.asyncOpen(configuration: (user?.configuration(partitionValue: partitionValue))!,

        callback: { (maybeRealm, error) in
            guard error == nil else {
                fatalError("Failed to open realm: \(error!)")
            }
            guard let realm = maybeRealm else {
                fatalError("realm is nil!")
            }
            // realm opened
            let tasks = realm.objects(shipwreck.self)

            print("Here is the result", tasks)

        })
}

however this is what i got as print out

Sync: Connection[1]: Connected to endpoint 'xxxxxxxxx' (from '1xxxxxxx0')
Here is the result []

how can I access the realm result and iterate through them?


text:
Q: How do I get Firefox tabs really on top? Firefox 4 has a tabs on top feature, but it doesn't really work if you have customized toolbar.
For example:
I've got all my navigation buttons and address and search fields on the file "Menu Bar" toolbar, When you select "Tabs on top", the tabs move above the bookmark toolbar, which is pointless. It looks like this:
navigation, address, search, menu
tabs toolbar
bookmarks toolbar

I'd prefer something like this:
bookmarks toolbar
tabs toolbar
navigation, address, search, menu

A: Right click on any bar, then in the context menu you need to unmark the Menu Bar.
This step is crucial as it moves the Menu Bar out of the way, because it's a top-most bar by default.

A: Try this firefox Addon called "Tabs on Top".  If that doesn't do the trick, there are tons of other similar addons that may give you the look that you want.

A: The closest you can get to moving the tabs on top without hacking Firefox would be to change the menubar to a single Firefox button and allow the tabs to be on the top row. The problem is, Firefox still uses the Windows frame around it whereas Google Chrome doesn't and I'm guessing that makes the menu bar only allowed at the very top.

A: I could not perform your "requirements" for toolbar positions, but you can do that with FF4: place bookmarks toolbar between Firefox orange ribbon and the tabs. Just press mouse right button on a toolbar and press "customize" option. Then drag and drop the bookmarks toolbar to where do you want and then ok.
But tabs on top for FF4 is only for when the window is maximized. So use "Hide Caption Titlebar Plus" add-on to make the titlebar disappears also for restored windows :) Then adjust something settings to do it better for you.


text:
Q: Problem with assembly code for Linear Search I've adapted the code from this query years ago: https://stackoverflow.com/a/43176620/14157885newreg=6d84b17a2ad6472ca4e585e1b2484d33 about the implementation of the linear search in assembly programming. I'm new to this language and I cannot grasp the problem. Below is a similar code as seen on the link:
;;;;;;;;;;;;;;;;;;;;    MACRO DEFINITIONS   ;;;;;;;;;;;;;;;;;;;;
; A macro with two parameters
; Implements the write system call
    %macro writestring 2
        mov eax, 4  ;sys_write system call number
        mov ebx, 1  ;file descriptor std_out
        mov ecx, %1 ;message to write from parameter 1
        mov edx, %2 ;message length from parameter 2
        int 0x80
    %endmacro
; A macro with two parameters
; Implements the sys_read call
    %macro read_string 2
        mov eax, 3  ;sys_write system call number
        mov ebx, 2  ;file descriptor std_in
        mov ecx, %1 ;variable/array to hold data, pass by reference in param 1
        mov edx, %2 ;number of bytes to read passed by value in param 2
        int 0x80
    %endmacro

;;;;;;;;;;;;;;;;;;;;    DATA SEGMENT    ;;;;;;;;;;;;;;;;;;;;
section .data
msg1 db 'Here are the elements: '
lenmsg1 equ $-msg1
msg2 db 'Enter a number to search for: '
lenmsg2 equ $-msg2
msg3 db 'The target value was found at index '
lenmsg3 equ $-msg3
msg4 db 'The target value was NOT found...',0x0a, 0x0d
lenmsg4 equ $-msg4
asciinums db '7','3','2','1','0','5','6','4','8','9'
lenasciinums equ $-asciinums
crlf db 0x0d, 0x0a
lencrlf equ $ - crlf
target db 0x00
targetlocation db 0x30

section .text
    global _start
_start:
    writestring msg1, lenmsg1
    writestring asciinums, lenasciinums
    writestring crlf, lencrlf
    writestring msg2, lenmsg2
    read_string target, 1
    writestring crlf, lencrlf
    mov eax, asciinums  ;eax holds base address
    mov ecx, 0          ;ecx is index register
getNextElement:
    mov bl, [eax+ecx]   ;copy value from asciinums into an 8-bit register
    cmp bl, [target]    ;compare the 8-bit register to target value
    je  found           ;jump if equal to the found label
    inc ecx             ;increment index register
    cmp ecx, 10         ;compare index register to decimal 10
    jne getNextElement  ;if index register not equal to 10 go to getNextElement

    writestring msg4, lenmsg4
    jmp terminate
found:
    add [targetlocation], ecx
    writestring msg3, lenmsg3
    writestring targetlocation, 1
    writestring crlf, lencrlf
terminate:
    mov eax, 1          ;terminate program
    int 0x80

However, when I run the code and input a number, it seems to not work as the message prompt shows: The target value was NOT found... This might be a silly question for many experienced in assembly but hopefully you could help me. Thank you


text:
Q: Find and replace between first '>' and next '<' in vim I have an html table with some headers:
Header01
...
Different Header 20

I'd like to find and replace everything between the first > and the next < with {{   }}:
{{   }}
...
{{   }}

I know I can use :s/\%Vth/td/g to replace all the th with td, but how can I use Vim's regex to find and replace everything between > and < with {{    }}?
I have attempted the following without success
:s/\%V\>(.*?)\</{{   }}/g

A: You may use
%s/>\(.\{-}\)</>{{ \1 }}</g

In a non-very magic mode, \< and \> are word boundaries that is why they did not work on your side. Besides, *?, a Perl-like lazy quantifier, should be written as \{-} in Vim. The % symbol at the start tells Vim to search and replace on all lines, not just the current one.
Details

*

*> - matches a >

*\(.\{-}\) -  captures into Group 1 any 0 or more chars (but linebreaks, if you need to include line breaks, prepend . with \_) but as few as possible

*< - matches a <
The replacement is >{{ \1 }}<, >{{, Group 1 value and }}>. g makes multiple search and replace operations on lines.

A: if you would take the risk of changing a html/vim by regex, in vim, you can just do:
%s/>[^<]*</>{{ & }}</g

A: I may be misreading the question, but it appears the desired replacement text is paired double braces around 3 whitespaces (not around the original matched text: "replace everything between the first > and the next < with {{   }}". If correct, then the following simple substitute command should work:
%s/>.*</>{{   }}</g

A: If you have just one tag -->  content  per line, you can do:
:%norm cit{{ }}

As you would know, "cit" is a vim text-object that stands for "Change Inner Tag".
If you have many tags on each line you can try:
:%s,>\zs[^<]*\ze</.*,{{ }},g

For more read :h text-objects and :h \zs


text:
Q: Заменить элементы главной диагонали Есть такой код, знаю не самый лучший, но есть нужно переделать что бы он заменял  элементы главной диагонали каждой строки arsum'ом. Сейчас это частично но он заменяет немного не так
В данный момент он заменяет вот так
а надо так
import java.io.*;

class MyCode {

    public static void main(String[] args) {

        int[][] array = new int[5][5];
        int arsum = 0;
        int k = 0;

        array[0][0] = -3;
        array[0][1] = 2;
        array[0][2] = -2;
        array[0][3] = 11;
        array[0][4] = -1;

        array[1][0] = 5;
        array[1][1] = -12;
        array[1][2] = -2;
        array[1][3] = 9;
        array[1][4] = -1;

        array[2][0] = 2;
        array[2][1] = -12;
        array[2][2] = -2;
        array[2][3] = 11;
        array[2][4] = -1;

        array[3][0] = 3;
        array[3][1] = 2;
        array[3][2] = -8;
        array[3][3] = -9;
        array[3][4] = 10;

        array[4][0] = 5;
        array[4][1] = -7;
        array[4][2] = 6;
        array[4][3] = -11;
        array[4][4] = 0;

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j] + "\t");
            }
            System.out.println();
        }

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                if (array[i][j] > 0) {
                    arsum = arsum + array[i][j];
                }
            }

            array[i][k] = arsum;
            k++;
            System.out.print(i + "\t строка - сумма положительных элементов =" + arsum + "\n");
            arsum = 0;
        }

        for (int n = 0; n < array.length; n++) {
            for (int m = 0; m < array[n].length; m++) {
                System.out.print(array[n][m] + "\t");
            }
            System.out.println();
        }
    }
}

A: Сформулирую понятую мною постановку вопроса.
Имеем матрицу n*n в которой, по горизонтали высчитывается сумма всех положительных чисел и присваивается тому элементу, который принадлежит диагонали, по данной горизонтали, с левого верхнего угла матрицы до правого нижнего угла матрицы.
В вопросе обозначено три цикла.

*

*Выводит заданные значения по горизонтали и вертикали

*Высчитывает суммы положительных чисел по каждой горизонтали и присваивает полученные значения элементам по условию задачи

*Выводит обновленную матрицу

Ссылка на вывод
В том ли проблема у автора, что он использует три цикла?
Попробовал реализовать немного иначе, наверняка есть решение изящнее. Решил генерировать значения элементов в диапазоне от min до max.
Random randomez = new Random();
        int[][] array = new int[5][5];
        int min = -10;
        int max = 10;
        //int arsum = 0;
        //int k = 0;
        for (int i = 0; i < array.length; i++) {
            int summaDiagonal = 0;
            for (int j = 0; j < array[i].length; j++) {
                array[i][j] = randomez.nextInt(max - min + 1) + min;
                if(array[i][i] < 0){
                        array[i][i] = 0;
                    }
                if (j != i) {
                    if(array[i][j] > 0){
                        summaDiagonal = array[i][j] + summaDiagonal;
                    }
                }
            }
            array[i][i] = summaDiagonal;
            for (int z = 0; z < array[i].length; z++) {
               System.out.print(array[i][z] + "\t\t");
                if(z == array[i].length - 1){
                   System.out.println();
                }
            }
        }

На выходе
17      8       9       -4      -6 //17 =0 + 8 + 9, на месте 17 было отр число и мы его обнулили, что бы не складывать к отр числу
2       11      8       -5      1 //11 = 0 + 2 + 8 + 1
-6      -1      8       -1      8 //8 = 8 + 0
-9      -3      -1      7       7 //7 = 0 + 7
-10     1       -1      9       10 //10 = 1 + 9 + 0


text:
Q: Deduce one of two template parameters with parameter pack in C++20 I have an N-dimensional array class with two template parameters, a class and a size_t. To construct a 3-dimensional array of size x by y by z, I would like to be able to use:
ArrayND<float> A(x, y, z);

...but can't figure out how to do so--as it stands, I have to redundantly specify the dimension:
ArrayND<float, 3> A(x, y, z);

I thought that this deduction guide:
template <class T, class ...I>
ArrayND(I...) -> ArrayND<T, sizeof...(I)>;

...would be sufficient to allow the omission of the dimension parameter, but it isn't--when I try to compile a program containing "ArrayND<float> A(x, y, z)" with G++ 12.1.0 using -std=c++20, it fails ("error: wrong number of template arguments (1, should be 2)"). Is it possible to do what I'm trying to? If so, what am I doing wrong?
A simplified version of the class in question:
template <class T, size_t N>
class ArrayND {
    // Members: the actual storage, and the conceptual size
    std::vector<T> storage;
    size_t dims[N];

public:
    // Constructor: ArrayND<T, N>(dim1, dim2, ...);
    template <class ...I> requires (sizeof...(I) == N && std::is_integral_v<std::common_type_t<I...>>)
    constexpr ArrayND(const I ...i): storage((i * ...)), dims{i...} {}

private:
    // Indexing helper--convert from (i, j, k...) to the actual index within storage
    template <decltype(N) M=N-1, class I, class ...J>
    constexpr const auto flattened_index(const I i, const J ...j) const {
        auto index = i * std::accumulate(dims+N-M, dims+N, 1, std::multiplies());
        if constexpr (sizeof...(J) > 0) index += flattened_index<M-1>(j...);
        return index;
    }

public:
    // Index a cell
    template <class ...I> requires (sizeof...(I) == N && std::is_integral_v<std::common_type_t<I...>>)
    constexpr auto &operator()(const I ...i) { return storage[flattened_index(i...)]; }

    // Access underlying data
    constexpr auto data() { return storage.data(); }
};

A minimal working example can be found here; delete the 3 on line 47 to see the failure.


text: Q: Convverting pdf file given by latex to word My supervisor told me that for revised version we need to have the word file. However, I dont know how to do that. If I use grindeq then the figures are missed. Also, when I change pdf to word in any software it is not ideal and there are some inconsistency. Any idea?


text:
Q: After uninstallation SSL get CSRF verification failed My Domain SSL certificate expired. But after that when I try to login I am getting "CSRF verification failed. Request aborted." error message. But before that my apps working well over the year. Still my app working on SSL domains but not in Non SSL Domain. I am using sub domains. my login form are given bellow:
   <form class="login-form" action="{% url 'login' %}" method="post">
         {% csrf_token %}

   Username
   <input type="text" name="username" placeholder="Enter your username">

   Password
   <input type="password" name="password" placeholder="Enter Your Password">

   <button type="submit" class="btn btn-login float-right">Submit</button>

   </form>

I am getting same error on login admin page also