问:
How to know which params is missing in a query?
I'm setting up a Booking router in NodeJS, and I have many params in.
Now when I forgot params I return an error like :

500: Need more information

I wonder if it's possible to know which params are missing when I return the error code.

This is for a new API made in NodeJS

Here are the params that I want to retrieve from the front ( made in ReactJS )

```<code>let body = {
        agentDutyCode: "STRING",
        RatePlanCode: params.rateCode,
        RoomCode: params.roomCode,
        AmountAfterTax: params.amountTax,
        Start: params.fromDate,
        End: params.toDate,
        CardCode: params.cardCode,
        CardNumber: params.cardNumber,
        ExpireDate: params.expireDate,
        SeriesCode: params.cvv,
        CardHolderName: params.nameCard,
        ChainCode: params.chainCode,
        HotelCode: params.hotelCode,
        RoomQuantities: params.roomQuantities,
        GuestQuantitie: params.numberGuest,
        GuestPerRoom: params.guestPerRoom,
        LastName: params.lastName,
        FirstName: params.firstName,
        PhoneNumber: params.phoneNumber,
        email: params.email,
        FVL_SUBUNIT_7: params.walletAddress
    }
</code>```

And this is my promise :

 cdsJson.bookResource(req.body)
        .then((response) => {
            if (response !== null) {
                res.response = {
                    ...response
                }
            } if (response.hotel.length === 0) {
                res.respStatus = 500
                res.response = {
                    sendMsg: "Need more informations"
                }
                next('route')
            }
            return response
        })
```

If the request succeeds I got a reservation ID otherwise I got :

Error 500: Need more information

答:
You're trying to do server side validation. In Node a good approach would be to define a JSON Schema for the expected parameters and then in your route handler validate the data sent in the request with a JSON Schema validator. This would help you work out whether a request was valid and help you generate error messages automatically. As a rule it's much better (i.e. simpler and more maintainable) to use tools that enable you to declaratively declare your validation (via a schema) than imperatively write code to manually validate objects.

JSON Schema spec https://json-schema.org/

A validator https://github.com/epoberezkin/ajv

Body:
I'm setting up a Booking router in NodeJS, and I have many params in.
Now when I forgot params I return an error like :

500: Need more information

I wonder if it's possible to know which params are missing when I return the error code.

This is for a new API made in NodeJS

Here are the params that I want to retrieve from the front ( made in ReactJS )

let body = {
        agentDutyCode: "STRING",
        RatePlanCode: params.rateCode,
        RoomCode: params.roomCode,
        AmountAfterTax: params.amountTax,
        Start: params.fromDate,
        End: params.toDate,
        CardCode: params.cardCode,
        CardNumber: params.cardNumber,
        ExpireDate: params.expireDate,
        SeriesCode: params.cvv,
        CardHolderName: params.nameCard,
        ChainCode: params.chainCode,
        HotelCode: params.hotelCode,
        RoomQuantities: params.roomQuantities,
        GuestQuantitie: params.numberGuest,
        GuestPerRoom: params.guestPerRoom,
        LastName: params.lastName,
        FirstName: params.firstName,
        PhoneNumber: params.phoneNumber,
        email: params.email,
        FVL_SUBUNIT_7: params.walletAddress
    }

And this is my promise :

 cdsJson.bookResource(req.body)
        .then((response) => {
            if (response !== null) {
                res.response = {
                    ...response
                }
            } if (response.hotel.length === 0) {
                res.respStatus = 500
                res.response = {
                    sendMsg: "Need more informations"
                }
                next('route')
            }
            return response
        })

If the request succeeds I got a reservation ID otherwise I got :

Error 500: Need more information


来源: stackexchange

问:
SQL Where clause greatly increases query time
I have a table that I do some joins and operations on. This table has about 150,000 rows and if I select all and run it, it returns in about 10 seconds. If I create my query into its own table, and filter out all the rows where a certain field is null, now the query takes 10 minutes to run. Is it suppoused to be like this or is there any way to fix it? Here is the query. </p>

```<code>SELECT *
FROM
(
    Select
     I.Date_Created
    ,I.Company_Code
    ,I.Division_Code
    ,I.Invoice_Number
    ,Sh.CUST_PO
    ,I.Total_Quantity
    ,ID.Total
    ,SH.Ship_City City
    ,CASE WHEN SH.Ship_Cntry <> 'US' THEN 'INT' ELSE SH.Ship_prov END State
    ,SH.Ship_Zip Zip
    ,SH.Ship_Cntry Country
    ,S.CustomerEmail
    from [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock)
    LEFT JOIN (SELECT
                    ID.Company_Code
                    ,ID.Division_Code
                    ,ID.Invoice_Number
                    ,SUM (ID.Price* ID.Quantity) Total
                    FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices_Detail ID (nolock)
                    GROUP BY ID.Company_Code, ID.Division_Code, ID.Invoice_Number) ID
            ON I.Company_Code = ID.Company_Code
            AND I.Division_Code = ID.Division_Code
            AND I.Invoice_Number = ID.Invoice_Number
    LEFT JOIN
        [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].SHIPHIST SH (nolock) ON I.Pickticket_Number = SH.Packslip
    LEFT JOIN
        [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].[MagentoCustomerEmailData] S on SH.CUST_PO = S.InvoiceNumber

    Where I.Company_Code ='09' AND I.Division_Code = '001'
    AND I.Customer_Number = 'ECOM2X'
    )T
    Where T.CustomerEmail IS NOT NULL -- This is the problematic line
Order By T.Date_Created desc
</code>```

答:
If you are aware of the Index Considerations and you are sure about the problem point, then you can use this to improve it:

```<code>USE A1WAREHOUSE;
GO

CREATE NONCLUSTERED INDEX IX_MagentoCustomerEmailData_CustomerEmail
ON [dbo].[MagentoCustomerEmailData] (CustomerEmail ASC);

GO
</code>```

Totally, you need to add index on columns used in ORDER BY, WHERE, GROUP BY, ON etc sections. Before adding indexes be sure that you are aware of the consequences.

Read more about Index:

https://www.mssqltips.com/sqlservertutorial/9133/sql-server-nonclustered-indexes/

https://www.itprotoday.com/sql-server/indexing-dos-and-don-ts

ContentLicense: CC BY-SA 4.0

Body:
I have a table that I do some joins and operations on. This table has about 150,000 rows and if I select all and run it, it returns in about 10 seconds. If I create my query into its own table, and filter out all the rows where a certain field is null, now the query takes 10 minutes to run. Is it suppoused to be like this or is there any way to fix it? Here is the query.

SELECT *
FROM
(
    Select
     I.Date_Created
    ,I.Company_Code
    ,I.Division_Code
    ,I.Invoice_Number
    ,Sh.CUST_PO
    ,I.Total_Quantity
    ,ID.Total
    ,SH.Ship_City City
    ,CASE WHEN SH.Ship_Cntry <> 'US' THEN 'INT' ELSE SH.Ship_prov END State
    ,SH.Ship_Zip Zip
    ,SH.Ship_Cntry Country
    ,S.CustomerEmail
    from [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock)
    LEFT JOIN (SELECT
                    ID.Company_Code
                    ,ID.Division_Code
                    ,ID.Invoice_Number
                    ,SUM (ID.Price* ID.Quantity) Total
                    FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices_Detail ID (nolock)
                    GROUP BY ID.Company_Code, ID.Division_Code, ID.Invoice_Number) ID
            ON I.Company_Code = ID.Company_Code
            AND I.Division_Code = ID.Division_Code
            AND I.Invoice_Number = ID.Invoice_Number
    LEFT JOIN
        [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].SHIPHIST SH (nolock) ON I.Pickticket_Number = SH.Packslip
    LEFT JOIN
        [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].[MagentoCustomerEmailData] S on SH.CUST_PO = S.InvoiceNumber

    Where I.Company_Code ='09' AND I.Division_Code = '001'
    AND I.Customer_Number = 'ECOM2X'
    )T
    Where T.CustomerEmail IS NOT NULL -- This is the problematic line
Order By T.Date_Created desc

Body:
If you are aware of the Index Considerations and you are sure about the problem point, then you can use this to improve it:

USE A1WAREHOUSE;
GO

CREATE NONCLUSTERED INDEX IX_MagentoCustomerEmailData_CustomerEmail
ON [dbo].[MagentoCustomerEmailData] (CustomerEmail ASC);

GO

Totally, you need to add index on columns used in ORDER BY, WHERE, GROUP BY, ON etc sections. Before adding indexes be sure that you are aware of the consequences.

Read more about Index:

https://www.mssqltips.com/sqlservertutorial/9133/sql-server-nonclustered-indexes/

https://www.itprotoday.com/sql-server/indexing-dos-and-don-ts


问:
Cannot SSH into Amazon EC2 instance
I have spent almost 24hours trying to figure out what I'm doing wrong, but I can't figure this out. Starting to feel there is something wrong with my local setup.

I've made sure to chmod 400 erik-keypair.pem

I've stored erik-keypair.pem in my user .ssh folder, AND relocated the other id_rsa files just so they don't interfere (trying to remove any variables)

Ec2 instance security has ssh enabled

Here's the response

```<code>$ ssh -v -v -i erik-keypair.pem root@ec2-XX-XX-XX-XXX.compute-1.amazonaws.com
OpenSSH_5.2p1, OpenSSL 0.9.8l 5 Nov 2009
debug1: Reading configuration data /etc/ssh_config
debug2: ssh_connect: needpriv 0
debug1: Connecting to ec2-XX-XX-XX-XXX.compute-1.amazonaws.com [XX.XX.XX.XXX] port 22.
debug1: Connection established.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug2: key_type_from_name: unknown key type '-----END'
debug1: identity file erik-keypair.pem type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5ubuntu1
debug1: match: OpenSSH_5.1p1 Debian-5ubuntu1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.2
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 124/256
debug2: bits set: 502/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'ec2-XX-XX-XX-XXX.compute-1.amazonaws.com' is known and matches the RSA host key.
debug1: Found key in /Users/erik/.ssh/known_hosts:1
debug2: bits set: 523/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: erik-keypair.pem (0x0)
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: erik-keypair.pem
debug1: read PEM private key done: type RSA
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

Does anyone spot what I'm doing wrong?

答: If I'm not mistaken you should use ec2-user rather than root.</p>

ContentLicense: CC BY-SA 3.0

Title: Cannot SSH into Amazon EC2 instance

Body:
I have spent almost 24hours trying to figure out what I'm doing wrong, but I can't figure this out. Starting to feel there is something wrong with my local setup.

I've made sure to chmod 400 erik-keypair.pem

I've stored erik-keypair.pem in my user .ssh folder, AND relocated the other id_rsa files just so they don't interfere (trying to remove any variables)

Ec2 instance security has ssh enabled

Here's the response

$ ssh -v -v -i erik-keypair.pem root@ec2-XX-XX-XX-XXX.compute-1.amazonaws.com
OpenSSH_5.2p1, OpenSSL 0.9.8l 5 Nov 2009
debug1: Reading configuration data /etc/ssh_config
debug2: ssh_connect: needpriv 0
debug1: Connecting to ec2-XX-XX-XX-XXX.compute-1.amazonaws.com [XX.XX.XX.XXX] port 22.
debug1: Connection established.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug2: key_type_from_name: unknown key type '-----END'
debug1: identity file erik-keypair.pem type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5ubuntu1
debug1: match: OpenSSH_5.1p1 Debian-5ubuntu1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.2
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 124/256
debug2: bits set: 502/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'ec2-XX-XX-XX-XXX.compute-1.amazonaws.com' is known and matches the RSA host key.
debug1: Found key in /Users/erik/.ssh/known_hosts:1
debug2: bits set: 523/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: erik-keypair.pem (0x0)
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: erik-keypair.pem
debug1: read PEM private key done: type RSA
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

Does anyone spot what I'm doing wrong?


问:
Getting the first row from database refreshes the page continuously
I'm trying to get the first row from phpmyadmin. After trying to do it different ways, I thought I would ask. Right now, the problem is that it is refreshing the browser continuously.

i've tried to add a die, but I'm not very good at mysqli/php

```<code>    $sql2="SELECT * FROM stellingen WHERE REGIOID=1;";
    $records2 =  mysqli_query($con, $sql2);

    $row = mysqli_fetch_assoc($records2);

    while ($stellingen = mysqli_data_seek($records2, 0)){
        echo "<p>".$stellingen['Stelling']."</p>";
    }
</code>```

I expect the php to fetch the first data. In the context of a loop where the next data will nneed to come later in the page.

some more code

```<code>
<div class="stellingen">
    <div class="stelling-wrapper" id="btn1">
        <img src="images/button.svg" alt="Show more..." class="btn" id="bton">
        <p type="button" class="stelling">
<?php
    $sql2="SELECT * FROM stellingen WHERE REGIOID=1;";
    $records2 =  mysqli_query($con, $sql2);

    $row = mysqli_fetch_assoc($records2);

    while ($stellingen = mysqli_data_seek($records2, 0)){
        echo "<p>".$stellingen['Stelling']."</p>";
    }

    /*
    if ($recordscheck2 > 0){
        while ($stellingen = mysqli_fetch_assoc($records2)){
            echo "<p>".$stellingen['Stelling']."</p>";
        }
    }*/
?>
</div>
<div id="p1">
    <table id="tabel" border=1px class="data">
    <tr>
        <th>Title</th>
        <th>Source</th>
        <th>Weight</th>
        <th>Date</th>
    </tr>

<?php
$sql1="SELECT * FROM stelling WHERE stelling_iD=1;";
$records1 =  mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records1);

if ($recordscheck > 0){
    while ($stelling = mysqli_fetch_assoc($records1)){
        echo "<tr>";
            echo "<td>".$stelling['Title']."</td>";
            echo "<td>".$stelling['Source']."</td>";
            echo "<td>".$stelling['Wheight']."</td>";
            echo "<td>".$stelling['Timer']."</td>";
        echo "</tr>";
    }
}
?>
    </table>
</div>
</code>```

答:
Okey, so your using mysqli_data_seek() in a while() loop, which is wrong...

```<code><?php

if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {

    mysqli_data_seek($result, 0);

    $row = mysqli_fetch_assoc($result);

    echo "<p>{$row["Stelling"]}</p>";

}

?>
</code>```

Should work for you.

[Edit] I corrected my variable names.

Body:
I'm trying to get the first row from phpmyadmin. After trying to do it different ways, I thought I would ask. Right now, the problem is that it is refreshing the browser continuously.

i've tried to add a die, but I'm not very good at mysqli/php

    $sql2="SELECT * FROM stellingen WHERE REGIOID=1;";
    $records2 =  mysqli_query($con, $sql2);

    $row = mysqli_fetch_assoc($records2);

    while ($stellingen = mysqli_data_seek($records2, 0)){
        echo "
".$stellingen['Stelling']."
";
    }

I expect the php to fetch the first data. In the context of a loop where the next data will nneed to come later in the page.

some more code

<?php
    $sql2="SELECT * FROM stellingen WHERE REGIOID=1;";
    $records2 =  mysqli_query($con, $sql2);

    $row = mysqli_fetch_assoc($records2);

    while ($stellingen = mysqli_data_seek($records2, 0)){
        echo "
".$stellingen['Stelling']."
";
    }

    /*
    if ($recordscheck2 > 0){
        while ($stellingen = mysqli_fetch_assoc($records2)){
            echo "
".$stellingen['Stelling']."
";
        }
    }*/
?>

        Title
        Source
        Weight
        Date

<?php
$sql1="SELECT * FROM stelling WHERE stelling_iD=1;";
$records1 =  mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records1);

if ($recordscheck > 0){
    while ($stelling = mysqli_fetch_assoc($records1)){
        echo "
";
            echo "".$stelling['Title']."	";
            echo "".$stelling['Source']."	";
            echo "".$stelling['Wheight']."	";
            echo "".$stelling['Timer']."	";
        echo "
";
    }
}
?>

Body:
Okey, so your using mysqli_data_seek() in a while() loop, which is wrong...

<?php

if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {

    mysqli_data_seek($result, 0);

    $row = mysqli_fetch_assoc($result);

    echo "<p>{$row["Stelling"]}</p>";

}

?>

Should work for you.

[Edit] I corrected my variable names.


问:
Obtaining data from the form with GET data. Django
How can I get data from the form using the GET method?

For example, I have this form:

```<code>class LoansSearchForm(forms.Form):
    balance = forms.IntegerField(label='', required=False)
</code>```

In my view display in the form template this way:

```<code>def search_results(request):
    form = LoansSearchForm(request.GET)
    cd = form.cleaned_data
    word = cd['balance']

    context = {'form': form,
               'test': word,}
    return render(request, 'search_results.html', context)
</code>```

But i still a error:

```<code>'LoansSearchForm' object has no attribute 'cleaned_data'
</code>```

When trying to get them this way:

```<code>word = form['balance']
</code>```

I receive a field with completed data. How to get the data from my the form correctly?

Is my form written correctly? Should I use something like that?
(sorry if my question is trivial, but I found very little information about GET forms)

```<code>if request.method == 'GET':
    form = LoansSearchForm(request.GET)
    if form.is_valid():
        print('Hello World')
else:
    form = LoansSearchForm()
</code>```

答:
```<code>def search_results(request):
    form = LoansSearchForm(request.GET)
    cd = form.cleaned_data                       # here <------
    word = cd['balance']

    context = {'form': form,
               'test': word,}
    return render(request, 'search_results.html', context)
</code>```

The problem with your code is that forms are not filled on initialization but when you call form.is_valid, if the form is indeed valid, then it populates cleaned_data

You can read more about the related documentation.

Body:
How can I get data from the form using the GET method?

For example, I have this form:

class LoansSearchForm(forms.Form):
    balance = forms.IntegerField(label='', required=False)

In my view display in the form template this way:

def search_results(request):
    form = LoansSearchForm(request.GET)
    cd = form.cleaned_data
    word = cd['balance']

    context = {'form': form,
               'test': word,}
    return render(request, 'search_results.html', context)

But i still a error:

'LoansSearchForm' object has no attribute 'cleaned_data'

When trying to get them this way:

word = form['balance']

I receive a field with completed data. How to get the data from my the form correctly?

Is my form written correctly? Should I use something like that?
(sorry if my question is trivial, but I found very little information about GET forms)

if request.method == 'GET':
    form = LoansSearchForm(request.GET)
    if form.is_valid():
        print('Hello World')
else:
    form = LoansSearchForm()

Body:
def search_results(request):
    form = LoansSearchForm(request.GET)
    cd = form.cleaned_data                       # here <------
    word = cd['balance']

    context = {'form': form,
               'test': word,}
    return render(request, 'search_results.html', context)

The problem with your code is that forms are not filled on initialization but when you call form.is_valid, if the form is indeed valid, then it populates cleaned_data

You can read more about the related documentation.


问:
Field not being injected with Dagger
In the following code, the field serviceUtil is not being injected by Dagger:

AppController.kt

```<code>class App : Application() {
    @Inject
    lateinit var serviceUtil: ServiceUtil

    init {
        DaggerAppComponent
            .builder()
            .build()
            .inject(this)
    }

    override fun onCreate() {
        super.onCreate()
        context = this
    }

    fun startService() {
        serviceUtil.startService()
    }

    companion object {
        lateinit var context: App
    }
}
</code>```

AppComponent.kt

```<code>@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: Application)
}
</code>```

ServiceUtilModule.kt

```<code>@Module
class ServiceUtilModule {
    @Provides
    fun provideServiceUtil() : ServiceUtil {
        return ServiceUtil()
    }
}
</code>```

From my main activity I call:

```<code>App.context.startService()
</code>```

答:
You mistyped here

```<code>@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: Application)
}
</code>```

You should pass you App class as argument, not the basic one.

```<code>@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: App)
}
</code>```

Title: Field not being injected with Dagger

Body:
In the following code, the field serviceUtil is not being injected by Dagger:

AppController.kt

class App : Application() {
    @Inject
    lateinit var serviceUtil: ServiceUtil

    init {
        DaggerAppComponent
            .builder()
            .build()
            .inject(this)
    }

    override fun onCreate() {
        super.onCreate()
        context = this
    }

    fun startService() {
        serviceUtil.startService()
    }

    companion object {
        lateinit var context: App
    }
}

AppComponent.kt

@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: Application)
}

ServiceUtilModule.kt

@Module
class ServiceUtilModule {
    @Provides
    fun provideServiceUtil() : ServiceUtil {
        return ServiceUtil()
    }
}

From my main activity I call:

App.context.startService()

Body:
You mistyped here

@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: Application)
}

You should pass you App class as argument, not the basic one.

@Singleton
@Component(modules = [(ServiceUtilModule::class)])
interface AppComponent {
    fun inject(app: App)
}


问:
How to deserialize JSON to IList<KeyValuePair<string, object>> with whitespaces in key?
I have a big problem with deserializing my JSON to an object. It should be deserialized to IList<KeyValuePair<string, object>> the problem is that the keys have white spaces.

```<code>"spec": {
         "SOMETHING WITH SPACES" : "10"
         etc.
         ...
}
</code>```

public class SomeObject
{
...
public IList<KeyValuePair<string, object>> spec{ get; set; }
...
}
```

<p>Deserializing code:</p>

<pre class="lang-cs prettyprint-override"><code>var sr = new ServiceStack.Text.JsonSerializer<SomeObject>();
var esResult = sr.DeserializeFromString(responseJson);
</code>```

responseJson is a GET from ElasticSearch.

What I get to my field it is null.
If I have key without whitespaces it's deserializing normally and I'm getting my IList<KeyValuePair<string, object>>

答:
You can't use IList or List here, because your source JSON has no [ ] in it, which is a requirement if you want to parse into such a collection. In other words, without [ ] you can't parse into a collection, at least not without going through lots of hoops.

Instead you need to use a Dictionary as was suggested already in comments.

Note: I used Newtonsoft JsonConvert because you didn't state what your parser is, but that should make little or no difference to my arguments.

Working code:

```<code>var json = "{ \"spec\": { \"SOMETHING WITH SPACES\" : \"10\" } }";
var someObj = JsonConvert.DeserializeObject<SomeObject>(json);

public class SomeObject
{
    public Dictionary<string, object> spec{ get; set; }
}
</code>```

After that, you can cast the spec property to an IEnumerable and loop through whatever was found:

```<code>foreach (var pair in someObj.spec as IEnumerable<KeyValuePair<string, object>>)
{
    Console.WriteLine(pair.Key + " -> " + pair.Value);
}
</code>```

Or even convert it to a List:

```<code>var list = someObj.spec.ToList();
foreach (var pair in list)
{
    Console.WriteLine(pair.Key + " -> " + pair.Value);
}
</code>```

.NET Fiddle: https://dotnetfiddle.net/15l2R3

Body:
I have a big problem with deserializing my JSON to an object. It should be deserialized to IList<KeyValuePair<string, object>> the problem is that the keys have white spaces.

"spec": {
         "SOMETHING WITH SPACES" : "10"
         etc.
         ...
}

public class SomeObject
{
...
public IList<KeyValuePair<string, object>> spec{ get; set; }
...
}

Deserializing code:

var sr = new ServiceStack.Text.JsonSerializer<SomeObject>();
var esResult = sr.DeserializeFromString(responseJson);

responseJson is a GET from ElasticSearch.

What I get to my field it is null.
If I have key without whitespaces it's deserializing normally and I'm getting my IList<KeyValuePair<string, object>>

Body:
You can't use IList or List here, because your source JSON has no [ ] in it, which is a requirement if you want to parse into such a collection. In other words, without [ ] you can't parse into a collection, at least not without going through lots of hoops.

Instead you need to use a Dictionary as was suggested already in comments.

Note: I used Newtonsoft JsonConvert because you didn't state what your parser is, but that should make little or no difference to my arguments.

Working code:

var json = "{ \"spec\": { \"SOMETHING WITH SPACES\" : \"10\" } }";
var someObj = JsonConvert.DeserializeObject<SomeObject>(json);

public class SomeObject
{
    public Dictionary<string, object> spec{ get; set; }
}

After that, you can cast the spec property to an IEnumerable and loop through whatever was found:

foreach (var pair in someObj.spec as IEnumerable<KeyValuePair<string, object>>)
{
    Console.WriteLine(pair.Key + " -> " + pair.Value);
}

Or even convert it to a List:

var list = someObj.spec.ToList();
foreach (var pair in list)
{
    Console.WriteLine(pair.Key + " -> " + pair.Value);
}

.NET Fiddle: https://dotnetfiddle.net/15l2R3


问:
parse parenthesized numbers to negative numbers
How can i Parse parenthesized numbers in a list of strings  to negative numbers (or strings with negative sign).

example

```<code>input
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']

output
['abcd',-1234,'Level-2 (2):','-31%', 'others','-3102.2%']
</code>```

strings only with numbers inside parenthesis or numbers with comma/dot inside parenthesis followed by a percentage(%) sign, should be parsed . other strings such as 'Level-2 (2):' should not be parsed.

I have tried

```<code>translator = str.maketrans(dict.fromkeys('(),'))
['-'+(x.translate(translator)) for x in list1]
</code>```

but the output is (every element has a - appended)

```<code>['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']
</code>```

答:
If you do not need to convert the value to int or float, re.match and str.translate should do the trick:

```<code>rx = re.compile('\([\d,.]+\)%?$')
tab = str.maketrans({i: None for i in '(),'})

output = ['-' + i.translate(tab) if rx.match(i) else i for i in list1]
</code>```

It gives:

```<code>['abcd', '-1234', 'Level-2 (2):', '-31%', 'others', '-3102.2%']
</code>```

Body:
How can i Parse parenthesized numbers in a list of strings  to negative numbers (or strings with negative sign).

example

input
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']

output
['abcd',-1234,'Level-2 (2):','-31%', 'others','-3102.2%']

strings only with numbers inside parenthesis or numbers with comma/dot inside parenthesis followed by a percentage(%) sign, should be parsed . other strings such as 'Level-2 (2):' should not be parsed.

I have tried

translator = str.maketrans(dict.fromkeys('(),'))
['-'+(x.translate(translator)) for x in list1]

but the output is (every element has a - appended)

['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']

Body:
If you do not need to convert the value to int or float, re.match and str.translate should do the trick:

rx = re.compile('\([\d,.]+\)%?$')
tab = str.maketrans({i: None for i in '(),'})

output = ['-' + i.translate(tab) if rx.match(i) else i for i in list1]

It gives:

['abcd', '-1234', 'Level-2 (2):', '-31%', 'others', '-3102.2%']


问:
How to create typings for asynchronous methods - method overloading
I was wondering how I would implement something like these (This was found in the @types from the node ws(WebSocket) module).

```<code>on(event: 'close', listener: (this: WebSocket, code: number, reason: string) => void): this;
on(event: 'error', listener: (this: WebSocket, err: Error) => void): this;
on(event: 'upgrade', listener: (this: WebSocket, request: http.IncomingMessage) => void): this;
on(event: 'message', listener: (this: WebSocket, data: WebSocket.Data) => void): this;
</code>```

I'm able to just implement the declarations but as soon as I try and add a function body I get Duplicate function implementation.ts(2393)

This is the code that I'm trying to utilize:

```<code>  on(event: 'message',  cb: (msg: string) => void)  { this.CB_onMsg = cb; }
  on(event: 'close',    cb: () => void)             { this.CB_onClose = cb; }
</code>```

答:
In typescript function declaration can be define multiple times as per our needs but the actual function implementation should be in single time. Else we'll get the error - Duplicate function implementation

Unlike other languages, in typescript return type also can be overload based on different input params type.

```<code>function on(event: "message", cb: (msg: string) => void): void;
function on(event: "close", cb: () => void): void;
function on(event: "message" | "close", cb: (msg?: string) => void): void {
    console.log(event);
    cb(event);
}

on("message", msg => console.log(msg));
on("close", () => console.log("no message"));
</code>```

But in reality below single line is more than sufficient

```<code>function on(event: "message" | "close", cb: (msg?: string) => void): void {
     //implementation
}
</code>```

Body:
I was wondering how I would implement something like these (This was found in the @types from the node ws(WebSocket) module).

on(event: 'close', listener: (this: WebSocket, code: number, reason: string) => void): this;
on(event: 'error', listener: (this: WebSocket, err: Error) => void): this;
on(event: 'upgrade', listener: (this: WebSocket, request: http.IncomingMessage) => void): this;
on(event: 'message', listener: (this: WebSocket, data: WebSocket.Data) => void): this;

I'm able to just implement the declarations but as soon as I try and add a function body I get Duplicate function implementation.ts(2393)

This is the code that I'm trying to utilize:

  on(event: 'message',  cb: (msg: string) => void)  { this.CB_onMsg = cb; }
  on(event: 'close',    cb: () => void)             { this.CB_onClose = cb; }

Body:
In typescript function declaration can be define multiple times as per our needs but the actual function implementation should be in single time. Else we'll get the error - Duplicate function implementation

Unlike other languages, in typescript return type also can be overload based on different input params type.

function on(event: "message", cb: (msg: string) => void): void;
function on(event: "close", cb: () => void): void;
function on(event: "message" | "close", cb: (msg?: string) => void): void {
    console.log(event);
    cb(event);
}

on("message", msg => console.log(msg));
on("close", () => console.log("no message"));

But in reality below single line is more than sufficient

function on(event: "message" | "close", cb: (msg?: string) => void): void {
     //implementation
}


问:
How to use thread lock when reading and writing a csv file in python?
I am working on refining dummy blockchain code, and want to make it impossible to read and write csv file if it's already being used. What should do i do?

I've put start(), join(), acquire(), release() etc all the places that i could thought, but i weren't work at all. Once gotten a message that "Permission denied" while i opened my file, however, it still gave me the information in the file. (All the other functions are working properly.)

```<code>def readBlockchain(blockchainFilePath, mode = 'internal'):

get_lock.acquire()
print("readBlockchain is called")
importedBlockchain = []

try:
    with open(blockchainFilePath, 'r',  newline='') as file:
        blockReader = csv.reader(file)
        for line in blockReader:
            block = Block(line[0], line[1], line[2], line[3], line[4], line[5],line[6])

        importedBlockchain.append(block)

    print("Pulling blockchain from csv...")
    get_lock.release()
    return importedBlockchain

except:
    if mode == 'internal':
        blockchain = generateGenesisBlock()
        importedBlockchain.append(blockchain)
        writeBlockchain(importedBlockchain)
        get_lock.release()
        return importedBlockchain

    else:
        get_lock.release()
        return None
</code>```

I expect it not to be read if i've opened the csv file, and to be read after i closed the file.

I'll look forward to your answers!
Thanks.

答:
Have a look at mutexes, that enables you to acquire and lock a ressource, and to unlock it once your job is finished.

Link : mutex

Body:
I am working on refining dummy blockchain code, and want to make it impossible to read and write csv file if it's already being used. What should do i do?

I've put start(), join(), acquire(), release() etc all the places that i could thought, but i weren't work at all. Once gotten a message that "Permission denied" while i opened my file, however, it still gave me the information in the file. (All the other functions are working properly.)

def readBlockchain(blockchainFilePath, mode = 'internal'):

get_lock.acquire()
print("readBlockchain is called")
importedBlockchain = []

try:
    with open(blockchainFilePath, 'r',  newline='') as file:
        blockReader = csv.reader(file)
        for line in blockReader:
            block = Block(line[0], line[1], line[2], line[3], line[4], line[5],line[6])

        importedBlockchain.append(block)

    print("Pulling blockchain from csv...")
    get_lock.release()
    return importedBlockchain

except:
    if mode == 'internal':
        blockchain = generateGenesisBlock()
        importedBlockchain.append(blockchain)
        writeBlockchain(importedBlockchain)
        get_lock.release()
        return importedBlockchain

    else:
        get_lock.release()
        return None

I expect it not to be read if i've opened the csv file, and to be read after i closed the file.

I'll look forward to your answers!
Thanks.


问:
How to shutdown and reboot the emulator through code in android?
I have implemented the code like:

```<code>Intent i = new Intent(Intent.ACTION_REBOOT);
sendBroadcast(i);
</code>```

it get the error(runtime):

```<code>java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.REBOOT from pid=*** and uid=***
</code>```

答:
I haven't tried this, and I think there are (and should be) a lot of restrictions on rebooting from code. But you can try to check the permission:

```<code><uses-permission android:name="android.permission.REBOOT" />
</code>```

and from here I read you might need some extra undocumented stuff:

```<code>Intent i = new Intent(Intent.ACTION_REBOOT);
i.putExtra("nowait", 1);
i.putExtra("interval", 1);
i.putExtra("window", 0);
sendBroadcast(i);
</code>```

Take special notice of the sentence in that link:

Not only is it not in the API docs,
  but because as you say you need to be
  signed with the platform cert, you can
  only use this if you are running on a
  device whose system software you have
  built yourself.

Body:
I have implemented the code like:

Intent i = new Intent(Intent.ACTION_REBOOT);
sendBroadcast(i);

it get the error(runtime):

java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.REBOOT from pid=*** and uid=***

Body:
I haven't tried this, and I think there are (and should be) a lot of restrictions on rebooting from code. But you can try to check the permission:

<uses-permission android:name="android.permission.REBOOT" />

and from here I read you might need some extra undocumented stuff:

Intent i = new Intent(Intent.ACTION_REBOOT);
i.putExtra("nowait", 1);
i.putExtra("interval", 1);
i.putExtra("window", 0);
sendBroadcast(i);

Take special notice of the sentence in that link:

Not only is it not in the API docs,
  but because as you say you need to be
  signed with the platform cert, you can
  only use this if you are running on a
  device whose system software you have
  built yourself.


问:
Trying to reduce the size of boxes on screen
I am trying to setup a style based on bootstrap3.

Basically I want to try and reduce the size of the input elements which I have done, getting a decent proportion of 'box' vs 'text'.
However if I use the same font-size in a select box with the same size then I get a situation where the text is masked along the bottom edge...

I think there is a tiny bit more margin at the top of the select box, but for the life of me I cant find where that is set in BootStrap to change it (if at all).

I think all I need to do is move the text in the 'select' element up by a couple of pixels and it will align with those bits of text in standard text boxes....

Can anyone point me in the right direct please?

答:
Found the associated CSS in the bootstrap, with a bit of trial and error....

Mainly in the 'form-control' section.

but now also using Bootstrap 4, with a couple of additional styles.


问:
Return "Error" if no match found by regex
I have a string:

```<code>link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo"
</code>```

And I have a function which return the domain name from that url or if it not found, returns '':

```<code>def get_domain(url):
    domain_regex = re.compile("\:\/\/(.*?)\/|$")
    return re.findall(domain_regex, str(url))[0].replace('www.', '')

get_domain(link)
</code>```

returned result:

```<code>this_is_my_perfect_url.com
</code>```

|$ returns '' if regex matches nothing.

Is there a way to implement the default value Error inside regex so I do not have to do any check inside the fuction?

So if link = "there_is_no_domain_in_here" then the fuction returns Error instead of ''.

答:
why not use urlparse to get domain?

# env python 2
# import urlparse
# python 3
from urllib.parse import urlparse

def get_domain(url):
    parsed_uri = urlparse(url)
    domain = parsed_uri.netloc
    return domain or "ERROR"

url = 'there_is_no_domain_in_here'
print(get_domain(url))
```

Body:
I have a string:

link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo"

And I have a function which return the domain name from that url or if it not found, returns '':

def get_domain(url):
    domain_regex = re.compile("\:\/\/(.*?)\/|$")
    return re.findall(domain_regex, str(url))[0].replace('www.', '')

get_domain(link)

returned result:

this_is_my_perfect_url.com

|$ returns '' if regex matches nothing.

Is there a way to implement the default value Error inside regex so I do not have to do any check inside the fuction?

So if link = "there_is_no_domain_in_here" then the fuction returns Error instead of ''.


问:
How to make first column of html table fixed in responsive design
I need html  table  first column fixed in responsive.I have select box in my php page. I have used ajax to display data from database in html table. in responsive design  after selecting value in select box first td value is not fixed and other td values not scrolling.I have used jquery script to make html table first  column        fixed.With out selecting value in select box it is working in responsive .</p>

答:
you could do this with a single query  </p>

```<code>select *
from  admin
INNER JOIN table2 ON admin.username = table2.t2_col_username
WHERE admin.batchname= ?
</code>```

<p>and you should avoid the use of php var  in SQL (you are at risk for sqlinjection  )
for this take a look at prepared statement and binding param </p>

Body:
you could do this with a single query

select *
from  admin
INNER JOIN table2 ON admin.username = table2.t2_col_username
WHERE admin.batchname= ?

and you should avoid the use of php var  in SQL (you are at risk for sqlinjection  )
for this take a look at prepared statement and binding param


答:
Recommended: run form.is_valid() and then you do form.cleaned_data

```<code>def search_results(request):
    form = LoansSearchForm(request.GET)
    if form.is_valid():
        cd = form.cleaned_data
        word = cd['balance']
    else:
        word = None

    context = {'form': form,
               'test': word,}
    return render(request, 'search_results.html', context)
</code>```

Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it anywhere.

more on cleaned data - documentation

Title: Obtaining data from the form with GET data. Django

Body:
Recommended: run form.is_valid() and then you do form.cleaned_data

def search_results(request):
    form = LoansSearchForm(request.GET)
    if form.is_valid():
        cd = form.cleaned_data
        word = cd['balance']
    else:
        word = None

    context = {'form': form,
               'test': word,}
    return render(request, 'search_results.html', context)

Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it anywhere.

more on cleaned data - documentation


问:
Background Color of Material UI Snackbar not being overridden
I'm doing an ErrorHandler in React.JS that pops up a Material UI Snackbar whenever there is an error caught by the ErrorHandler. The problem is that I want the backgroundColor style attribute red, but it does not change to a red color.

Could anyone guide me on how can I achieve the color change?

I have tried:

Using the className attribute on the Snackbar component.

Using the ContentProps prop.

Using CSS overriding styles with classes.

The ErrorHandler.jsx:

```<code>import React from "react";
import ErrorIcon from '@material-ui/icons/Error';
import CloseIcon from '@material-ui/icons/Close';
import Snackbar from '@material-ui/core/Snackbar';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import IconButton from '@material-ui/core/IconButton';
import { withStyles } from '@material-ui/core/styles';
import styles from "./errorHandlerStyles";
import PropTypes from "prop-types";

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hasError: false,
            error: ""
        };

        this.handleClose = this.handleClose.bind(this);
    }

    componentDidCatch(error) {
        this.setState({
            hasError: true,
            error: error
        });
    }

    handleClose() { this.setState({ hasError: false }); }

    render() {
        const { classes } = this.props;

        if (this.state.hasError) {
            return (
                <Snackbar
                    classes={{
                        root: classes.root
                    }}
                    anchorOrigin={{
                        vertical: "bottom",
                        horizontal: "left"
                    }}
                    autoHideDuration={5000}
                    onClose={this.handleClose}
                    open={this.state.hasError}
                >
                    <SnackbarContent
                        message={
                            <span className={classes.message}>
                                <ErrorIcon className={classes.icon} />
                                {this.state.error.toString()}
                            </span>
                        }
                        action={
                        <IconButton key="close" onClick={this.handleClose} className={classes.content}>
                            <CloseIcon />
                        </IconButton>
                    }
                    >
                    </SnackbarContent>
                </Snackbar>
            );
        }
        return this.props.children;
    }
}

ErrorBoundary.propTypes = {
    classes: PropTypes.object.isRequired
}

export default withStyles(styles)(ErrorBoundary);
</code>```

The errorHandlerStyles.js:

```<code>const styles = theme => ({
    message: {
        display: 'flex',
        alignItems: 'center',
        fontSize: 16
    },
    icon: {
        fontSize: 20,
        opacity: 0.9,
        marginRight: theme.spacing.unit * 1,
    },
    content: {
        margin: theme.spacing.unit * 1,
    },
    root: {
        backgroundColor: theme.palette.error.light
    }
});

export default styles;
</code>```

答: Try using className={classes.root} on the SnackbarContent component.

Body:
I'm doing an ErrorHandler in React.JS that pops up a Material UI Snackbar whenever there is an error caught by the ErrorHandler. The problem is that I want the backgroundColor style attribute red, but it does not change to a red color.

Could anyone guide me on how can I achieve the color change?

I have tried:

Using the className attribute on the Snackbar component.

Using the ContentProps prop.

Using CSS overriding styles with classes.

The ErrorHandler.jsx:

import React from "react";
import ErrorIcon from '@material-ui/icons/Error';
import CloseIcon from '@material-ui/icons/Close';
import Snackbar from '@material-ui/core/Snackbar';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import IconButton from '@material-ui/core/IconButton';
import { withStyles } from '@material-ui/core/styles';
import styles from "./errorHandlerStyles";
import PropTypes from "prop-types";

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hasError: false,
            error: ""
        };

        this.handleClose = this.handleClose.bind(this);
    }

    componentDidCatch(error) {
        this.setState({
            hasError: true,
            error: error
        });
    }

    handleClose() { this.setState({ hasError: false }); }

    render() {
        const { classes } = this.props;

        if (this.state.hasError) {
            return (
                <Snackbar
                    classes={{
                        root: classes.root
                    }}
                    anchorOrigin={{
                        vertical: "bottom",
                        horizontal: "left"
                    }}
                    autoHideDuration={5000}
                    onClose={this.handleClose}
                    open={this.state.hasError}
                >
                    <SnackbarContent
                        message={

                                <ErrorIcon className={classes.icon} />
                                {this.state.error.toString()}

                        }
                        action={
                        <IconButton key="close" onClick={this.handleClose} className={classes.content}>
                            <CloseIcon />
                        </IconButton>
                    }
                    >
                    </SnackbarContent>
                </Snackbar>
            );
        }
        return this.props.children;
    }
}

ErrorBoundary.propTypes = {
    classes: PropTypes.object.isRequired
}

export default withStyles(styles)(ErrorBoundary);

The errorHandlerStyles.js:

const styles = theme => ({
    message: {
        display: 'flex',
        alignItems: 'center',
        fontSize: 16
    },
    icon: {
        fontSize: 20,
        opacity: 0.9,
        marginRight: theme.spacing.unit * 1,
    },
    content: {
        margin: theme.spacing.unit * 1,
    },
    root: {
        backgroundColor: theme.palette.error.light
    }
});

export default styles;


问:
Attaching databases results in error "The server principal is not able to access the database"
I have 2 databases that i want to attach them SQL Server Express.

When I try it with another user account, i recieve login failed error.

This code sets the owner of the databases to current user

```<code>use [DatabaseName]
create user[DomainName\\UserName] for login [DomainName\\UserName]
exec sp_addroleMember 'db_owner','DomainName\\UserName'
</code>```

This works for first database but for second one i receive this error:

the server principal is not able to access the database

How can this be done programmatically?

答:
You should change database owner

```<code>exec sp_changedbowner 'yourlogin',NULL
</code>```

and then

```<code>ALTER DATABASE [Your_DB] SET TRUSTWORTHY ON
</code>```

Body:
I have 2 databases that i want to attach them SQL Server Express.

When I try it with another user account, i recieve login failed error.

This code sets the owner of the databases to current user

use [DatabaseName]
create user[DomainName\\UserName] for login [DomainName\\UserName]
exec sp_addroleMember 'db_owner','DomainName\\UserName'

This works for first database but for second one i receive this error:

the server principal is not able to access the database

How can this be done programmatically?

Body:
You should change database owner

exec sp_changedbowner 'yourlogin',NULL

and then

ALTER DATABASE [Your_DB] SET TRUSTWORTHY ON


问:
How to get microphones and cameras devices?
I'm trying to get a list with all devices connected of my iphone (external and internal cameras and microphones). How can do that?

I'm using AVCaptureDevices.devices() but this method only return the default devices (front and back camera and build-in mic). Connecting  a bluetooth mic, I have the same return.

How can I get a list of available devices connected on my phone?

答:
I found a workaround. Using AVAudioSession.sharedInstance().availableInputs I can get all audio input devices and set it with AVAudioSession.sharedInstance().setPreferredInput()

Example:

```<code>let audioSession: AVAudioSession = AVAudioSession.sharedInstance()

    do {
        try audioSession.setCategory(AVAudioSession.Category.playAndRecord, options: .allowBluetooth)
        try audioSession.setActive(true)
    } catch  {
        print("Error messing with audio session: \(error)")
    }

// All audio devices, bluetooth included
let audioInputDevices: [AVAudioSessionPortDescription] = audioSession.availableInputs!

</code>```

Body:
I found a workaround. Using AVAudioSession.sharedInstance().availableInputs I can get all audio input devices and set it with AVAudioSession.sharedInstance().setPreferredInput()

Example:

let audioSession: AVAudioSession = AVAudioSession.sharedInstance()

    do {
        try audioSession.setCategory(AVAudioSession.Category.playAndRecord, options: .allowBluetooth)
        try audioSession.setActive(true)
    } catch  {
        print("Error messing with audio session: \(error)")
    }

// All audio devices, bluetooth included
let audioInputDevices: [AVAudioSessionPortDescription] = audioSession.availableInputs!


问:
How to merge 2 CSV files based on filename
I have 2 CSV files:

```<code>1234ABC.stats.csv
name,value1,value1

1234ABC.csv
value2,value2,value2
</code>```

Both of these files have only 1 line in them.

They both have no header, and are in the same directory with no other file types.

How can I add the content from the second file onto the end of the line from the first?

desired output:

```<code>name,value1,value1,value2,value2,value2
</code>```

答:
(Edit fixed a bug — ; $_ was missing)  Off-hand I'd do

```<code>perl -e  'print join q(,), map { chomp; $_ } <>; print qq(\n)'  *.csv
</code>```

<> is a list of all the lines in all the input files.  chomp removes the newlines, then join adds the commas.

You may need to specify the files manually rather than just using *.csv if the order of the results is different than you want.

Or you could do it by hand in a text editor :D .

Body:
I have 2 CSV files:

1234ABC.stats.csv
name,value1,value1

1234ABC.csv
value2,value2,value2

Both of these files have only 1 line in them.

They both have no header, and are in the same directory with no other file types.

How can I add the content from the second file onto the end of the line from the first?

desired output:

name,value1,value1,value2,value2,value2

Body:
(Edit fixed a bug — ; $_ was missing)  Off-hand I'd do

perl -e  'print join q(,), map { chomp; $_ } <>; print qq(\n)'  *.csv

<> is a list of all the lines in all the input files.  chomp removes the newlines, then join adds the commas.

You may need to specify the files manually rather than just using *.csv if the order of the results is different than you want.

Or you could do it by hand in a text editor :D .


问:
Iterate over an Array and push elements to an Object
I have an array object which looks like this

```<code>identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
country: "US",
province: "Illinois"
</code>```

I want my data model to look like this

```<code>identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
issuedEntity:{
country: "US",
province: "Illinois"
}
</code>```

Initially I assign array of Objects to a variable

```<code>identification: this.model['identificationArray'].
</code>```

IdentificationArray is an array of Object and contains all the details but in a simple json format. I want to be able to somehow manipulate it and insert data by creating an issuedEntity object and then country and province details inside that object.

For that I tried iterating over the array but I am getting error.Can someone help me figure out how to do it.

```<code>myModel.identification.forEach(identificationObj => {
issuedEntity: {
province = identificationObj.issuedEntity.province,
country = identificationObj.issuedEntity.country,
}
}
);
</code>```

答:
You can use array map function and return an object with required keys

let data = [{
  identificationType: "DL",
  identificationDesc: "Test",
  referenceNumber: "123456789",
  country: "US",
  province: "Illinois"
}]

let newData = data.map(function(item) {
  return {
    identificationType: item.identificationType,
    identificationDesc: item.identificationDesc,
    referenceNumber: item.referenceNumber,
    issuedEntity: {
      country: item.country,
      province: item.province
    }

  }
});

console.log(newData)```

Body:
I have an array object which looks like this

identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
country: "US",
province: "Illinois"

I want my data model to look like this

identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
issuedEntity:{
country: "US",
province: "Illinois"
}

Initially I assign array of Objects to a variable

identification: this.model['identificationArray'].

IdentificationArray is an array of Object and contains all the details but in a simple json format. I want to be able to somehow manipulate it and insert data by creating an issuedEntity object and then country and province details inside that object.

For that I tried iterating over the array but I am getting error.Can someone help me figure out how to do it.

myModel.identification.forEach(identificationObj => {
issuedEntity: {
province = identificationObj.issuedEntity.province,
country = identificationObj.issuedEntity.country,
}
}
);


问:
What are the often misunderstood concepts in C++?
What are the often misunderstood concepts in c++?</p>

答: C structs VS C++ structs is often misunderstood.

OwnerDisplayName: rajKumar

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: starblue

OwnerDisplayName: turbovince


问:
python re.sub with an integer operation
I currently have a pattern substitution that does the following:

```<code>x = re.sub('(\d+)','\g<1>','100')
=> x = 100
</code>```

I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is there a way to do this so that => x = 10

Thanks,
Richard

答:
re.sub can take function as a second parameter.</p>

```<code>import re

def func(r):
    return str(int(r.group(0)) / 10)

x = re.sub("\d+", func, "100")
print x
</code>```

Title: python re.sub with an integer operation

Body:
I currently have a pattern substitution that does the following:

x = re.sub('(\d+)','\g<1>','100')
=> x = 100

I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is there a way to do this so that => x = 10

Thanks,
Richard

Body:
re.sub can take function as a second parameter.

import re

def func(r):
    return str(int(r.group(0)) / 10)

x = re.sub("\d+", func, "100")
print x


Title: Txt to XML Python parser

Body:
I tried to parse a .txt file that looks like this:

-------------------------------------------------------------------------------
Compare Results
Compare Directory 1 : /data/Run_288/bitmaps
Compare Directory 2 : /data/Run_301/bitmaps
 -------------------------------------------------------------------------------
 idx, Filename                                                         ,   Exact,    F3x3,    F5x5,    F7x7, Threshold,    P/F
-------------------------------------------------------------------------------
   1, ASCII_APPE_600X450_150_colorManBasic2.blackGrayReproductionImage_0_2p_color_test_four_object.pdf_20190522005734_00001.tif,       0,       0,       0,       0,       0,    PASS
   2, ASCII_APPE_600X450_150_colorManBasic2.blackGrayReproductionImage_0_2p_color_test_four_object.pdf_20190522005734_00002.tif,       0,       0,       0,       0,       0,    PASS
-------------------------------------------------------------------------------
Bitmap Compare FAILURE !!! Threshold Exceeded : Threshold Values : Exact = 0 : Fuzzy 3x3 = 200 : Fuzzy 5x5 = 100 : Fuzzy 7x7 = 50 : Threshold 7x7 = 0
3, MIME_Test3_Job_setup__600X600_50_default_default_PPST56_003.mjm_20190521213826_00001.tif,    2083,    1180,     650,     262,      52,    FAIL

-------------------------------------------------------------------------------

I need to obtain an xml with this format:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Suite date="2019-05-27T10:47:03" compareDir1="/data/Run_288/bitmaps" compareDir2="/data/Run_301/bitmaps">
<Test name="ASCII_APPE_600X450_150_colorManBasic2.blackGrayReproductionImage_0_2p_color_test_four_object.pdf_20190522005734_00001.tif" result="pass">
</Test>
<Test name="ASCII_APPE_600X450_150_colorManBasic2.blackGrayReproductionImage_0_2p_color_test_four_object.pdf_20190522005734_00002.tif" result="pass">
</Test>
<Test name="MIME_Test3_Job_setup__600X600_50_default_default_PPST56_003.mjm_20190521213826_00001.tif" result="crash">
</Test>
</Suite>

This is the code that should do the work.The problem is that is not working and with my little python knowledge I don't know why.Can somebody help me please with this?!
Thank you!

import xml.etree.ElementTree as ET
root = ET.Element('Suite')
with open('file3.txt') as f:
    lines = f.read().splitlines()
    print(lines)
#add first subelement
celldata = ET.SubElement(root, 'Test')
import itertools as it
#for every line in input file
#group consecutive dedup to one
for line in it.groupby(lines):
    line=line[0]
    #if its a break of subelements  - that is an empty space
    if not line:
        #add the next subelement and get it as celldata
        celldata = ET.SubElement(root, 'test')
    else:
        #otherwise, split with : to get the tag name
        tag = line.split(",")
        #format tag name
        el=ET.SubElement(celldata,tag[1])
        print(tag[1])
        print(tag[7])
        tag=' '.join(tag[1]).strip()
      if 'PASS' in line:
           tag = line.split(",")[-1].strip()
      elif 'FAILURE' in line:
           splist =  filter(None,line.split(" "))
           tag = splist[splist.index(',')+1]

        el.text = tag

#prettify xml
import xml.dom.minidom as minidom
formatedXML = minidom.parseString(
                          ET.tostring(
                                      root)).toprettyxml(indent=" ",encoding='utf-8').strip()
# Display for debugging
print formatedXML

#write the formatedXML to file.
with open("results.xml","w+") as f:
    f.write(formatedXML)

Body:
For this I would use regular expressions. My take:

data = '''-------------------------------------------------------------------------------
Compare Results
Compare Directory 1 : /data/Run_288/bitmaps
Compare Directory 2 : /data/Run_301/bitmaps
 -------------------------------------------------------------------------------
 idx, Filename                                                         ,   Exact,    F3x3,    F5x5,    F7x7, Threshold,    P/F
-------------------------------------------------------------------------------
   1, ASCII_APPE_600X450_150_colorManBasic2.blackGrayReproductionImage_0_2p_color_test_four_object.pdf_20190522005734_00001.tif,       0,       0,       0,       0,       0,    PASS
   2, ASCII_APPE_600X450_150_colorManBasic2.blackGrayReproductionImage_0_2p_color_test_four_object.pdf_20190522005734_00002.tif,       0,       0,       0,       0,       0,    PASS
-------------------------------------------------------------------------------
Bitmap Compare FAILURE !!! Threshold Exceeded : Threshold Values : Exact = 0 : Fuzzy 3x3 = 200 : Fuzzy 5x5 = 100 : Fuzzy 7x7 = 50 : Threshold 7x7 = 0
3, MIME_Test3_Job_setup__600X600_50_default_default_PPST56_003.mjm_20190521213826_00001.tif,    2083,    1180,     650,     262,      52,    FAIL

-------------------------------------------------------------------------------'''

import re

dirs = []
for d in re.findall('Compare Directory\s+(\d+)\s*:\s*(.*?)$', data, flags=re.DOTALL|re.MULTILINE):
    dirs += [d]

passes = []
fails = []

for line in data.split('\n'):
    for p in re.findall('(\d+,\s+(.*?),.*?PASS)$', line):
        passes += [p]
    for f in re.findall('(\d+,\s+(.*?),.*?FAIL)$', line):
        fails += [f]

s = f'''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Suite date="2019-05-27T10:47:03" compareDir1="{dirs[0][1]}" compareDir2="{dirs[1][1]}">
'''

for p in passes:
    s += f'''   <Test name="{p[1]}" result="pass">
    </Test>
'''

for fail in fails:
    s += f'''   <Test name="{fail[1]}" result="crash">
    </Test>
'''

s += '''</Suite>'''

print(s)

Prints:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Suite date="2019-05-27T10:47:03" compareDir1="/data/Run_288/bitmaps" compareDir2="/data/Run_301/bitmaps">
    <Test name="ASCII_APPE_600X450_150_colorManBasic2.blackGrayReproductionImage_0_2p_color_test_four_object.pdf_20190522005734_00001.tif" result="pass">
    </Test>
    <Test name="ASCII_APPE_600X450_150_colorManBasic2.blackGrayReproductionImage_0_2p_color_test_four_object.pdf_20190522005734_00002.tif" result="pass">
    </Test>
    <Test name="MIME_Test3_Job_setup__600X600_50_default_default_PPST56_003.mjm_20190521213826_00001.tif" result="crash">
    </Test>
</Suite>


问:
jQuery and AJAX Loading
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.

My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.

newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.

The code for the AJAX that loads the story and media is:

```<code>$.ajax({
  url: './scripts/storyLoader.php?storyid='+storyId,
  success: function(result){
    $('#storycontainer').hide();
    $('#loading').remove();
    $('#storycontainer').hide(0).html(result).fadeIn(1000);
    }
});
$.ajax({
  url: './scripts/mediaLoader.php?storyid='+storyId,
  success: function(result){
    $('.martefact').hide();
    $('#loading').remove();
    $('.martefact').html(result).slideDown(1000);
    }
});
</code>```

Basically, I only want the media div to slide down once the video or image has finished loading.

Thanks

答:
You need to use an 'on complete' callback function on the first animation.

Have a look jQuery api documentation for .fadeIn()

It should look something like:

```
$('#book').fadeIn('slow', function() {
    // Code to run after animation completed...
});
```

Title: jQuery and AJAX Loading

Body:
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.

My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.

newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.

The code for the AJAX that loads the story and media is:

$.ajax({
  url: './scripts/storyLoader.php?storyid='+storyId,
  success: function(result){
    $('#storycontainer').hide();
    $('#loading').remove();
    $('#storycontainer').hide(0).html(result).fadeIn(1000);
    }
});
$.ajax({
  url: './scripts/mediaLoader.php?storyid='+storyId,
  success: function(result){
    $('.martefact').hide();
    $('#loading').remove();
    $('.martefact').html(result).slideDown(1000);
    }
});

Basically, I only want the media div to slide down once the video or image has finished loading.

Thanks

Body:
You need to use an 'on complete' callback function on the first animation.

Have a look jQuery api documentation for .fadeIn()

It should look something like:

$('#book').fadeIn('slow', function() {
    // Code to run after animation completed...
});


问:
Loading indication with a delay and anti-flickering in RxJS
I want to implement loading indication using RxJS (version 6). A loading indicator (a spinner) would be shown in a component before asynchronous data call finishes. I have some rules to implement (whether these rules are correct might be another question, maybe leave a comment):

If the data arrives successfully earlier than in 1 second, no indicator should be shown (and data should be rendered normally)

If the call fails earlier than in 1 second, no indicator should be shown (and error message should be rendered)

If the data arrives later than in 1 second an indicator should be shown for at least 1 second (to prevent flashing spinner, the data should be rendered afterwards)

If the call fails later than in 1 second an indicator should be shown for at least 1 second

If the call takes more than 10 seconds the call should be canceled (and error message displayed)

I am implementing this in an Angular project, but I believe, that this is not Angular specific.

I have found some pieces of this puzzle, but I need help to assemble them together.

In this SO answer there is an implementation of an operator that delays the showing of a loading indicator.

A nice but incomplete implementation for Angular is described in this article.

Showing loading indicator for a minimum amount of time is described in this Medium article.

答:
You can try to construct a steam in a following fashion.

(Assuming data$ is your data observable that emits when data comes and errors, when it fails)

```<code>import { timer, merge, of } from 'rxjs';
import { mapTo, map, catchError, takeUntil, delay, switchMap } from 'rxjs/operators'

const startTime = new Date();
merge(
  data$.pipe(
    takeUntil(timer(10000)),
    map((data) => ({ data, showSpinner: false, showError: false })),
    catchError(() => of({ data: null, showSpinner: false, showError: true })),
    switchMap((result) => {
      const timeSinceStart = (new Date).getTime() - startTime.getTime();
      return timeSinceStart > 1000 && timeSinceStart < 2000 ? of(result).pipe(delay(2000 - timeSinceStart)) : of(result)
    }),
  )
  timer(1000).pipe(
    mapTo({ data: null, showSpinner: true, showError: false }),
    takeUntil(data$)
  ),
  timer(10000).pipe(
    mapTo({ data: null, showSpinner: false, showError: true }),
    takeUntil(data$)
  )
).subscribe(({ data, showSpinner, showError }) => {
   // assign the values to relevant properties so the template can
   // show either data, spinner, or error

});

</code>```

Body:
You can try to construct a steam in a following fashion.

(Assuming data$ is your data observable that emits when data comes and errors, when it fails)

import { timer, merge, of } from 'rxjs';
import { mapTo, map, catchError, takeUntil, delay, switchMap } from 'rxjs/operators'

const startTime = new Date();
merge(
  data$.pipe(
    takeUntil(timer(10000)),
    map((data) => ({ data, showSpinner: false, showError: false })),
    catchError(() => of({ data: null, showSpinner: false, showError: true })),
    switchMap((result) => {
      const timeSinceStart = (new Date).getTime() - startTime.getTime();
      return timeSinceStart > 1000 && timeSinceStart < 2000 ? of(result).pipe(delay(2000 - timeSinceStart)) : of(result)
    }),
  )
  timer(1000).pipe(
    mapTo({ data: null, showSpinner: true, showError: false }),
    takeUntil(data$)
  ),
  timer(10000).pipe(
    mapTo({ data: null, showSpinner: false, showError: true }),
    takeUntil(data$)
  )
).subscribe(({ data, showSpinner, showError }) => {
   // assign the values to relevant properties so the template can
   // show either data, spinner, or error

});


答:
You can map over your original object and change it's internal values or addon external values to it.

```<code>myModel.identification.map(idObj => {
   idObj.issuedEntity = {
       province: idObj.province
       country: idObj.country
   }
   delete idObj.province
   delete idObj.country
   return idObj
})
</code>```

Title: Iterate over an Array and push elements to an Object

Body:
You can map over your original object and change it's internal values or addon external values to it.

myModel.identification.map(idObj => {
   idObj.issuedEntity = {
       province: idObj.province
       country: idObj.country
   }
   delete idObj.province
   delete idObj.country
   return idObj
})


答:
I like @fa06 answer, but he misses, that you want the data daily.
so try this:</p>

```<code>select * from t1 a
where DATA_ORA in (select min(DATA_ORA) from t1 b where a.badge=b.badge GROUP BY DATE_FORMAT(DATA_ORA, '%Y%m%d'))
union
select * from t1 a
where DATA_ORA in (select max(DATA_ORA) from t1 b where a.badge=b.badge GROUP BY DATE_FORMAT(DATA_ORA, '%Y%m%d'));
</code>```

Title: Select Max and Min datetime for distinct user

Body:
I have a record as below

ID(int)      DATA_ORA(timestamp)     BADGE  LETTORE
   1         2017-04-01 09:30:00       1       1
   2         2017-04-01 12:30:00       1       2
   3         2017-04-01 13:30:00       1       1
   4         2017-04-01 18:30:00       1       2
   5         2017-04-01 09:30:00       2       1
   6         2017-04-01 18:30:00       2       2
   7         2017-04-02 09:30:00       1       1
   8         2017-04-02 18:30:00       1       2
   9         2017-04-03 09:30:00       3       1
   10        2017-04-03 12:30:00       3       2
   11        2017-04-03 13:30:00       3       1
   12        2017-04-03 18:30:00       3       2

I want to get the first access time and the last daily logout time (for each day) for each individual user (badge).

How I can do this?

The record I wish to as below

ID(int)      DATA_ORA(timestamp)     BADGE  LETTORE
   1         2017-04-01 09:30:00       1       1
   4         2017-04-01 18:30:00       1       2
   5         2017-04-01 09:30:00       2       1
   6         2017-04-01 18:30:00       2       2
   7         2017-04-02 09:30:00       1       1
   8         2017-04-02 18:30:00       1       2
   9         2017-04-03 09:30:00       3       1
   12        2017-04-03 18:30:00       3       2

Is it possible to do that? Thanks.

NOTE: ID are auto-incremented and LETTORE 1 is entry and LETTORE 2 is exit.

Body:
I like @fa06 answer, but he misses, that you want the data daily.
so try this:

select * from t1 a
where DATA_ORA in (select min(DATA_ORA) from t1 b where a.badge=b.badge GROUP BY DATE_FORMAT(DATA_ORA, '%Y%m%d'))
union
select * from t1 a
where DATA_ORA in (select max(DATA_ORA) from t1 b where a.badge=b.badge GROUP BY DATE_FORMAT(DATA_ORA, '%Y%m%d'));


问:
Can I alter the constraints of one table by using the constraints of another table?
I had to drop a table and remake it using an archive. In the process, I lost the table's constraints--things like the primary key--triggers, indices, and more. I have, however, the same table on a different DB, which has all the appropriate constraints.

I have tried adding the constraints, triggers, and indices manually, but there are just too many.

I was wondering if I could do something like:

```<code>alter table t73
  modify col_n....col_n+1
  using (select constraints from t73@otherdb)
</code>```

答:
this is below example how you can use dbms_metadata.get_ddl oracle package

```<code>create table EX_EMPLOYEe ( id number(5) null, name varchar2(100))
/
alter table ex_Employee add constraint PK_EX_EMPLOYEE primary key (id)
/
alter table ex_Employee add constraint FK_EX_EMPLOYEE foreign key (id)
references ex_Employee1 (id)
/
create table EX_EMPLOYEe1 ( id number(5) null, name varchar2(100))
/
alter table ex_Employee1 add constraint PK_EX_EMPLOYEE1 primary key (id)

alter table SYS_PARAM_KEY_LABEL
  add constraint FK1_SYS_PARAM_KEY_LABEL foreign key (KEY_GROUP_ID)
  references SYS_PARAM_KEY_GROUP (KEY_GROUP_ID);
/
CREATE INDEX IDX_EX_EMPLOYEe on ex_employee(name)
/
  Create or replace PROCEDURE P_EX_EMPLOYEe as
  begin
  select id from ex_employee where rownum=1;
  end;
/
CREATE OR REPLACE TRIGGER TRG_EX_EMPLOYEe AFTER DELETE ON EX_EMPLOYEe
FOR EACH ROW
BEGIN
  DELETE FROM ex_employee1 WHERE id = :OLD.ID;
END;
/
select to_char( dbms_metadata.get_ddl('CONSTRAINT', c.constraint_name)) from user_constraints c where table_name='EX_EMPLOYEE'
and c.constraint_type='P'
union
select to_char( dbms_metadata.get_ddl('REF_CONSTRAINT', c.constraint_name)) from user_constraints c where table_name='EX_EMPLOYEE'
and c.constraint_type='R'
union
select to_char( dbms_metadata.get_ddl('INDEX', c.index_name)) from user_indexes c where table_name='EX_EMPLOYEE'
union
select to_char( dbms_metadata.get_ddl('PROCEDURE', d.name)) from user_dependencies d where d.referenced_name='EX_EMPLOYEE'
and d.type='PROCEDURE'
union
select to_char( dbms_metadata.get_ddl('TRIGGER', d.name)) from user_dependencies d where d.referenced_name='EX_EMPLOYEE'
and d.type='TRIGGER'
</code>```

Body:
I had to drop a table and remake it using an archive. In the process, I lost the table's constraints--things like the primary key--triggers, indices, and more. I have, however, the same table on a different DB, which has all the appropriate constraints.

I have tried adding the constraints, triggers, and indices manually, but there are just too many.

I was wondering if I could do something like:

alter table t73
  modify col_n....col_n+1
  using (select constraints from t73@otherdb)

Body:
this is below example how you can use dbms_metadata.get_ddl oracle package

create table EX_EMPLOYEe ( id number(5) null, name varchar2(100))
/
alter table ex_Employee add constraint PK_EX_EMPLOYEE primary key (id)
/
alter table ex_Employee add constraint FK_EX_EMPLOYEE foreign key (id)
references ex_Employee1 (id)
/
create table EX_EMPLOYEe1 ( id number(5) null, name varchar2(100))
/
alter table ex_Employee1 add constraint PK_EX_EMPLOYEE1 primary key (id)

alter table SYS_PARAM_KEY_LABEL
  add constraint FK1_SYS_PARAM_KEY_LABEL foreign key (KEY_GROUP_ID)
  references SYS_PARAM_KEY_GROUP (KEY_GROUP_ID);
/
CREATE INDEX IDX_EX_EMPLOYEe on ex_employee(name)
/
  Create or replace PROCEDURE P_EX_EMPLOYEe as
  begin
  select id from ex_employee where rownum=1;
  end;
/
CREATE OR REPLACE TRIGGER TRG_EX_EMPLOYEe AFTER DELETE ON EX_EMPLOYEe
FOR EACH ROW
BEGIN
  DELETE FROM ex_employee1 WHERE id = :OLD.ID;
END;
/
select to_char( dbms_metadata.get_ddl('CONSTRAINT', c.constraint_name)) from user_constraints c where table_name='EX_EMPLOYEE'
and c.constraint_type='P'
union
select to_char( dbms_metadata.get_ddl('REF_CONSTRAINT', c.constraint_name)) from user_constraints c where table_name='EX_EMPLOYEE'
and c.constraint_type='R'
union
select to_char( dbms_metadata.get_ddl('INDEX', c.index_name)) from user_indexes c where table_name='EX_EMPLOYEE'
union
select to_char( dbms_metadata.get_ddl('PROCEDURE', d.name)) from user_dependencies d where d.referenced_name='EX_EMPLOYEE'
and d.type='PROCEDURE'
union
select to_char( dbms_metadata.get_ddl('TRIGGER', d.name)) from user_dependencies d where d.referenced_name='EX_EMPLOYEE'
and d.type='TRIGGER'


问:
linux find regex
I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

```<code>find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'
</code>```

Bash, Ubuntu

答:
You should have a look on the -regextype argument of find, see manpage:

```<code>      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex
          tests which occur later on the command line.  Currently-implemented
          types  are  emacs (this is the default), posix-awk, posix-basic,
          posix-egrep and posix-extended.
</code>```

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

```<code>find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'
</code>```

Title: linux find regex

Body:
I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'

Bash, Ubuntu

Body:
You should have a look on the -regextype argument of find, see manpage:

      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex
          tests which occur later on the command line.  Currently-implemented
          types  are  emacs (this is the default), posix-awk, posix-basic,
          posix-egrep and posix-extended.

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'


问:
In VB.net, is it possible to play an embedded MP3 audio file?
When I launch my application, background music starts.
The code below allows me to get that,
provided that I integrate a WAV audio file into the resources.

Unfortunately, a WAV audio file is very heavy: my file is 40 MB.
If I used the same audio file in mp3, it would be: 2.75 MB.

Visual Basic does not accept mp3 files. Is there not a way around this problem?
Thank you for your reply.

Class MainWindow

```<code>'Music Background.

Private Sub Main_Form_Loaded(sender As Object, e As RoutedEventArgs) Handles Main_Form.Loaded
    Dim son = New Media.SoundPlayer(My.Resources.My_Music)
    son.PlayLooping()
</code>```

答:
Thank you GSerg, your link has allowed me to find the solution: the code below works perfectly.
Previously, install Naudio under Visual Studio. Then,
Imports System.IO - Imports NAudio.Wave

Music Background.

```<code>Private Sub Form_Main_Loaded(sender As Object, e As RoutedEventArgs) Handles Form_Main.Loaded
    Dim mp3file As MemoryStream = New MemoryStream(My.Resources.My.Music)
    Dim mp3Reader As Mp3FileReader = New Mp3FileReader(mp3file)
    Dim waveOut As WaveOut = New WaveOut
    waveOut.Init(mp3Reader)
    waveOut.Play()
</code>```

Another question: is there a function or an additional code to play music loop? Thank you for your reply.

Body:
When I launch my application, background music starts.
The code below allows me to get that,
provided that I integrate a WAV audio file into the resources.

Unfortunately, a WAV audio file is very heavy: my file is 40 MB.
If I used the same audio file in mp3, it would be: 2.75 MB.

Visual Basic does not accept mp3 files. Is there not a way around this problem?
Thank you for your reply.

Class MainWindow

'Music Background.

Private Sub Main_Form_Loaded(sender As Object, e As RoutedEventArgs) Handles Main_Form.Loaded
    Dim son = New Media.SoundPlayer(My.Resources.My_Music)
    son.PlayLooping()

Body:
Thank you GSerg, your link has allowed me to find the solution: the code below works perfectly.
Previously, install Naudio under Visual Studio. Then,
Imports System.IO - Imports NAudio.Wave

Music Background.

Private Sub Form_Main_Loaded(sender As Object, e As RoutedEventArgs) Handles Form_Main.Loaded
    Dim mp3file As MemoryStream = New MemoryStream(My.Resources.My.Music)
    Dim mp3Reader As Mp3FileReader = New Mp3FileReader(mp3file)
    Dim waveOut As WaveOut = New WaveOut
    waveOut.Init(mp3Reader)
    waveOut.Play()

Another question: is there a function or an additional code to play music loop? Thank you for your reply.


问:
How to pass environment variable to docker-compose up
I am trying to run a container. I already have the image uploaded to private Docker registry. I want to write a compose file to download and deploy the image. But I want to pass the TAG name as a variable from the docker-compose run command.My compose file looks like below. How can I pass the value for KB_DB_TAG_VERSION as part of docker-compose up command?</p>

```<code>version: '3'
services:
   db:
    #build: k-db
    user: "1000:50"
    volumes:
      - /data/mysql:/var/lib/mysql
    container_name: k-db
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    image:  XX:$KB_DB_TAG_VERSION
    image: k-db
    ports:
      - "3307:3306"
</code>```

答:
In your docker-compose.yml file add

```<code>env_file:
  - .env_file
</code>```

to your db service where .env_file is your .env file (change its name accordingly).

```<code>version: '3'
services:
   db:
    #build: k-db
    user: "1000:50"
    volumes:
      - /data/mysql:/var/lib/mysql
    container_name: k-db
    env_file:
      - .env_file
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    image:  XX:$KB_DB_TAG_VERSION
    image: k-db
    ports:
      - "3307:3306"
</code>```

Body:
I am trying to run a container. I already have the image uploaded to private Docker registry. I want to write a compose file to download and deploy the image. But I want to pass the TAG name as a variable from the docker-compose run command.My compose file looks like below. How can I pass the value for KB_DB_TAG_VERSION as part of docker-compose up command?

version: '3'
services:
   db:
    #build: k-db
    user: "1000:50"
    volumes:
      - /data/mysql:/var/lib/mysql
    container_name: k-db
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    image:  XX:$KB_DB_TAG_VERSION
    image: k-db
    ports:
      - "3307:3306"

Body:
In your docker-compose.yml file add

env_file:
  - .env_file

to your db service where .env_file is your .env file (change its name accordingly).

version: '3'
services:
   db:
    #build: k-db
    user: "1000:50"
    volumes:
      - /data/mysql:/var/lib/mysql
    container_name: k-db
    env_file:
      - .env_file
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    image:  XX:$KB_DB_TAG_VERSION
    image: k-db
    ports:
      - "3307:3306"


问:
Seaborn: Violinplot experiences difficulty with too many variables?
I wanted to use seaborn to visualize my entire Pandas dataframe with violinplots, and I thought I had made the necessary corrections to generate a large graph for the sizable number of 270 variables my dataframe possessed.

However, no matter what I do, the violinplots only display their inner mini-boxplots (as another question here describes) for each variable, and not their kde's:

```<code>fig, ax = plt.subplots(figsize=(50,5))
ax.set_ylim(-6, 6)

a = sns.violinplot(x='variable', y='value', data=pd.melt(train_norm), ax=ax)
a.set_xticklabels(a.get_xticklabels(), rotation=90);

plt.savefig('massive_violinplot.png', figsize=(50,5), dpi=220)
</code>```

(apologies for the cropped graph, the whole thing is too big to post)

Whereas the following code, using the same pd.Dataframe, but only showing the first six variables, displays correctly:

```<code>fig, ax = plt.subplots(figsize=(10,5))
ax.set_ylim(-6, 6)

a = sns.violinplot(x='variable', y='value', data=pd.melt(train_norm.iloc[:,:6]), ax=ax)
a.set_xticklabels(a.get_xticklabels(), rotation=90);

plt.savefig('massive_violinplot.png', figsize=(10,5), dpi=220)
</code>```

How could I get a graph like the above for all the variables, filled with proper violinplots showing their kde's?

答:
This is not related to the number of variables or the plot size but to the huge differences in the distributions of the variables. I can't access your data right now so I will ilustrate it with a made up dataset. You can follow along with your dataset, selecting the three variables with more dispersion and the three with less dispersion. As a dispersion measurement you can use the variance or even the data range (if you don't have crazy long tails) or something different, I am not sure what would work better.

```<code>rs = np.random.RandomState(42)
data = rs.randn(100, 6)
data[:, :3] *= 20
df = pd.DataFrame(data)
</code>```

See what happens if we plot the density with common axes so they are directly comparable.

```<code>df.plot(kind='kde', subplots=True, layout=(3, 2), sharex=True, sharey=True)
plt.tight_layout()
</code>```

This is more or less the same you can see in the seaborn violin plot but of course transposed.

```<code>sns.violinplot(x='variable', y='value', data=pd.melt(df))
</code>```

This is usually great for comparing the variables because you can look at the differences in width as differences in density. Unfortunately the violin for the variables with more dispersion are so narrow that you can't see the width at all and you lose any sense of the shape. On the other hand the variables with less dispersion appear too short (actually in your dataset some of them are just horizontal lines).

For the first problem you can make the violins use all the available horizontal space by using scale='width' but then you no longer can compare the density across variables. The width is the same at the peaks but the density is not.

```<code>sns.violinplot(x='variable', y='value', data=pd.melt(df), scale='width')
</code>```

By the way, this is what matplotlib's violin plot does by default.

```<code>plt.violinplot(df.T)
</code>```

For the second problem I think your only option is to normalize or standardize the variables in some way.

```<code>sns.violinplot(x='variable', y='value', data=pd.melt((df - df.mean()) / df.std()))
</code>```

Now you have a clearer view of each variable separately (how many modes they have, how skewed they are, how long the tails are...) but you can compare neither the scale nor the dispersion across variables.

The moral of the story is that you can't see everything at once, you have to pick and choose depending on what you are looking for in the data.

Body:
I wanted to use seaborn to visualize my entire Pandas dataframe with violinplots, and I thought I had made the necessary corrections to generate a large graph for the sizable number of 270 variables my dataframe possessed.

However, no matter what I do, the violinplots only display their inner mini-boxplots (as another question here describes) for each variable, and not their kde's:

fig, ax = plt.subplots(figsize=(50,5))
ax.set_ylim(-6, 6)

a = sns.violinplot(x='variable', y='value', data=pd.melt(train_norm), ax=ax)
a.set_xticklabels(a.get_xticklabels(), rotation=90);

plt.savefig('massive_violinplot.png', figsize=(50,5), dpi=220)

(apologies for the cropped graph, the whole thing is too big to post)

Whereas the following code, using the same pd.Dataframe, but only showing the first six variables, displays correctly:

fig, ax = plt.subplots(figsize=(10,5))
ax.set_ylim(-6, 6)

a = sns.violinplot(x='variable', y='value', data=pd.melt(train_norm.iloc[:,:6]), ax=ax)
a.set_xticklabels(a.get_xticklabels(), rotation=90);

plt.savefig('massive_violinplot.png', figsize=(10,5), dpi=220)

How could I get a graph like the above for all the variables, filled with proper violinplots showing their kde's?

Body:
This is not related to the number of variables or the plot size but to the huge differences in the distributions of the variables. I can't access your data right now so I will ilustrate it with a made up dataset. You can follow along with your dataset, selecting the three variables with more dispersion and the three with less dispersion. As a dispersion measurement you can use the variance or even the data range (if you don't have crazy long tails) or something different, I am not sure what would work better.

rs = np.random.RandomState(42)
data = rs.randn(100, 6)
data[:, :3] *= 20
df = pd.DataFrame(data)

See what happens if we plot the density with common axes so they are directly comparable.

df.plot(kind='kde', subplots=True, layout=(3, 2), sharex=True, sharey=True)
plt.tight_layout()

This is more or less the same you can see in the seaborn violin plot but of course transposed.

sns.violinplot(x='variable', y='value', data=pd.melt(df))

This is usually great for comparing the variables because you can look at the differences in width as differences in density. Unfortunately the violin for the variables with more dispersion are so narrow that you can't see the width at all and you lose any sense of the shape. On the other hand the variables with less dispersion appear too short (actually in your dataset some of them are just horizontal lines).

For the first problem you can make the violins use all the available horizontal space by using scale='width' but then you no longer can compare the density across variables. The width is the same at the peaks but the density is not.

sns.violinplot(x='variable', y='value', data=pd.melt(df), scale='width')

By the way, this is what matplotlib's violin plot does by default.

plt.violinplot(df.T)

For the second problem I think your only option is to normalize or standardize the variables in some way.

sns.violinplot(x='variable', y='value', data=pd.melt((df - df.mean()) / df.std()))

Now you have a clearer view of each variable separately (how many modes they have, how skewed they are, how long the tails are...) but you can compare neither the scale nor the dispersion across variables.

The moral of the story is that you can't see everything at once, you have to pick and choose depending on what you are looking for in the data.


答:
Try awk script:</p>

```<code>awk '{printf("%s",$0)}NR==FNR{printf(",")}' 1234ABC.stats.csv 1234ABC.csv
</code>```

Title: How to merge 2 CSV files based on filename

Body:
I have 2 CSV files:

1234ABC.stats.csv
name,value1,value1

1234ABC.csv
value2,value2,value2

Both of these files have only 1 line in them.

They both have no header, and are in the same directory with no other file types.

How can I add the content from the second file onto the end of the line from the first?

desired output:

name,value1,value1,value2,value2,value2

Body:
Try awk script:

awk '{printf("%s",$0)}NR==FNR{printf(",")}' 1234ABC.stats.csv 1234ABC.csv