问:
Incrase flatbuffers performance in c++
We're developing a high frequency trading platform with C++ and we've tried implementing grpc with protobuf but we saw that a single network call tooks approximately 200-300 microseconds which is too long for us. What we are expecting to have as serializing/deserializing data through network socket is approximately 50-60 microseconds.
Than we 've tried to use protobuf with native c++ sockets (with using non blocking i/o), we saw that this time performance became approximately 150-200 microseconds which was not enough for us. Than we saw flatbuffers and implemented it as described in below.  However during our tests we saw that only serializing (also same in deserializing) tooks approximately 50 microseconds and also transferring the data tooks 30-40 microseconds so totatly it tooks approximately 100-150 microseconds. So I wondered if we are doing something wrong in our implementation of flatbuffers.

In the below example, I've calculated the difference betwen timestamp logs are :

Timestamp 1 -> Timestamp 2 = 16 microseconds

Timestamp 2 -> Timestamp 3 = 24 microseconds

Total serialization = 40 microseconds

Do you know any other way to increase the performance

Example code for serializing data with flatbuffers in C++:

```<code>const char* MAHelper::getRequest(BaseRequest *request,int& size) {
    const char *result;

    flatbuffers::FlatBufferBuilder builder(10240);
    if (request->orderType == OrderTypes::TYPE_LoginRequest){
        std::cout<<"Timestamp 1: "<<getCurrentTimestamp()<<std::endl;
        LoginRequest *loginRequest = (LoginRequest*) request;
        std::cout<<"Converting Login Request 1: "<<getCurrentTimestamp()<<std::endl;
        auto username = builder.CreateString(loginRequest->userName);
        auto password = builder.CreateString(loginRequest->password);
        auto application = getApplication(loginRequest->applicationType);

        std::cout<<"Timestamp 2: "<<getCurrentTimestamp()<<std::endl;
        auto loginReq = piramit::orders::fb::CreateLoginRequest(builder,username,password,application);
        auto loginOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_LoginRequest,loginReq.Union());
        builder.Finish(loginOrderBase);
        std::cout<<"Timestamp 3:"<<getCurrentTimestamp()<<std::endl;
    } else if (request->orderType == OrderTypes::TYPE_EnterOrderRequest) {
        EnterOrderRequest *enterOrderRequest = (EnterOrderRequest*) request;
        auto strategyIdentifier = builder.CreateString(enterOrderRequest->strategyIdentifier);
        auto passThrough  = builder.CreateString(enterOrderRequest->passThrough);
        auto account = builder.CreateString(enterOrderRequest->account);
        auto authToken = builder.CreateString(enterOrderRequest->baseRequest.authToken);

        auto enterOrderReq = piramit::orders::fb::CreateEnterOrder(builder,enterOrderRequest->orderbookId,enterOrderRequest->quantity,enterOrderRequest->price,account,
                getStrategyType(enterOrderRequest->strategyType),strategyIdentifier,getSide(enterOrderRequest->side),getTimeInForce(enterOrderRequest->timeInForce),passThrough,getOrderType(enterOrderRequest->orderType));
        auto enterOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_EnterOrder,enterOrderReq.Union(),authToken);
        builder.Finish(enterOrderBase);
    } else if (request->orderType == OrderTypes::TYPE_ReplaceOrderRequest) {
        ReplaceOrderRequest  *replaceOrderRequest = (ReplaceOrderRequest*) request;
        auto orderToken = builder.CreateString(replaceOrderRequest->orderToken);
        auto authToken = builder.CreateString(replaceOrderRequest->baseRequest.authToken);

        auto replaceOrderReq = piramit::orders::fb::CreateReplaceOrder(builder,orderToken,replaceOrderRequest->quantity,replaceOrderRequest->price);
        auto replaceOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_ReplaceOrder,replaceOrderReq.Union(),authToken);
        builder.Finish(replaceOrderBase);
    } else if (request->orderType == OrderTypes::TYPE_CancelOrderRequest) {
        CancelOrderRequest  *cancelOrderRequest = (CancelOrderRequest*) request;
        auto orderToken = builder.CreateString(cancelOrderRequest->orderToken);
        auto authToken = builder.CreateString(cancelOrderRequest->baseRequest.authToken);

        auto cancelOrderReq = piramit::orders::fb::CreateCancelOrder(builder,orderToken);
        auto cancelOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_CancelOrder,cancelOrderReq.Union(),authToken);
        builder.Finish(cancelOrderBase);
    } else if (request->orderType == OrderTypes::TYPE_BasicOrderRequest) {
        BasicOrderRequest  *basicOrderRequest = (BasicOrderRequest*) request;
        auto authToken = builder.CreateString(basicOrderRequest->baseRequest.authToken);

        auto basicOrderReq = piramit::orders::fb::CreateOrderRequest(builder,getOperationType(basicOrderRequest->operation),basicOrderRequest->orderId,getOrderType(basicOrderRequest->orderTypes));
        auto basicOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_OrderRequest,basicOrderReq.Union(),authToken);
        builder.Finish(basicOrderBase);
    } else if (request->orderType == OrderTypes::TYPE_AccountStrategyRequest) {
        AccountStrategyRequest  *accountStrategyRequest = (AccountStrategyRequest*) request;

        flatbuffers::Offset<flatbuffers::String> account = 0;
        flatbuffers::Offset<flatbuffers::String> strategyIdentifier = 0;
        auto authToken = builder.CreateString(accountStrategyRequest->baseRequest.authToken);

        if (accountStrategyRequest->operation == OPERATION_SET) {
            account = builder.CreateString(accountStrategyRequest->accountStrategy.account);
            strategyIdentifier = builder.CreateString(accountStrategyRequest->accountStrategy.strategyIdentifier);
        }
        flatbuffers::Offset<piramit::orders::fb::AccountStrategy> accountStrategy = piramit::orders::fb::CreateAccountStrategy(builder,accountStrategyRequest->accountStrategy.orderBookId,account,getStrategyType(accountStrategyRequest->accountStrategy.strategyType),strategyIdentifier);

        auto accountStrategyReq = piramit::orders::fb::CreateAccountStrategyRequest(builder,getOperationType(accountStrategyRequest->operation),accountStrategy);
        auto accountStrategyBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_AccountStrategyRequest,accountStrategyReq.Union(),authToken);
        builder.Finish(accountStrategyBase);
    } else if (request->orderType == OrderTypes::TYPE_OrderBookStateRequest) {
        OrderBookStateRequest  *orderBookStateRequest = (OrderBookStateRequest*) request;

        auto stateName = builder.CreateString(orderBookStateRequest->stateName);
        auto orderBookStateReq = piramit::orders::fb::CreateOrderBookStateRequest(builder,stateName,orderBookStateRequest->orderBookId,orderBookStateRequest->timestamp);
        auto orderBookStateBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_OrderBookStateRequest,orderBookStateReq.Union());
        builder.Finish(orderBookStateBase);
    }

    uint8_t *requestBuffer = builder.GetBufferPointer();
    result = (const char*) requestBuffer;
    size = builder.GetSize();

    return result;
}
</code>```

And also this is part of our schema in flatbuffers

```<code>union BaseRequest { LoginRequest,EnterOrder,CancelOrder,ReplaceOrder,OrderRequest,AccountStrategyRequest,OrderBookStateRequest }

table RequestHolder  {
  request:BaseRequest;
  authToken:string;
}

table LoginRequest {
    username:string;
    password:string;
    application:Application = APP_UNKNOWN;
}

table EnterOrder{
    order_book_id:uint;
    quantity:ulong;
    price:int;
    account:string;
    strategy:StrategyType;
    strategy_identifier:string;
    side:Side;
    time_in_force:TimeInForce;
    pass_through:string;
    order_type:OrderType;
}

root_type RequestHolder;
</code>```

答:
For serializing:

You can save yourself some time by reusing the FlatBufferBuilder accross, just call Reset() on it to clear.

You are doing HFT in C++, yet a lot of your data consists of strings? FlatBuffers has all sorts of really efficient ways of representing data, with scalars, structs and enums. Try to find better representations of your data if speed really matters.

For deserializing:

Deserializing in FlatBuffers costs 0ms, since there is no need to do anything. You can access in place. If what you're doing is copying all incoming FlatBuffers data into your own data structures, you are throwing away one of FlatBuffers biggest advantages. Instead, make the code acting on the incoming data work directly with the incoming FlatBuffer.

Title: Incrase flatbuffers performance in c++

Body:
We're developing a high frequency trading platform with C++ and we've tried implementing grpc with protobuf but we saw that a single network call tooks approximately 200-300 microseconds which is too long for us. What we are expecting to have as serializing/deserializing data through network socket is approximately 50-60 microseconds.
Than we 've tried to use protobuf with native c++ sockets (with using non blocking i/o), we saw that this time performance became approximately 150-200 microseconds which was not enough for us. Than we saw flatbuffers and implemented it as described in below.  However during our tests we saw that only serializing (also same in deserializing) tooks approximately 50 microseconds and also transferring the data tooks 30-40 microseconds so totatly it tooks approximately 100-150 microseconds. So I wondered if we are doing something wrong in our implementation of flatbuffers.

In the below example, I've calculated the difference betwen timestamp logs are :

Timestamp 1 -> Timestamp 2 = 16 microseconds

Timestamp 2 -> Timestamp 3 = 24 microseconds

Total serialization = 40 microseconds

Do you know any other way to increase the performance

Example code for serializing data with flatbuffers in C++:

const char* MAHelper::getRequest(BaseRequest *request,int& size) {
    const char *result;

    flatbuffers::FlatBufferBuilder builder(10240);
    if (request->orderType == OrderTypes::TYPE_LoginRequest){
        std::cout<<"Timestamp 1: "<<getCurrentTimestamp()<<std::endl;
        LoginRequest *loginRequest = (LoginRequest*) request;
        std::cout<<"Converting Login Request 1: "<<getCurrentTimestamp()<<std::endl;
        auto username = builder.CreateString(loginRequest->userName);
        auto password = builder.CreateString(loginRequest->password);
        auto application = getApplication(loginRequest->applicationType);

        std::cout<<"Timestamp 2: "<<getCurrentTimestamp()<<std::endl;
        auto loginReq = piramit::orders::fb::CreateLoginRequest(builder,username,password,application);
        auto loginOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_LoginRequest,loginReq.Union());
        builder.Finish(loginOrderBase);
        std::cout<<"Timestamp 3:"<<getCurrentTimestamp()<<std::endl;
    } else if (request->orderType == OrderTypes::TYPE_EnterOrderRequest) {
        EnterOrderRequest *enterOrderRequest = (EnterOrderRequest*) request;
        auto strategyIdentifier = builder.CreateString(enterOrderRequest->strategyIdentifier);
        auto passThrough  = builder.CreateString(enterOrderRequest->passThrough);
        auto account = builder.CreateString(enterOrderRequest->account);
        auto authToken = builder.CreateString(enterOrderRequest->baseRequest.authToken);

        auto enterOrderReq = piramit::orders::fb::CreateEnterOrder(builder,enterOrderRequest->orderbookId,enterOrderRequest->quantity,enterOrderRequest->price,account,
                getStrategyType(enterOrderRequest->strategyType),strategyIdentifier,getSide(enterOrderRequest->side),getTimeInForce(enterOrderRequest->timeInForce),passThrough,getOrderType(enterOrderRequest->orderType));
        auto enterOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_EnterOrder,enterOrderReq.Union(),authToken);
        builder.Finish(enterOrderBase);
    } else if (request->orderType == OrderTypes::TYPE_ReplaceOrderRequest) {
        ReplaceOrderRequest  *replaceOrderRequest = (ReplaceOrderRequest*) request;
        auto orderToken = builder.CreateString(replaceOrderRequest->orderToken);
        auto authToken = builder.CreateString(replaceOrderRequest->baseRequest.authToken);

        auto replaceOrderReq = piramit::orders::fb::CreateReplaceOrder(builder,orderToken,replaceOrderRequest->quantity,replaceOrderRequest->price);
        auto replaceOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_ReplaceOrder,replaceOrderReq.Union(),authToken);
        builder.Finish(replaceOrderBase);
    } else if (request->orderType == OrderTypes::TYPE_CancelOrderRequest) {
        CancelOrderRequest  *cancelOrderRequest = (CancelOrderRequest*) request;
        auto orderToken = builder.CreateString(cancelOrderRequest->orderToken);
        auto authToken = builder.CreateString(cancelOrderRequest->baseRequest.authToken);

        auto cancelOrderReq = piramit::orders::fb::CreateCancelOrder(builder,orderToken);
        auto cancelOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_CancelOrder,cancelOrderReq.Union(),authToken);
        builder.Finish(cancelOrderBase);
    } else if (request->orderType == OrderTypes::TYPE_BasicOrderRequest) {
        BasicOrderRequest  *basicOrderRequest = (BasicOrderRequest*) request;
        auto authToken = builder.CreateString(basicOrderRequest->baseRequest.authToken);

        auto basicOrderReq = piramit::orders::fb::CreateOrderRequest(builder,getOperationType(basicOrderRequest->operation),basicOrderRequest->orderId,getOrderType(basicOrderRequest->orderTypes));
        auto basicOrderBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_OrderRequest,basicOrderReq.Union(),authToken);
        builder.Finish(basicOrderBase);
    } else if (request->orderType == OrderTypes::TYPE_AccountStrategyRequest) {
        AccountStrategyRequest  *accountStrategyRequest = (AccountStrategyRequest*) request;

        flatbuffers::Offset<flatbuffers::String> account = 0;
        flatbuffers::Offset<flatbuffers::String> strategyIdentifier = 0;
        auto authToken = builder.CreateString(accountStrategyRequest->baseRequest.authToken);

        if (accountStrategyRequest->operation == OPERATION_SET) {
            account = builder.CreateString(accountStrategyRequest->accountStrategy.account);
            strategyIdentifier = builder.CreateString(accountStrategyRequest->accountStrategy.strategyIdentifier);
        }
        flatbuffers::Offset<piramit::orders::fb::AccountStrategy> accountStrategy = piramit::orders::fb::CreateAccountStrategy(builder,accountStrategyRequest->accountStrategy.orderBookId,account,getStrategyType(accountStrategyRequest->accountStrategy.strategyType),strategyIdentifier);

        auto accountStrategyReq = piramit::orders::fb::CreateAccountStrategyRequest(builder,getOperationType(accountStrategyRequest->operation),accountStrategy);
        auto accountStrategyBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_AccountStrategyRequest,accountStrategyReq.Union(),authToken);
        builder.Finish(accountStrategyBase);
    } else if (request->orderType == OrderTypes::TYPE_OrderBookStateRequest) {
        OrderBookStateRequest  *orderBookStateRequest = (OrderBookStateRequest*) request;

        auto stateName = builder.CreateString(orderBookStateRequest->stateName);
        auto orderBookStateReq = piramit::orders::fb::CreateOrderBookStateRequest(builder,stateName,orderBookStateRequest->orderBookId,orderBookStateRequest->timestamp);
        auto orderBookStateBase = piramit::orders::fb::CreateRequestHolder(builder,piramit::orders::fb::BaseRequest_OrderBookStateRequest,orderBookStateReq.Union());
        builder.Finish(orderBookStateBase);
    }

    uint8_t *requestBuffer = builder.GetBufferPointer();
    result = (const char*) requestBuffer;
    size = builder.GetSize();

    return result;
}

And also this is part of our schema in flatbuffers

union BaseRequest { LoginRequest,EnterOrder,CancelOrder,ReplaceOrder,OrderRequest,AccountStrategyRequest,OrderBookStateRequest }

table RequestHolder  {
  request:BaseRequest;
  authToken:string;
}

table LoginRequest {
    username:string;
    password:string;
    application:Application = APP_UNKNOWN;
}

table EnterOrder{
    order_book_id:uint;
    quantity:ulong;
    price:int;
    account:string;
    strategy:StrategyType;
    strategy_identifier:string;
    side:Side;
    time_in_force:TimeInForce;
    pass_through:string;
    order_type:OrderType;
}

root_type RequestHolder;


来源: stackexchange

问:
MySQL - SSL - with TLS1.2 cipher AES256-SHA256 / DHE-RSA-AES256-SHA256
I'm using MySQL with SSL with TLS1.2 cipher AES256-SHA256 / DHE-RSA-AES256-SHA256.
I have compiled MySQL with openssl. I am able to connect to MySQL over
    SSL with TLS1.0 ciphers. But when I tried to connect with TLS1.2 ciphers
    connection fails with error.

```<code>MySQL server version :- 5.6.23-log Source distribution
Custom OpenSSL version :- OpenSSL 1.0.1j 15 Oct 2014
Java version :- 1.8.0_40
</code>```

Error thrown with TLS1.2 cipher connect

```<code>> mysql -umysql --ssl-cipher=DHE-RSA-AES256-SHA256 -T -v

ERROR 2026 (HY000): SSL connection error:
error:00000001:lib(0):func(0):reason(1)

User time 0.00, System time 0.00
Maximum resident set size 2664, Integral resident set size 0
Non-physical pagefaults 777, Physical pagefaults 0, Swaps 0
Blocks in 0 out 0, Messages in 0 out 0, Signals 0
Voluntary context switches 2, Involuntary context switches 5
</code>```

Snippet of my.cnf

```<code>[client]
default-character-set=utf8
ssl=ON
ssl-ca=/home/mysql-cert/ca.pem
ssl-cert=/home/mysql-cert/client-cert.pem
ssl-key=/home/mysql-cert/client-key.pem

[mysql]
default-character-set=utf8

[mysqld]
general_log=1

ssl-cipher=DHE-RSA-AES256-SHA256
ssl-cipher=AES256-SHA256
ssl-cipher=AES256-SHA
ssl-ca=/home/mysql-cert/ca.pem
ssl-cert=/home/mysql-cert/server-cert.pem
ssl-key=/home/mysql-cert/server-key.pem
</code>```

MySQL prompt snipeet with TLS1.0 cipher connected

```<code>   mysql> \s
--------------
mysql  Ver 14.14 Distrib 5.6.23, for Linux (x86_64) using EditLine wrapper

Connection id:          6
Current database:
Current user:           root@localhost
SSL:                    Cipher in use is AES256-SHA
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         5.6.23-log Source distribution
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:            /tmp/mysql.sock
Uptime:                 1 hour 32 min 40 sec

Threads: 1  Questions: 11  Slow queries: 0  Opens: 67  Flush tables: 1
Open tables: 60  Queries per second avg: 0.001
--------------

mysql> SHOW STATUS LIKE 'ssl%';
+--------------------------------+--------------------------+
| Variable_name                  | Value                    |
+--------------------------------+--------------------------+
| Ssl_accept_renegotiates        | 0                        |
| Ssl_accepts                    | 6                        |
| Ssl_callback_cache_hits        | 0                        |
| Ssl_cipher                     | AES256-SHA               |
| Ssl_cipher_list                | AES256-SHA               |
| Ssl_client_connects            | 0                        |
| Ssl_connect_renegotiates       | 0                        |
| Ssl_ctx_verify_depth           | 18446744073709551615     |
| Ssl_ctx_verify_mode            | 5                        |
| Ssl_default_timeout            | 7200                     |
| Ssl_finished_accepts           | 3                        |
| Ssl_finished_connects          | 0                        |
| Ssl_server_not_after           | Jan 23 10:29:20 2025 GMT |
| Ssl_server_not_before          | Mar 17 10:29:20 2015 GMT |
| Ssl_session_cache_hits         | 0                        |
| Ssl_session_cache_misses       | 0                        |
| Ssl_session_cache_mode         | SERVER                   |
| Ssl_session_cache_overflows    | 0                        |
| Ssl_session_cache_size         | 128                      |
| Ssl_session_cache_timeouts     | 0                        |
| Ssl_sessions_reused            | 0                        |
| Ssl_used_session_cache_entries | 0                        |
| Ssl_verify_depth               | 18446744073709551615     |
| Ssl_verify_mode                | 5                        |
| Ssl_version                    | TLSv1                    |
+--------------------------------+--------------------------+
25 rows in set (0.00 sec)

mysql> SHOW VARIABLES LIKE '%ssl%';
+---------------+----------------------------------+
| Variable_name | Value                            |
+---------------+----------------------------------+
| have_openssl  | YES                              |
| have_ssl      | YES                              |
| ssl_ca        | /home/mysql-cert/ca.pem          |
| ssl_capath    |                                  |
| ssl_cert      | /home/mysql-cert/server-cert.pem |
| ssl_cipher    | AES256-SHA                       |
| ssl_crl       |                                  |
| ssl_crlpath   |                                  |
| ssl_key       | /home/mysql-cert/server-key.pem  |
+---------------+----------------------------------+
9 rows in set (0.00 sec)
</code>```

MySQL compiled as

```<code>     > cmake . -DCMAKE_PREFIX_PATH=/opt/scr-openssl/ssl/
-DWITH_SSL=/opt/scr-openssl/ssl/
-DWITH_OPENSSL=/opt/scr-openssl/ssl/bin/
-DWITH_OPENSSL_INCLUDES=/opt/scr-openssl/ssl/include/
-DWITH_OPENSSL_LIBS=/opt/scr-openssl/ssl/lib/ -DENABLE_DOWNLOADS=1
 >make
 >make install
</code>```

Please help me out to configure MySQL to work with TLS1.2 cipher.

答:
MySQL v5.6.23 can only support TLS 1.0. To get support for TLS 1.2, you need to upgrade to a later MySQL version and ensure that both client and server have been compiled to use OpenSSL.

You might be able to use MySQL 5.6.46, according to the MySQL documentation.

When compiled using OpenSSL 1.0.1 or higher, MySQL supports the TLSv1, TLSv1.1, and TLSv1.2 protocols as of MySQL 5.6.46, and TLS1v1 prior to 5.6.46.

ContentLicense: CC BY-SA 3.0

Body:
I'm using MySQL with SSL with TLS1.2 cipher AES256-SHA256 / DHE-RSA-AES256-SHA256.
I have compiled MySQL with openssl. I am able to connect to MySQL over
    SSL with TLS1.0 ciphers. But when I tried to connect with TLS1.2 ciphers
    connection fails with error.

MySQL server version :- 5.6.23-log Source distribution
Custom OpenSSL version :- OpenSSL 1.0.1j 15 Oct 2014
Java version :- 1.8.0_40

Error thrown with TLS1.2 cipher connect

> mysql -umysql --ssl-cipher=DHE-RSA-AES256-SHA256 -T -v

ERROR 2026 (HY000): SSL connection error:
error:00000001:lib(0):func(0):reason(1)

User time 0.00, System time 0.00
Maximum resident set size 2664, Integral resident set size 0
Non-physical pagefaults 777, Physical pagefaults 0, Swaps 0
Blocks in 0 out 0, Messages in 0 out 0, Signals 0
Voluntary context switches 2, Involuntary context switches 5

Snippet of my.cnf

[client]
default-character-set=utf8
ssl=ON
ssl-ca=/home/mysql-cert/ca.pem
ssl-cert=/home/mysql-cert/client-cert.pem
ssl-key=/home/mysql-cert/client-key.pem

[mysql]
default-character-set=utf8

[mysqld]
general_log=1

ssl-cipher=DHE-RSA-AES256-SHA256
ssl-cipher=AES256-SHA256
ssl-cipher=AES256-SHA
ssl-ca=/home/mysql-cert/ca.pem
ssl-cert=/home/mysql-cert/server-cert.pem
ssl-key=/home/mysql-cert/server-key.pem

MySQL prompt snipeet with TLS1.0 cipher connected

   mysql> \s
--------------
mysql  Ver 14.14 Distrib 5.6.23, for Linux (x86_64) using EditLine wrapper

Connection id:          6
Current database:
Current user:           root@localhost
SSL:                    Cipher in use is AES256-SHA
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         5.6.23-log Source distribution
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:            /tmp/mysql.sock
Uptime:                 1 hour 32 min 40 sec

Threads: 1  Questions: 11  Slow queries: 0  Opens: 67  Flush tables: 1
Open tables: 60  Queries per second avg: 0.001
--------------

mysql> SHOW STATUS LIKE 'ssl%';
+--------------------------------+--------------------------+
| Variable_name                  | Value                    |
+--------------------------------+--------------------------+
| Ssl_accept_renegotiates        | 0                        |
| Ssl_accepts                    | 6                        |
| Ssl_callback_cache_hits        | 0                        |
| Ssl_cipher                     | AES256-SHA               |
| Ssl_cipher_list                | AES256-SHA               |
| Ssl_client_connects            | 0                        |
| Ssl_connect_renegotiates       | 0                        |
| Ssl_ctx_verify_depth           | 18446744073709551615     |
| Ssl_ctx_verify_mode            | 5                        |
| Ssl_default_timeout            | 7200                     |
| Ssl_finished_accepts           | 3                        |
| Ssl_finished_connects          | 0                        |
| Ssl_server_not_after           | Jan 23 10:29:20 2025 GMT |
| Ssl_server_not_before          | Mar 17 10:29:20 2015 GMT |
| Ssl_session_cache_hits         | 0                        |
| Ssl_session_cache_misses       | 0                        |
| Ssl_session_cache_mode         | SERVER                   |
| Ssl_session_cache_overflows    | 0                        |
| Ssl_session_cache_size         | 128                      |
| Ssl_session_cache_timeouts     | 0                        |
| Ssl_sessions_reused            | 0                        |
| Ssl_used_session_cache_entries | 0                        |
| Ssl_verify_depth               | 18446744073709551615     |
| Ssl_verify_mode                | 5                        |
| Ssl_version                    | TLSv1                    |
+--------------------------------+--------------------------+
25 rows in set (0.00 sec)

mysql> SHOW VARIABLES LIKE '%ssl%';
+---------------+----------------------------------+
| Variable_name | Value                            |
+---------------+----------------------------------+
| have_openssl  | YES                              |
| have_ssl      | YES                              |
| ssl_ca        | /home/mysql-cert/ca.pem          |
| ssl_capath    |                                  |
| ssl_cert      | /home/mysql-cert/server-cert.pem |
| ssl_cipher    | AES256-SHA                       |
| ssl_crl       |                                  |
| ssl_crlpath   |                                  |
| ssl_key       | /home/mysql-cert/server-key.pem  |
+---------------+----------------------------------+
9 rows in set (0.00 sec)

MySQL compiled as

     > cmake . -DCMAKE_PREFIX_PATH=/opt/scr-openssl/ssl/
-DWITH_SSL=/opt/scr-openssl/ssl/
-DWITH_OPENSSL=/opt/scr-openssl/ssl/bin/
-DWITH_OPENSSL_INCLUDES=/opt/scr-openssl/ssl/include/
-DWITH_OPENSSL_LIBS=/opt/scr-openssl/ssl/lib/ -DENABLE_DOWNLOADS=1
 >make
 >make install

Please help me out to configure MySQL to work with TLS1.2 cipher.

ContentLicense: CC BY-SA 4.0


问:
echoing text field value in a while loop
```<code>echo " <table bgcolor='#d3fcfe'   align='center'>  ";

while ($row = mysql_fetch_array($result)) {

echo '</div> <tr onmouseout="this.bgColor=\'#d3fcfe\';"  onmouseover= "this   .bgColor=\'#fffdcd\';" >  ';
 $numq2=$row['username'] ;

{
echo '<td ><div class="iddiv"> <input name="" type="text" value="$numq2" />   <div>    </td> ';
}

echo '  </table>';
}
</code>```

<p>i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script? </p>

答:
You need to use double quotes " for your strings in order for variables to be evaluated.  Escape the double quotes in your HTML to have one long string.

Alternatively, you can use concatenation, allowing you to use single quotes around your HTML, and then concatenating the evaluated variables in between, like so:

```<code>echo '<td ><div class="iddiv"> <input name="" type="text" value="'.$numq2.'" />   <div>    </td> ';
</code>```

Body:
echo "
  ";

while ($row = mysql_fetch_array($result)) {

echo '

  ';
 $numq2=$row['username'] ;

{
echo '
 <input name="" type="text" value="$numq2" />
    	 ';
}

echo '
';
}

i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script?

Body:
You need to use double quotes " for your strings in order for variables to be evaluated.  Escape the double quotes in your HTML to have one long string.

Alternatively, you can use concatenation, allowing you to use single quotes around your HTML, and then concatenating the evaluated variables in between, like so:

echo '<td ><div class="iddiv"> <input name="" type="text" value="'.$numq2.'" />   <div>    </td> ';


问:
Conditional routing of components in react js
My code is as shown below. I want routing in such a way that if there is Appointment route active then login route link must be disappear. And if login component is routing then Appointment route link must be disappear. I got stucked . What condition should I enter here.

```<code>            <Link to="/" style={{height:'20px'}}><strong style={{fontSize:'15px' ,color:'#0'}}>Home</strong></Link>
            <Link to="/contact" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Appointment</strong></Link>
            <Link to="/services" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Services</strong></Link>
            <Link to="/Login" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Login For Doctors</strong></Link>
            <Link to="/Appointment" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Todays Appointment</strong></Link>
        </Navigation>
</code>```

答:
There are a bunch of ways to conditional render components or jsx elements in react.

The Basic understanding you should grasp is: whenever you return false or falsey, it won't render.

There are a few techniques you could use, please refer to this article for more information

if conditional

ternary operator

&& operator (my personal favorite)

Switch statement

Body:
My code is as shown below. I want routing in such a way that if there is Appointment route active then login route link must be disappear. And if login component is routing then Appointment route link must be disappear. I got stucked . What condition should I enter here.

            <Link to="/" style={{height:'20px'}}>Home</Link>
            <Link to="/contact" style={{height:'20px'}}>Appointment</Link>
            <Link to="/services" style={{height:'20px'}}>Services</Link>
            <Link to="/Login" style={{height:'20px'}}>Login For Doctors</Link>
            <Link to="/Appointment" style={{height:'20px'}}>Todays Appointment</Link>
        </Navigation>


问:
Chunking Request Issues Out Of Nowhere on Chrome, Firefox, and cURL
Out of seemingly nowhere my production server is getting a chunking error on a specific request. No config files have been changed on the server and nothing else on the server has changed. I'm not even sure where to start in debugging this error.

This chunking error only happens on 1 GET request with query params.

On Chrome the error is:
net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (Ok).

To make sure this was not a Chrome specific issue, I tried on Firefox but the same thing happens although with a different error SyntaxError: JSON.parse: unterminated string at line . Inspecting the response shows that Firefox is receiving some of the JSON from the request, but not all of it.

On the server I used cURL to GET the URL with the exact same query params and got this error: ncurl: (18) transfer closed with outstanding read data remaining. If I use HTTP 1.0 nothing changes, but if I add the header "Expect: " , at some point the request stops receiving data.

cURL is not the issue here, I need this request to work with the Javascript AJAX request. The file that makes this request has not been altered for 7 months.

The expected return of this request is between 50 - 200 rows from the database. If I do a SELECT query directly on the database, there is no problem.

Where do I start to look? Log files have no information of interest and the server has plenty of memory and cpu.

Our server is Ubuntu 16.04 and Apache 2.4. Our API is DreamFactory; no settings there have been changed either.

答: Looks like you have a firewall or an AntiVirus running. Try making the calls with the antivirus software turned off or paused?</p>


答:
You need to check useLocation() inside this file in order to know which path you are currently on, and then hide that path.

Here is a post which shows how to use useLocation(). Then you can use any method you want to hide that link. An example would be:

```<code>  {location !== '/contact'
      <Link to="/contact" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Appointment</strong></Link>
       : null}
</code>```

after setting location to the current path like this:

```<code>const location = useLocation().pathname
</code>```

Title: Conditional routing of components in react js

Body:
You need to check useLocation() inside this file in order to know which path you are currently on, and then hide that path.

Here is a post which shows how to use useLocation(). Then you can use any method you want to hide that link. An example would be:

  {location !== '/contact'
      <Link to="/contact" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Appointment</strong></Link>
       : null}

after setting location to the current path like this:

const location = useLocation().pathname


问:
Aptana Scriptdoc doesn't show up in Code Assist
I've followed all the instructions to get my code comments to show up in Code Assist but I'm not having any luck. Currently using Aptana 3 plugin inside of Eclipse (could that be the issue?)

```<code>myObj = {
/**
* Gets the current foo
* @param {String} fooId The unique identifier for the foo.
* @return {Object} Returns the current foo.
*/
getFoo: function (fooID) {
    return bar[fooID];
}
</code>```

}

When I have the above code, the function shows up in code assist, but there is no documentation associated with it.

答:
Found out on the Aptana support forums that their Scriptdoc setup doesn't support undeclared vars.

If I change the above code to:

```<code>var myObj = {
    /**
    * Gets the current foo
    * @param {String} fooId The unique identifier for the foo.
    * @return {Object} Returns the current foo.
    */
    getFoo: function (fooID) {
        return bar[fooID];
    }
}
</code>```

then everything works

Body:
I've followed all the instructions to get my code comments to show up in Code Assist but I'm not having any luck. Currently using Aptana 3 plugin inside of Eclipse (could that be the issue?)

myObj = {
/**
* Gets the current foo
* @param {String} fooId The unique identifier for the foo.
* @return {Object} Returns the current foo.
*/
getFoo: function (fooID) {
    return bar[fooID];
}

}

When I have the above code, the function shows up in code assist, but there is no documentation associated with it.

Body:
Found out on the Aptana support forums that their Scriptdoc setup doesn't support undeclared vars.

If I change the above code to:

var myObj = {
    /**
    * Gets the current foo
    * @param {String} fooId The unique identifier for the foo.
    * @return {Object} Returns the current foo.
    */
    getFoo: function (fooID) {
        return bar[fooID];
    }
}

then everything works


问:
How to setup Auth0 with custom domain on Nuxt.js
I already have Auth0 working with my Nuxt.js application but now I'm trying to use it with a custom domain.

I already have everything set up and working on Auth0 side with a custom domain.

I tried to just change the domain on nuxt.config.js:

```<code>  auth: {
    redirect: {
      login: '/auth/login',
      callback: '/auth/signed-in'
    },
    fullPathRedirect: true,
    strategies: {
      local: false,
      auth0: {
        domain: 'customlogin.com',
        client_id: '------'
      }
    }
  }
</code>```

But when I try to login I get this error from Auth0:

You should not be hitting this endpoint. Make sure to use the code
  snippets shown in the tutorial or visit support.auth0.com for help.

Auth0 also mention to add this to the configuration:

```<code>  overrides: {
    __tenant: config.auth0Tenant,
    __token_issuer: config.authorizationServer.issuer
  },
</code>```

But I'm not sure where could I add this on NuxtJS.

答:
Ok, found the issue.
As I was using a custom login page on Auth0 settings, the additional setting above I had to add it there:</p>

```<code>/* additional configuration needed for custom domains */
configurationBaseUrl: config.clientConfigurationBaseUrl,
overrides: {
  __tenant: config.auth0Tenant,
  __token_issuer: 'custom.domain.com'
},
</code>```

Body:
I already have Auth0 working with my Nuxt.js application but now I'm trying to use it with a custom domain.

I already have everything set up and working on Auth0 side with a custom domain.

I tried to just change the domain on nuxt.config.js:

  auth: {
    redirect: {
      login: '/auth/login',
      callback: '/auth/signed-in'
    },
    fullPathRedirect: true,
    strategies: {
      local: false,
      auth0: {
        domain: 'customlogin.com',
        client_id: '------'
      }
    }
  }

But when I try to login I get this error from Auth0:

You should not be hitting this endpoint. Make sure to use the code
  snippets shown in the tutorial or visit support.auth0.com for help.

Auth0 also mention to add this to the configuration:

  overrides: {
    __tenant: config.auth0Tenant,
    __token_issuer: config.authorizationServer.issuer
  },

But I'm not sure where could I add this on NuxtJS.

Body:
Ok, found the issue.
As I was using a custom login page on Auth0 settings, the additional setting above I had to add it there:

/* additional configuration needed for custom domains */
configurationBaseUrl: config.clientConfigurationBaseUrl,
overrides: {
  __tenant: config.auth0Tenant,
  __token_issuer: 'custom.domain.com'
},


问:
GTK - Run function on window close
I'm trying to run a simple function when the 'x' button is clicked in my GTK window but am having trouble getting this to work. I get this error every time I run it:

(process:17950): GLib-GObject-WARNING **: 11:58:51.480: ../../../../gobject/gsignal.c:2523: signal 'delete-event' is invalid for instance '0x55a183d991a0' of type 'GtkApplication'

Here are my functions:

main():

```<code>int main(int argc, char **argv) {
    GtkApplication *app;
    int status;

    // Set up the application and start it
    app = gtk_application_new ("com.sds.hashcrack.server", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (init), NULL);
    g_signal_connect (app, "delete-event", G_CALLBACK (test), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

</code>```

test():

```<code>gboolean test(GtkWidget *widget, GdkEvent  *event, gpointer   user_data) {
    g_print("Closed");
    return true;
}
</code>```

Can anyone shed any light on what I'm doing wrong? Many thanks

答:
The "delete-event" signal is available on GtkWidget instances, not on GtkApplication ones.

You will need to connect the test callback to the delete-event signal on the GtkWindow you're adding to your application.

Title: GTK - Run function on window close

Body:
I'm trying to run a simple function when the 'x' button is clicked in my GTK window but am having trouble getting this to work. I get this error every time I run it:

(process:17950): GLib-GObject-WARNING **: 11:58:51.480: ../../../../gobject/gsignal.c:2523: signal 'delete-event' is invalid for instance '0x55a183d991a0' of type 'GtkApplication'

Here are my functions:

main():

int main(int argc, char **argv) {
    GtkApplication *app;
    int status;

    // Set up the application and start it
    app = gtk_application_new ("com.sds.hashcrack.server", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (init), NULL);
    g_signal_connect (app, "delete-event", G_CALLBACK (test), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

test():

gboolean test(GtkWidget *widget, GdkEvent  *event, gpointer   user_data) {
    g_print("Closed");
    return true;
}

Can anyone shed any light on what I'm doing wrong? Many thanks


问:
EmberJS show router model in application.hbs
I am working with Ember.js, and I am trying to make my pages display the title of the page just below the navbar. To make this work I have tried to use model hook, and show it in the application.hbs file.

So far I have tried variations of this:

routes/contact.js

```<code>import Route from '@ember/routing/route';

export default class ContactRoute extends Route {
  model() {
    return 'Title of page';
  }
}
</code>```

templates/application.hbs

```<code><div>
  <NavBar />

  <div class="pageTitle">
    <h2>
      <p>{{@model}}</p>
    </h2>
  </div>

  <div class="body">
    {{outlet}}
  </div>
</div>
</code>```

I've mostly tried to mess around with @model in application.hbs things like outlet.@model. But all of these attempts have resulted in empty titles or Template Compiler Errors.
Does anyone have a solution for this? Preferably one that does not involve jquery?

答:
Since you have created a new page (route) named contact, the UI part of the page has to be in the corresponding template file, i.e., templates/contact.hbs and not templates/application.hbs as the templates/contact.hbs file can only access the @model of routes/contact.js

ie., the below markup has to in templates/contact.hbs file and will be displayed when accessing the page at http://localhost:4200/contact

{{@model}}

```

Also, note that the markup present in the templates/contact.hbs file will be rendered in the place of application template's {{outlet}} (see here)

For a detailed reference, check this twiddle

Body:
I am working with Ember.js, and I am trying to make my pages display the title of the page just below the navbar. To make this work I have tried to use model hook, and show it in the application.hbs file.

So far I have tried variations of this:

routes/contact.js

import Route from '@ember/routing/route';

export default class ContactRoute extends Route {
  model() {
    return 'Title of page';
  }
}

templates/application.hbs

  <NavBar />

{{@model}}

    {{outlet}}

I've mostly tried to mess around with @model in application.hbs things like outlet.@model. But all of these attempts have resulted in empty titles or Template Compiler Errors.
Does anyone have a solution for this? Preferably one that does not involve jquery?

Body:
Since you have created a new page (route) named contact, the UI part of the page has to be in the corresponding template file, i.e., templates/contact.hbs and not templates/application.hbs as the templates/contact.hbs file can only access the @model of routes/contact.js

ie., the below markup has to in templates/contact.hbs file and will be displayed when accessing the page at http://localhost:4200/contact

<div class="pageTitle">
  <h2>
    <p>{{@model}}</p>
  </h2>
</div>

Also, note that the markup present in the templates/contact.hbs file will be rendered in the place of application template's {{outlet}} (see here)

For a detailed reference, check this twiddle


问:
Creating a button in Java, causes getLayoutParams to return null
I need to create a button in Java. Below is my code:

```<code> Button b = new Button(MyClass.this);
 b.requestLayout();
 LayoutParams lp = b.getLayoutParams();
 lp.height = LayoutParams.WRAP_CONTENT;
 lp.width = LayoutParams.WRAP_CONTENT;
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);
</code>```

I then add this button to the bottom of a ListView:

```<code> getListView().addFooterView(b);
</code>```

However this crashes, because getLayoutParams returns null.

Even if I create new  LayoutParams instead of getLayoutParams, i.e.:

```<code> Button b = new Button(MyClass.this);
 LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);
</code>```

then the application crashes. Without setLayoutParams, it runs fine, but my button is not sized properly.

How can I size my button?

答:
It's returning null because when you programmatically create a widget, it has no layout params!  (Until you add it to a view, then it receives defaults from the LayoutManager)

edit: above is referring to line 3 of your code

Set them like this:

```<code>TextView moneyTV = new TextView(this);
LayoutParams lp1 = new LayoutParams(HeightParamHere, WidthParamHere, WeightParamHere);
moneyTV.setLayoutParams(lp1);
</code>```

Edit2:  here's some readybake replacement code.

```<code>Button b = new Button(MyClass.this);
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setText("bla");
b.setTextSize(16);
b.setOnClickListener(myListener);
</code>```

Assuming you have defined myListener, this should work.

Body:
I need to create a button in Java. Below is my code:

 Button b = new Button(MyClass.this);
 b.requestLayout();
 LayoutParams lp = b.getLayoutParams();
 lp.height = LayoutParams.WRAP_CONTENT;
 lp.width = LayoutParams.WRAP_CONTENT;
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);

I then add this button to the bottom of a ListView:

 getListView().addFooterView(b);

However this crashes, because getLayoutParams returns null.

Even if I create new  LayoutParams instead of getLayoutParams, i.e.:

 Button b = new Button(MyClass.this);
 LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);

then the application crashes. Without setLayoutParams, it runs fine, but my button is not sized properly.

How can I size my button?

Body:
It's returning null because when you programmatically create a widget, it has no layout params!  (Until you add it to a view, then it receives defaults from the LayoutManager)

edit: above is referring to line 3 of your code

Set them like this:

TextView moneyTV = new TextView(this);
LayoutParams lp1 = new LayoutParams(HeightParamHere, WidthParamHere, WeightParamHere);
moneyTV.setLayoutParams(lp1);

Edit2:  here's some readybake replacement code.

Button b = new Button(MyClass.this);
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setText("bla");
b.setTextSize(16);
b.setOnClickListener(myListener);

Assuming you have defined myListener, this should work.


问:
How do I calculate the rest/modulo of two numbers without the "%" operator?
For example with the following input:

```<code>int num = -100
int divisor = 10
=>  -100 mod 10 = 0   (Edge-case: negative numbers as input)
</code>```

```<code>int num = 300
int divisor = -7
=>300 mod 7 = 6
</code>```

I used this method before but with negative numbers, it´s not working:

```<code>int method(int i, int div){
    return (num - divisor * (num / divisor));
}
</code>```

Expected result :

```<code>-1234, 512 ==> <302>
</code>```

Actual result :

```<code>-1234, 512 ==> <210>
</code>```

答:
Here is your method.

```<code>static int method(int num, int div){
   return num - div * (num / div);
}
</code>```

It works fine as it returns a remainder regardless of the signs used just like
%.  But if you want more of a positive mod answer you need to do the following:

```<code>static int method(int num, int div){
   int mod = num - div * (num / div);
   return (mod < 0) ? mod + div : mod;
}
</code>```

From the Java Virtual Machine Specification for irem.

Both value1 and value2 must be of type int. The values are popped
  from the operand stack. The int result is value1 - (value1 / value2)
  * value2. The result is pushed onto the operand stack.

Body:
For example with the following input:

int num = -100
int divisor = 10
=>  -100 mod 10 = 0   (Edge-case: negative numbers as input)

int num = 300
int divisor = -7
=>300 mod 7 = 6

I used this method before but with negative numbers, it´s not working:

int method(int i, int div){
    return (num - divisor * (num / divisor));
}

Expected result :

-1234, 512 ==> <302>

Actual result :

-1234, 512 ==> <210>

Body:
Here is your method.

static int method(int num, int div){
   return num - div * (num / div);
}

It works fine as it returns a remainder regardless of the signs used just like
%.  But if you want more of a positive mod answer you need to do the following:

static int method(int num, int div){
   int mod = num - div * (num / div);
   return (mod < 0) ? mod + div : mod;
}

From the Java Virtual Machine Specification for irem.

Both value1 and value2 must be of type int. The values are popped
  from the operand stack. The int result is value1 - (value1 / value2)
  * value2. The result is pushed onto the operand stack.


问:
React history.push() not rendering new component
I have a React.js project with a simple sign in function. After the user is authorized, I call history.push method which changes the link in the address bar but does not render the new component. (I use BrowserRouter)

My index.js component:

```<code>ReactDOM.render(
  <Provider store={createStore(mainReducer, applyMiddleware(thunk))}>
    <BrowserRouter>
      <Main />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);
</code>```

My Main.js component:

```<code>const Main = (props) => {
  return (
    <Switch>
      <Route exact path="/" component={Signin} />
      <Route exact path="/servers" component={Servers} />
    </Switch>
)}

export default withRouter(Main);
</code>```

My Action Creator:

```<code>export const authorization = (username, password) => (dispatch) =>
  new Promise ((resolve, reject) => {
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        password: password,
      })
    }).then( response => {
      if (response.ok) {
          response.json().then( result => {
            console.log("API reached.");
            dispatch(logUserIn(result.token));
            resolve(result);
        })
      } else {
        let error = new Error(response.statusText)
        error.response = response
        dispatch(showError(error.response.statusText), () => {throw error})
        reject(error);
      }
    });
  });
</code>```

My Signin.js component:

```<code> handleSubmit(event) {

    event.preventDefault();

    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token); //I do get "success" in console
      this.props.history.push('/servers') //Changes address, does not render /servers component
    });

  }

const mapActionsToProps = {
  onLoginRequest: authorization
}
</code>```

The weirdest thing is that if I change my handleSubmit() method to this - everything works perfectly:

```<code>  handleSubmit(event) {

    event.preventDefault();

    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token);
      //this.props.history.push('/servers')
    });
    this.props.history.push('/servers')
  }
</code>```

The same issue comes if I try to push history from the componentWillReceiveProps(newProps) method - it changes address but does not render new component. Could someone please explain why this happens and how to fix it?

答:
First, create a history object used the history package:

```<code>// src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
</code>```

Then wrap it in  in Main Router Component.

```<code>    import { Router, Route, Link } from 'react-router-dom';
    import history from './history';

    ReactDOM.render(
        <Provider store={store}>
          <Router history={history}>
            <Fragment>
              <Header />
              <Switch>
                <SecureRoute exact path="/" component={HomePage} />
                <Route exact path={LOGIN_PAGE} component={LoginPage} />
                <Route exact path={ERROR_PAGE} component={ErrorPage} />
              </Switch>
              <Footer />
            </Fragment>
      </Router>
    </Provider>)
</code>```

Here, After dispatching the request, redirecting to home page.

```<code>    function requestItemProcess(value) {
        return (dispatch) => {
            dispatch(request(value));
            history.push('/');
        };

    }
</code>```

should be helpful :)

Body:
I have a React.js project with a simple sign in function. After the user is authorized, I call history.push method which changes the link in the address bar but does not render the new component. (I use BrowserRouter)

My index.js component:

ReactDOM.render(
  <Provider store={createStore(mainReducer, applyMiddleware(thunk))}>
    <BrowserRouter>

    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

My Main.js component:

const Main = (props) => {
  return (
    <Switch>
      <Route exact path="/" component={Signin} />
      <Route exact path="/servers" component={Servers} />
    </Switch>
)}

export default withRouter(Main);

My Action Creator:

export const authorization = (username, password) => (dispatch) =>
  new Promise ((resolve, reject) => {
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        password: password,
      })
    }).then( response => {
      if (response.ok) {
          response.json().then( result => {
            console.log("API reached.");
            dispatch(logUserIn(result.token));
            resolve(result);
        })
      } else {
        let error = new Error(response.statusText)
        error.response = response
        dispatch(showError(error.response.statusText), () => {throw error})
        reject(error);
      }
    });
  });

My Signin.js component:

 handleSubmit(event) {

    event.preventDefault();

    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token); //I do get "success" in console
      this.props.history.push('/servers') //Changes address, does not render /servers component
    });

  }

const mapActionsToProps = {
  onLoginRequest: authorization
}

The weirdest thing is that if I change my handleSubmit() method to this - everything works perfectly:

  handleSubmit(event) {

    event.preventDefault();

    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token);
      //this.props.history.push('/servers')
    });
    this.props.history.push('/servers')
  }

The same issue comes if I try to push history from the componentWillReceiveProps(newProps) method - it changes address but does not render new component. Could someone please explain why this happens and how to fix it?

Body:
First, create a history object used the history package:

// src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();

Then wrap it in  in Main Router Component.

    import { Router, Route, Link } from 'react-router-dom';
    import history from './history';

    ReactDOM.render(
        <Provider store={store}>
          <Router history={history}>
            <Fragment>
              <Header />
              <Switch>
                <SecureRoute exact path="/" component={HomePage} />
                <Route exact path={LOGIN_PAGE} component={LoginPage} />
                <Route exact path={ERROR_PAGE} component={ErrorPage} />
              </Switch>
              <Footer />
            </Fragment>
      </Router>
    </Provider>)

Here, After dispatching the request, redirecting to home page.

    function requestItemProcess(value) {
        return (dispatch) => {
            dispatch(request(value));
            history.push('/');
        };

    }

should be helpful :)


问:
Permissions error creating .bak back-up of SQL Server database on Amazon RDS
I've inherited a website running on AWS. What I want to do is take a back-up of the SQL Server database (which is on Amazon RDS) so that I can set up a development environment locally. I have log-in credentials for the AWS console but I'm a complete newcomer in this environment so am trying to piece together the processes and terminology.

I've have read the docs here on how to enable import/export of SQL databases. There are 3 set-up steps in this guide:

Firstly, we need an S3 bucket. I see from the console that we already have a bucket called 'sqlbackups', so it would appear the previous dev has already gone through this process.

Secondly we need "An AWS Identity and Access Management (IAM) role to access the bucket". I've checked the console by going to 'IAM' from the 'services' list and selecting 'Roles' from the navigation on the left. We appear to have an IAM role called 'SQL_BackRestore_IAM'. I'm assuming that this is what we need, already set up by the previous dev?

Thirdly, we need "The SQLSERVER_BACKUP_RESTORE option added to an option group on your DB instance.". I've gone to the AWS console > RDS > Option groups and there's a group in there called 'custom-option-group-for-sql-express-v11' which has 'SQLSERVER_BACKUP_RESTORE' as an option. So, again, this looks like it has been set up already.

So now I believe I need to log in to the actual SQL Server and run a command to call a stored procedure to create the .bak backup. So I log into the database using the credentials I have from the website web.config file and I execute this:

```<code>exec msdb.dbo.rds_backup_database
@source_db_name='ExampleDBName',
@s3_arn_to_backup_to='arn:aws:s3:::sqlbackups/ExampleDBName.bak',
@type='FULL';
</code>```

However, I now get an error:

The EXECUTE permission was denied on the object 'rds_backup_database', database 'msdb', schema 'dbo'

Presumably it's something to do with the database log-in not having permissions to execute back-ups. I was not given any kind of sa or master database log-in though, so I'm now stuck!

Can anyone suggest how I can get this back-up command to work?

Many thanks.

答:
I had this same issue.

I solved it by using the RDS master username for login and running the backup procedure.

You can find the master username on the RDS database instance Configuration tab.

So in the AWS console:

RDS, Databases, Select Database, Configuration

If you don't know the master username password, you can also find that by clicking Modify on the database instance view. Set the password under Settings.

Body:
I've inherited a website running on AWS. What I want to do is take a back-up of the SQL Server database (which is on Amazon RDS) so that I can set up a development environment locally. I have log-in credentials for the AWS console but I'm a complete newcomer in this environment so am trying to piece together the processes and terminology.

I've have read the docs here on how to enable import/export of SQL databases. There are 3 set-up steps in this guide:

Firstly, we need an S3 bucket. I see from the console that we already have a bucket called 'sqlbackups', so it would appear the previous dev has already gone through this process.

Secondly we need "An AWS Identity and Access Management (IAM) role to access the bucket". I've checked the console by going to 'IAM' from the 'services' list and selecting 'Roles' from the navigation on the left. We appear to have an IAM role called 'SQL_BackRestore_IAM'. I'm assuming that this is what we need, already set up by the previous dev?

Thirdly, we need "The SQLSERVER_BACKUP_RESTORE option added to an option group on your DB instance.". I've gone to the AWS console > RDS > Option groups and there's a group in there called 'custom-option-group-for-sql-express-v11' which has 'SQLSERVER_BACKUP_RESTORE' as an option. So, again, this looks like it has been set up already.

So now I believe I need to log in to the actual SQL Server and run a command to call a stored procedure to create the .bak backup. So I log into the database using the credentials I have from the website web.config file and I execute this:

exec msdb.dbo.rds_backup_database
@source_db_name='ExampleDBName',
@s3_arn_to_backup_to='arn:aws:s3:::sqlbackups/ExampleDBName.bak',
@type='FULL';

However, I now get an error:

The EXECUTE permission was denied on the object 'rds_backup_database', database 'msdb', schema 'dbo'

Presumably it's something to do with the database log-in not having permissions to execute back-ups. I was not given any kind of sa or master database log-in though, so I'm now stuck!

Can anyone suggest how I can get this back-up command to work?

Many thanks.


问:
How can I filter an object based upon value in ReactJS?
I have the below objects. Whose value is YES, I need to filter it and store it in variable.</p>

```<code>"CalcResult": {
        "result": [
            {
                "IS_RPOP": "YES",
                "IS_ENE": "NO",
                "IS_SLO": "YES",
                "STATUS": "INCOMPLETE"
            }
        ],
        "Info": {
            "STATUS": [
                "INCOMPLETE"
            ]
        }
    }
</code>```

答:
Seems you want the keys and values which are equal to YES, if so you can try this method:

let data ={ "result": [ { "IS_RPOP": "YES", "IS_ENE": "NO", "IS_SLO": "YES", "STATUS": "INCOMPLETE" } ], "Info": { "STATUS": [ "INCOMPLETE" ] } };
var result = Object.fromEntries(Object.entries(data.result[0]).filter(([k,v])=>v=='YES'));

console.log(result)```

Body:
I have the below objects. Whose value is YES, I need to filter it and store it in variable.

"CalcResult": {
        "result": [
            {
                "IS_RPOP": "YES",
                "IS_ENE": "NO",
                "IS_SLO": "YES",
                "STATUS": "INCOMPLETE"
            }
        ],
        "Info": {
            "STATUS": [
                "INCOMPLETE"
            ]
        }
    }


问:
Turn multiple numbers from my web scraper into a list
When I run this code:

```<code>for promotion in soup.find_all("div", class_="promo"):
    headline = promotion.text
    headline = re.sub('[^0-9]', '', headline)
    print(headline)
</code>```

It prints out 30 numbers but I am trying to figure out a way to put those numbers into a list so I can take the 5 most recent numbers from it each time the script runs. Thank you for the help!

答:
If I am not wrong and if you mean the recent 5 numbers by last 5 numbers in your list this is the code you need.

```<code>promotion_list = []  # making new list
for promotion in soup.find_all("div", class_="promo"):
    headline = promotion.text
    headline = re.sub('[^0-9]', '', headline)
    print(headline)
    promotion_list.append(headline)  # putting all your 30 items in the new list
for i in range(1, 6):
    print(promotion_list[i * -1])  # this will print the last 5 or recent 5 items
</code>```

Hope you find this code helpful

Body:
When I run this code:

for promotion in soup.find_all("div", class_="promo"):
    headline = promotion.text
    headline = re.sub('[^0-9]', '', headline)
    print(headline)

It prints out 30 numbers but I am trying to figure out a way to put those numbers into a list so I can take the 5 most recent numbers from it each time the script runs. Thank you for the help!

Body:
If I am not wrong and if you mean the recent 5 numbers by last 5 numbers in your list this is the code you need.

promotion_list = []  # making new list
for promotion in soup.find_all("div", class_="promo"):
    headline = promotion.text
    headline = re.sub('[^0-9]', '', headline)
    print(headline)
    promotion_list.append(headline)  # putting all your 30 items in the new list
for i in range(1, 6):
    print(promotion_list[i * -1])  # this will print the last 5 or recent 5 items

Hope you find this code helpful


问:
Unsafe value used in a resource URL context (iframe)
Trying to pass value as iframe url from local db and and im getting error message:
 Unsafe value used in a resource URL context.
i'm trying to display an array of printers ip so i will be able to check their status via the website there is anyway to do this without iframe ?
i will be more then glad to hear some advises.

I'm new to angular and every help is more then welcome
thanks in advance.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  values: any;

  constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

ngOnInit() {
  this.getValues();

}

getValues() {
  this.http.get('http://localhost:5000/api/values/').subscribe(response => {
    this.values = response;
  }, error => {
    console.log(error);
  })
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><H2>Print Manager</H2>

<div id="outerdiv">
  <iframe src="http://192.168.1.6/general/status.html" id="inneriframe" scrolling="no"  ></iframe>
</div>

<div *ngFor="let value of values">
<p>{{value.id}},{{value.hostName}},{{value.location}},{{value.manufacturer}},{{value.ip}}</p>

<span>Hostname: {{value.hostName}}</span>
<br>
<span>Location: {{value.location}}</span>
<br>
<span>Manufacturer: {{value.manufacturer}}</span>
<br>
<span>IP: {{value.ip}}</span>

</div></code>```

答:
You may use Angular DomSanitizer from @angular/platform-browser

Refer Angular Guide for more info

```<code>import {DomSanitizationService} from '@angular/platform-browser';

@Component({
  templateUrl: 'temp.html'
})
export class AppComponent {
yourUrl : '';
  constructor(private sanitizer : DomSanitizationService) {
  }

  getSanitizedURL() {
    return this.sanitizer.bypassSecurityTrustUrl(yourUrl);
  }
}
</code>```

HTML :

```<code>   <div id="outerdiv">
      <iframe src="getSanitizedURL()" id="inneriframe" scrolling="no"></iframe>
    </div>
</code>```

Body:
Trying to pass value as iframe url from local db and and im getting error message:
 Unsafe value used in a resource URL context.
i'm trying to display an array of printers ip so i will be able to check their status via the website there is anyway to do this without iframe ?
i will be more then glad to hear some advises.

I'm new to angular and every help is more then welcome
thanks in advance.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  values: any;

  constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

ngOnInit() {
  this.getValues();

}

getValues() {
  this.http.get('http://localhost:5000/api/values/').subscribe(response => {
    this.values = response;
  }, error => {
    console.log(error);
  })
}

}

Print Manager

{{value.id}},{{value.hostName}},{{value.location}},{{value.manufacturer}},{{value.ip}}

Hostname: {{value.hostName}}

Location: {{value.location}}

Manufacturer: {{value.manufacturer}}

IP: {{value.ip}}

Body:
You may use Angular DomSanitizer from @angular/platform-browser

Refer Angular Guide for more info

import {DomSanitizationService} from '@angular/platform-browser';

@Component({
  templateUrl: 'temp.html'
})
export class AppComponent {
yourUrl : '';
  constructor(private sanitizer : DomSanitizationService) {
  }

  getSanitizedURL() {
    return this.sanitizer.bypassSecurityTrustUrl(yourUrl);
  }
}

HTML :

   <div id="outerdiv">
      <iframe src="getSanitizedURL()" id="inneriframe" scrolling="no"></iframe>
    </div>


问:
Replace string between first and second occurrence of forward slash
i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.

Example

```<code>const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

</code>```

Output:

/questions/ask/1 to /example/ask/1

/questions-math/ask/1 to /example/ask/1

I can't seem to get right regex.
Thanks for any help. I know there are lot of similar questions but I just could not find a solution.

答:
It may be better to use simple JS like this:

var str = '/questions/ask/1';
var res = str.split("/");
res[1] = 'example';
res = res.join("/");
```

Body:
i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.

Example

const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

Output:

/questions/ask/1 to /example/ask/1

/questions-math/ask/1 to /example/ask/1

I can't seem to get right regex.
Thanks for any help. I know there are lot of similar questions but I just could not find a solution.


问:
CORS Policy Error only in reactjs when submitting a post request and working in postman
I'm having a "...has been blocked by CORS policy" error when trying to use the method post in my reactjs frontend even though i have enabled the @CrossOrigin annotation in ly spring boot backend and even though when testing the request on postman it works perfectly, the problem is in the frontend and i haven found any helpful solution

Here s my entity class:

```<code>@Entity
@Table(name="clientcheck")
public class ClientCheckEntity {

@Id
@Column(name="email")
private String email;

 @Column(name="password")
 private String passwordClient;

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPasswordClient() {
    return passwordClient;
}

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

My controller Class

```<code>@CrossOrigin(origins = "*", allowedHeaders = "*" )
@RestController
@RequestMapping("/clientschecklist")
public class ClientCheck {

@Autowired
private ClientsFunctionsImpl clientsfunctionsimpl;

@Autowired
private ClientsRepository2 clientsRepository;

@PostMapping("")
public ResponseEntity<ClientCheckEntity> createEmployee(@Valid @RequestBody ClientCheckEntity client)
{

    ClientCheckEntity client1 = clientsRepository.save(client);

    return new ResponseEntity<ClientCheckEntity>(client1,HttpStatus.CREATED);
}
}
</code>```

My Repository Interface :

```<code>@Repository
public interface ClientsRepository2 extends JpaRepository<ClientCheckEntity , String>{
}
</code>```

Frontend

My Signup Class:

```<code>import React, { Component } from 'react';
import "bootstrap/dist/css/bootstrap-grid.min.css";
import * as Yup from 'yup';
import Errors from '../Errors';
import {Formik} from 'formik';
import ClientService from './service';

const validationSchema = Yup.object().shape({

email: Yup.string()
.email('Invalid Email Address')
.required('Required Field'),

password: Yup.string()
.min(8,'Minimum 8 Characters')
.required('Required Field'),

 })

class Signin extends Component {
constructor(props){
super(props);
this.state = {
  email:'',
  password:'',
  disable:true
   };

  }

  handleSubmit=(values) =>{
   ClientService.createClient(
    {
    email: values.email,
    password: values.password
    }
    ).then(
    console.log(values)
     ).catch(
     console.log("not working")
    )
    }
render() {
  let {email,password} = this.state
    return (
    <div className="wrapper justify-content-center">

        <div className="form-wrapper">
          <h1>
            <b>
              <i>Create an Account</i>
            </b>
          </h1>

          <Formik
          initialValues={{ email,password}}
          validationSchema = {validationSchema}
          onSubmit={(values, {setSubmitting, resetForm}) => {

          setSubmitting(true);

          setTimeout(() => {
         alert(JSON.stringify(values, null, 2));
         resetForm();
         setSubmitting(false);

         }, 500);
    }}

  >
  {({values, errors, touched, handleChange, handleSubmit,isSubmitting }) => (

          <form className="the-form" onSubmit={handleSubmit}>
            <div className="row">
              <div className="col-md-12 ">
                <input
                  type="text"
                  placeholder="Enter email"
                  name="email"
                  onChange={handleChange}
                  value={values.email}

                  className={touched.email && errors.email ? "error"  :null }

                />
                <Errors touched={touched.email} message={errors.email} />
              </div>

              <div className="col-md-12 ">
                <input
                  type="password"
                  placeholder="Enter password"
                  name="password"
                  onChange={handleChange}
                  value={values.password}

                  className={touched.password && errors.password ? "error" : null}
                />

                <Errors touched={touched.password} message={errors.password} />
              </div>
              </div>

              <div className="createAccount">
            <button type="submit" className="btn btn-primary btn-block" disabled={isSubmitting} onClick= {this.handleSubmit}>
              Sign Up
            </button>
            <small>
              Already have an account ?

            </small>
          </div>
          </form>

          )}

         </Formik>
        </div>
      </div>

    );
}
}

export default Signin;
</code>```

My Service Class:

```<code>   import axios from 'axios';

   class ClientService{
   createClient(client){

    return axios.post(`http://localhost:8080/clientscheklist/`, client);

  }
   }

  export default new ClientService()
</code>```

答:
Here are some things you can try.

First of all, at your createClient function, call a console.log with JSON stringify like that:

```<code>createClient(client){

console.log(JSON.stringify(client));

return axios.post(`http://localhost:8080/clientscheklist/`, client);

}
</code>```

With that, go to your postman and change the type of body (since it is a POST) to "raw". Input your JSON that have been logged into your console and give it a try.

If it doesn't works, review that JSON and you should find the error.

If it works, you should try some headers like that in your axios post:

```<code>const headers = {
 'Content-Type': 'application/json'
}
  axios.post(API_URL, data, {
  headers: headers
})
</code>```

Body:
I'm having a "...has been blocked by CORS policy" error when trying to use the method post in my reactjs frontend even though i have enabled the @CrossOrigin annotation in ly spring boot backend and even though when testing the request on postman it works perfectly, the problem is in the frontend and i haven found any helpful solution

Here s my entity class:

@Entity
@Table(name="clientcheck")
public class ClientCheckEntity {

@Id
@Column(name="email")
private String email;

 @Column(name="password")
 private String passwordClient;

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPasswordClient() {
    return passwordClient;
}

public void setPasswordClient(String passwordClient) {
    this.passwordClient = passwordClient;
}
}

My controller Class

@CrossOrigin(origins = "*", allowedHeaders = "*" )
@RestController
@RequestMapping("/clientschecklist")
public class ClientCheck {

@Autowired
private ClientsFunctionsImpl clientsfunctionsimpl;

@Autowired
private ClientsRepository2 clientsRepository;

@PostMapping("")
public ResponseEntity<ClientCheckEntity> createEmployee(@Valid @RequestBody ClientCheckEntity client)
{

    ClientCheckEntity client1 = clientsRepository.save(client);

    return new ResponseEntity<ClientCheckEntity>(client1,HttpStatus.CREATED);
}
}

My Repository Interface :

@Repository
public interface ClientsRepository2 extends JpaRepository<ClientCheckEntity , String>{
}

Frontend

My Signup Class:

import React, { Component } from 'react';
import "bootstrap/dist/css/bootstrap-grid.min.css";
import * as Yup from 'yup';
import Errors from '../Errors';
import {Formik} from 'formik';
import ClientService from './service';

const validationSchema = Yup.object().shape({

email: Yup.string()
.email('Invalid Email Address')
.required('Required Field'),

password: Yup.string()
.min(8,'Minimum 8 Characters')
.required('Required Field'),

 })

class Signin extends Component {
constructor(props){
super(props);
this.state = {
  email:'',
  password:'',
  disable:true
   };

  }

  handleSubmit=(values) =>{
   ClientService.createClient(
    {
    email: values.email,
    password: values.password
    }
    ).then(
    console.log(values)
     ).catch(
     console.log("not working")
    )
    }
render() {
  let {email,password} = this.state
    return (

              Create an Account

          <Formik
          initialValues={{ email,password}}
          validationSchema = {validationSchema}
          onSubmit={(values, {setSubmitting, resetForm}) => {

          setSubmitting(true);

          setTimeout(() => {
         alert(JSON.stringify(values, null, 2));
         resetForm();
         setSubmitting(false);

         }, 500);
    }}

  >
  {({values, errors, touched, handleChange, handleSubmit,isSubmitting }) => (

          <form className="the-form" onSubmit={handleSubmit}>

                <input
                  type="text"
                  placeholder="Enter email"
                  name="email"
                  onChange={handleChange}
                  value={values.email}

                  className={touched.email && errors.email ? "error"  :null }

                />
                <Errors touched={touched.email} message={errors.email} />

                <input
                  type="password"
                  placeholder="Enter password"
                  name="password"
                  onChange={handleChange}
                  value={values.password}

                  className={touched.password && errors.password ? "error" : null}
                />

                <Errors touched={touched.password} message={errors.password} />

            <button type="submit" className="btn btn-primary btn-block" disabled={isSubmitting} onClick= {this.handleSubmit}>
              Sign Up
            </button>

              Already have an account ?

          </form>

          )}

         </Formik>

    );
}
}

export default Signin;

My Service Class:

   import axios from 'axios';

   class ClientService{
   createClient(client){

    return axios.post(`http://localhost:8080/clientscheklist/`, client);

  }
   }

  export default new ClientService()

Body:
Here are some things you can try.

First of all, at your createClient function, call a console.log with JSON stringify like that:

createClient(client){

console.log(JSON.stringify(client));

return axios.post(`http://localhost:8080/clientscheklist/`, client);

}

With that, go to your postman and change the type of body (since it is a POST) to "raw". Input your JSON that have been logged into your console and give it a try.

If it doesn't works, review that JSON and you should find the error.

If it works, you should try some headers like that in your axios post:

const headers = {
 'Content-Type': 'application/json'
}
  axios.post(API_URL, data, {
  headers: headers
})


问:
How to convert jmeter dashboard report to pdf
How to convert jmeter dashboard report to pdf

I'm unable to convert html report to pdf. plz suggest me the solution

答:
C'mon, have you done at least basic research before asking? There are a lot of options, for example:

Print it to file, all modern browsers allow saving web content as PDF, check out How to save a webpage as a PDF

There are online solutions like https://html2pdf.com/

There are offline solutions like http://www.pdflite.com/html-to-pdf/

There is BM.Sense online results analysis service which allows saving load test report as PDF


问:
Add custom column to IDataView in ML.NET
I'd like to add a custom column after loading my IDataView from file.
In each row, the column value should be the sum of previous 2 values. A sort of Fibonacci series.

I was wondering to create a custom transformer but I wasn't able to find something that could help me to understand how to proceed.
I also tried to clone ML.Net Git repository in order to see how other transformers were implemented but I saw many classes are marked as internal so I cannot re-use them in my project.

答:
Easy thing. I am assuming, you know how to use pipelines.

This is a part of my project, where I merge two columns together:

```<code>IEstimator<ITransformer> pipeline = mlContext.Transforms.CustomMapping(mapping, contractName: null)
                            .Append(mlContext.Transforms.Text.FeaturizeText(inputColumnName: "question1", outputColumnName: "question1Featurized"))
                            .Append(mlContext.Transforms.Text.FeaturizeText(inputColumnName: "question2", outputColumnName: "question2Featurized"))
                            .Append(mlContext.Transforms.Concatenate("Features", "question1Featurized", "question2Featurized"))
                            //.Append(mlContext.Transforms.NormalizeMinMax("Features"))
                            //.AppendCacheCheckpoint(mlContext)
                            .Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: nameof(customTransform.Label), featureColumnName: "Features"));
</code>```

As you can see the two columns question1Featurized and question2Featurized are combined into Features which will be created and can be used as any other column of IDataView. The Features column does not need to be declared in a separate class.

So in your case you should transform the columns firs in their data type, if strings you can do what I did and in case of numeric values use a custom Transformer/customMapping.

The documentation of the Concatenate function might help as well!

Body:
Easy thing. I am assuming, you know how to use pipelines.

This is a part of my project, where I merge two columns together:

IEstimator<ITransformer> pipeline = mlContext.Transforms.CustomMapping(mapping, contractName: null)
                            .Append(mlContext.Transforms.Text.FeaturizeText(inputColumnName: "question1", outputColumnName: "question1Featurized"))
                            .Append(mlContext.Transforms.Text.FeaturizeText(inputColumnName: "question2", outputColumnName: "question2Featurized"))
                            .Append(mlContext.Transforms.Concatenate("Features", "question1Featurized", "question2Featurized"))
                            //.Append(mlContext.Transforms.NormalizeMinMax("Features"))
                            //.AppendCacheCheckpoint(mlContext)
                            .Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: nameof(customTransform.Label), featureColumnName: "Features"));

As you can see the two columns question1Featurized and question2Featurized are combined into Features which will be created and can be used as any other column of IDataView. The Features column does not need to be declared in a separate class.

So in your case you should transform the columns firs in their data type, if strings you can do what I did and in case of numeric values use a custom Transformer/customMapping.

The documentation of the Concatenate function might help as well!


问:
Search and get value from JSON using Node.js
I need to search "Info" from below json and get response as below using node.js.

Please help on this.

JSON File

```<code>{
      "call": "Info",
      "locator": "test.so",
      "classname": "DeviceInfo",
      "autostart": true,
      "state": "activated",
       "module": "Plugin",
}
</code>```

Response

```<code>Info,test.so,DeviceInfo,true,activated,Plugin
</code>```

I have tried below and printing only Info not all data's.I need to search with Info not call

```<code>var fs = require("fs");
var content = fs.readFileSync("D:/Test1.json");
var objectValue = JSON.parse(content);
console.log(objectValue.call);

</code>```

答:
You may use Object.values(...) as described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

var fs = require("fs");
var content = fs.readFileSync("D:/Test1.json");
var objectValue = JSON.parse(content);
// output: [ 'Info', 'test.so', 'DeviceInfo', true, 'activated', 'Plugin' ]

```

Body:
I need to search "Info" from below json and get response as below using node.js.

Please help on this.

JSON File

{
      "call": "Info",
      "locator": "test.so",
      "classname": "DeviceInfo",
      "autostart": true,
      "state": "activated",
       "module": "Plugin",
}

Response

Info,test.so,DeviceInfo,true,activated,Plugin

I have tried below and printing only Info not all data's.I need to search with Info not call

var fs = require("fs");
var content = fs.readFileSync("D:/Test1.json");
var objectValue = JSON.parse(content);
console.log(objectValue.call);


问:
is there a quick script to rename JPGs in a folder to their HSL values
Im sure this is possible but:

I'm looking to simply rename swatch type 60px x 60px images based on their extracted HSL values.
"apple-candy.jpg" becomes 341-64-73.jpg

I only need to run this once. Bonus would be to use a 5px average at the 30px 30px coordinates.
Any help would be awesome

答:
With ImageMagick, the command would be something close too...

```<code>magick ./path/to/source/*.jpg \
    -set filename:base '%[fx:floor(hue*100)]-%[fx:floor(saturation*100)]-%[fx:floor(lightness*100)]' \
    './path/to/destination/%[filename:base].jpg'
</code>```

Haven't tested the above, but you may need to add -colorspace HSL depending how the data values are encoded.

Body:
With ImageMagick, the command would be something close too...

magick ./path/to/source/*.jpg \
    -set filename:base '%[fx:floor(hue*100)]-%[fx:floor(saturation*100)]-%[fx:floor(lightness*100)]' \
    './path/to/destination/%[filename:base].jpg'

Haven't tested the above, but you may need to add -colorspace HSL depending how the data values are encoded.


问:
Matplotlib pie chart wedge transparency?
I saw that matplotlib's pyplot.scatter() has an 'alpha' parameter that can be used to set the transparency of points. The pyplot.pie() doesn't have a similar parameter however. How can I set the transparency of certain wedges?</p>

答:
I found the answer while writing up this question and figured I'd post the solution for anyone who wants to know.

To set a wedge to be transparent:

```<code>import matplotlib.pyplot as plt

x  = [1,2,3,0.4,5]
alpha = 0.5
which_wedge = 4
n = plt.pie(x)
n[0][which_wedge].set_alpha(alpha)
</code>```

If you want to only display a single wedge, use a loop:

```<code>for i in range(len(n[0])):
    n[0][i].set_alpha(0.0)
n[0][which_wedge].set_alpha(1.0)
</code>```

Hope this helps someone! It can probably be used for pyplot.bar() too to hide certain bars.

Body:
I found the answer while writing up this question and figured I'd post the solution for anyone who wants to know.

To set a wedge to be transparent:

import matplotlib.pyplot as plt

x  = [1,2,3,0.4,5]
alpha = 0.5
which_wedge = 4
n = plt.pie(x)
n[0][which_wedge].set_alpha(alpha)

If you want to only display a single wedge, use a loop:

for i in range(len(n[0])):
    n[0][i].set_alpha(0.0)
n[0][which_wedge].set_alpha(1.0)

Hope this helps someone! It can probably be used for pyplot.bar() too to hide certain bars.


问:
Use VS Code for Cross-Platform Scalable C++ Project
This tutorial provided by the VS Code team explains how to setup C++ in VS Code with MinGW (https://code.visualstudio.com/docs/cpp/config-mingw), however it seems to only target small-scale projects as it is configured to rebuilds all files each time, and isn't setup to allow for easy configuration of a project (global defines, adding link libraries etc.) (or am I missing something?).

I am looking into using CMake as my build tool inside VS Code, however am really turned off by the idea of having to update the CMakeLists.txt file to change my project's configurations, e.g. every time I add files to my project or link a new library, as I have grown up using IDEs who do this process for me, which I find magnitudes easier as it allows me to purely to focus on writing code.

My question is, is there a known method to setup VS Code that will allow me to use a tool such as CMake without having to tinker with it too often?

This tutorial seems like a good starting point to setup CMake, but its method requires CMake knowledge https://pspdfkit.com/blog/2019/visual-studio-code-for-cpp/

I ideally would like the setup to cater for both small-scale and large-scale projects, both of which should allow for cross-platform building.

Thanks

答:
As Visual Studio Code is not a heavy weight IDE, you will need to put some effort to get it run the way you want it to have, either:
Write a CMake InputFile generator, e.g. :

```<code>list(APPEND EXECUTABLE_LIST executable_1 executable_2)
list(APPEND LIBRARY_LIST library_2 library_2 library_3)

foreach(lib IN LISTS LIBRARY_LIST)
     add_library(${lib} STATIC ${lib}.cpp)
endforeach()

foreach(exe IN LISTS EXECUTABLE_LIST)
    add_executable(${exe} ${exe}.cpp)
    target_include_directories(${exe} PUBLIC ${CMAKE_CURRENT_LIST_DIR})
    target_link_libraries(${exe} ${LIBRARY_LIST})
endforeach()
</code>```

or you could also use Visual Studio Code CMake Tool extention

For sure, you couldn't expect the highly functionality like Visual Studio in VS Code  as they serve different purpose (highly specialised, deep system couple but slow and big vs small, fast, highly configurable).

Body:
As Visual Studio Code is not a heavy weight IDE, you will need to put some effort to get it run the way you want it to have, either:
Write a CMake InputFile generator, e.g. :

list(APPEND EXECUTABLE_LIST executable_1 executable_2)
list(APPEND LIBRARY_LIST library_2 library_2 library_3)

foreach(lib IN LISTS LIBRARY_LIST)
     add_library(${lib} STATIC ${lib}.cpp)
endforeach()

foreach(exe IN LISTS EXECUTABLE_LIST)
    add_executable(${exe} ${exe}.cpp)
    target_include_directories(${exe} PUBLIC ${CMAKE_CURRENT_LIST_DIR})
    target_link_libraries(${exe} ${LIBRARY_LIST})
endforeach()

or you could also use Visual Studio Code CMake Tool extention

For sure, you couldn't expect the highly functionality like Visual Studio in VS Code  as they serve different purpose (highly specialised, deep system couple but slow and big vs small, fast, highly configurable).


问:
Dynamic search : Pandas data frame query
I am trying to take a string (word or phrase) user input to search for sub string in a particular column to query the results. How can i make it dynamic ? i.e. i want to keep adding the words as new queries to locate the item without having to define it.

eg. if input is - 'word1';
it returns all rows with 'word1' in df['column']

and if input is - 'word1 word2 wordn';
it returns all rows with the query as below :

```<code>x = input("Type to search for item : ")  # input phrase or word
words = x.split(' ')

query = df.loc[(df['Column'].str.contains(words[0]))
           &(df['Column'].str.contains(words[1]))
           &(df['Column'].str.contains(words[n]))
           ]
</code>```

答:
Consider Series.str.contains using regex with AND logic:

```<code>words_pattern = r"(" + ")(".join(words) + ")"

sub_df = df.loc[df['char'].str.contains(words_pattern, regex=True)]
</code>```

Alternatively, per warning in using regex string groupings, use Series.str.extract

```<code>words_pattern = r"(" + ")(".join(words) + ")"

res = df['char'].str.extract(words_pattern)
sub_df = df.loc[res.dropna().index]
</code>```

Body:
I am trying to take a string (word or phrase) user input to search for sub string in a particular column to query the results. How can i make it dynamic ? i.e. i want to keep adding the words as new queries to locate the item without having to define it.

eg. if input is - 'word1';
it returns all rows with 'word1' in df['column']

and if input is - 'word1 word2 wordn';
it returns all rows with the query as below :

x = input("Type to search for item : ")  # input phrase or word
words = x.split(' ')

query = df.loc[(df['Column'].str.contains(words[0]))
           &(df['Column'].str.contains(words[1]))
           &(df['Column'].str.contains(words[n]))
           ]

Body:
Consider Series.str.contains using regex with AND logic:

words_pattern = r"(" + ")(".join(words) + ")"

sub_df = df.loc[df['char'].str.contains(words_pattern, regex=True)]

Alternatively, per warning in using regex string groupings, use Series.str.extract

words_pattern = r"(" + ")(".join(words) + ")"

res = df['char'].str.extract(words_pattern)
sub_df = df.loc[res.dropna().index]


问:
How to send Cutomised output through RUNDECK
I have set my rundeck-config.groovy in my config folder and this is included in my profile file as well.

My Groovy file:

```<code>grails.mail.default.from="pavan@gmail.com" grails {  mail {host = "smtp.gmail.com"   username = "pavan@gmail.com"    port = 587    password = "ghsdkexgbnsowmdsu"    props =["mail.smtp.starttls.enable":"true", "mail.smtp.port":587, "mail.smtp.auth":"true"]  }}
</code>```

when i run my RUNDECK job i am recieving email notification, but the email i recieve has all the details, logs, commands used, even code which i dont want the recipent to see

i want to customise it and show only the output result in message body.

example: Checking Health of a server

```<code>url = "curl -kv https://vn2-lpgdmt-capp99.rno.vzon.com:8990/health/check"
</code>```

in the output i only want to show as

https://vn2-lpgdmt-capp99.rno.vzon.com:8990/health/check = Status:200 ok

kindly help, what plugins i might have to add or anything

thank you in advance

答:
You can use a custom template with your email notification that prints the output using ${logouput.data} to print the output, I leave an example:

<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='myurl' value='http://www.google.com' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <executionEnabled>true</executionEnabled>
    <id>322beb61-c701-4758-b58f-55da63953dee</id>
    <loglevel>INFO</loglevel>
    <name>CheckStatusExample</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <notification>
      <onsuccess>
        <email attachLog='true' attachLogInline='true' recipients='devopsteam@example.net' subject='Success!' />
      </onsuccess>
    </notification>
    <notifyAvgDurationThreshold />
    <plugins />
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <fileExtension>.sh</fileExtension>

      </command>
    </sequence>
    <uuid>322beb61-c701-4758-b58f-55da63953dee</uuid>
  </job>
</joblist>
```

<p>With this HTML template:</p>

<pre class="lang-html prettyprint-override"><code><html>
    <head>
        <title>my template</title>
    </head>
    <body>
        <p>Data: ${logoutput.data}</p>
    </body>
</html>
</code>```

Here the result on Rundeck, and here on the email inbox.

Body:
I have set my rundeck-config.groovy in my config folder and this is included in my profile file as well.

My Groovy file:

grails.mail.default.from="pavan@gmail.com" grails {  mail {host = "smtp.gmail.com"   username = "pavan@gmail.com"    port = 587    password = "ghsdkexgbnsowmdsu"    props =["mail.smtp.starttls.enable":"true", "mail.smtp.port":587, "mail.smtp.auth":"true"]  }}

when i run my RUNDECK job i am recieving email notification, but the email i recieve has all the details, logs, commands used, even code which i dont want the recipent to see

i want to customise it and show only the output result in message body.

example: Checking Health of a server

url = "curl -kv https://vn2-lpgdmt-capp99.rno.vzon.com:8990/health/check"

in the output i only want to show as

https://vn2-lpgdmt-capp99.rno.vzon.com:8990/health/check = Status:200 ok

kindly help, what plugins i might have to add or anything

thank you in advance

Body:
You can use a custom template with your email notification that prints the output using ${logouput.data} to print the output, I leave an example:

<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='myurl' value='http://www.google.com' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <executionEnabled>true</executionEnabled>
    <id>322beb61-c701-4758-b58f-55da63953dee</id>
    <loglevel>INFO</loglevel>
    <name>CheckStatusExample</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <notification>
      <onsuccess>
        <email attachLog='true' attachLogInline='true' recipients='devopsteam@example.net' subject='Success!' />
      </onsuccess>
    </notification>
    <notifyAvgDurationThreshold />
    <plugins />
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <fileExtension>.sh</fileExtension>
        <script><![CDATA[echo "@option.myurl@=$(curl --write-out %{http_code} --silent --output /dev/null @option.myurl@)"]]></script>
        <scriptargs />
        <scriptinterpreter>/bin/bash</scriptinterpreter>
      </command>
    </sequence>
    <uuid>322beb61-c701-4758-b58f-55da63953dee</uuid>
  </job>
</joblist>

With this HTML template:

<html>
    <head>
        <title>my template</title>
    </head>
    <body>
        <p>Data: ${logoutput.data}</p>
    </body>
</html>

Here the result on Rundeck, and here on the email inbox.