问:
SQL NESTED JOIN ISSUES
I'm having a heck of a time getting my query to work properly.  I have 3 tables (ORDERS, ORDERSITEMS, ORDERPAYMENTS) that I'm trying to build a report for monthly sales taxes due which will look like this:

```<code>MONTH      YEAR        TOTAL RECEIPTS        EXEMPT RECEIPTS     NON-EXEMPT RECEIPTS        SALES TAX
1           2020        $5,000                $4,500                $500                      $31.25
</code>```

TOTAL RECEIPTS:  To get this number you have to add together all of the C.OrderPayments_Amount for the given time frame, in this case  MONTH(C.OrderPayments_Date) = 1  AND YEAR(C.OrderPayments_Date) = 2020

EXEMPT RECEIPTS: You have to determine if an item is taxable (eg. digital files are not sales taxable, physical prints are).  To get this you have determine if the item is taxable by checking the B.OrdersItems_ItemChargeSalesTax.  If this field is 0 it does not get charged sales tax and if it is 1 then it does.  You then have to filter to only get ORDERSITEMS for the Jan 2020 time frame using  by grouping by the C.OrderPayments_Date column that have the B.OrdersItems_ItemChargeSalesTax = 0 and finally add the B.OrdersItems_Total together.

NON-EXEMPT RECEIPTS:  To get this number you do the same exact thing for EXEMPT RECEIPTS above except you look for B.OrdersItems_ItemChargeSalesTax = 1 and add the B.OrdersItems_Total together.

SALES TAX: To get this number you use the same date filter as before MONTH(C.OrderPayments_Date) = 1  AND YEAR(C.OrderPayments_Date) = 2020 and then add the A.Order_SalesTax column together.

The first query I have listed is working fine to bring me the total taxes paid and the total income for the month (right now I have hard coded the WHERE statement but that is going to be applied via filters on my list page).  What I
need to get from the ORDERSITEMS table is a field called ORDERSITEMS_ItemTotal and sum that field so it is a single line entry on the query.  I have seen another person do a nested join.  Any suggestions would be greatly appreciated.

```<code>**ORDERS TABLE "A"**
  Order_ID,
  Order_SalesTax,
  stateTaxAbbreviation

**ORDERSITEMS TABLE "B"**
  Order_FK,
  OrdersItems_ItemChargeSalesTax,
  OrdersItems_Total
</code>```

NOTE:  In the ORDERSITEMS table a single Order_FK may appear several times as there can be many items on an order

```<code>**ORDERPAYMENTS TABLE "C"**
  Order_FK,
  OrderPayments_PaymentDate,
  OrderPayments_Amount
</code>```

NOTE:  In the ORDERPAYMENTS table a single Order_FK may appear several times as there can be multiple payments on an order

While writing this out it seems to be an easy task but when I attempt to put it all together the numbers are wrong because it is adding entries multiple times because there are multiple items on an order and thus it is adding the total payment every time.

Here is the code that I've been tinkering with and I would really appreciate any guidance.  Thank you in advance and hopefully I've explained my situation clearly enough.

```<code>Select
    a.stateTaxAbbreviation AS StateAbbr,
    MONTH(c.OrderPayments_Date) AS PaymentMonth,
    YEAR(c.OrderPayments_Date) AS PaymentYear,
    SUM(c.OrderPayments_Amount) AS TotalPayments,
    SUM(a.Order_SalesTax) AS sales_tax
FROM dbo.ORDERS a
   INNER JOIN ORDERPAYMENTS as c ON c.Order_FK = a.Order_ID
      LEFT OUTER JOIN ORDERITEMS b on b.Order_FK = a.Order_ID
  WHERE a.stateTaxAbbreviation = 'MA' AND Month(b.OrderPayments_Date) = 1 AND YEAR(b.OrderPayments_Date) = 2020
  GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)
</code>```

答:
Thanks to Wouter for pointing me in the right direction.  After looking at his suggestion I went back and evaluated what I needed and I create the solution that worked that was based on his idea.  Thanks for your patience Wouter, your insight helped a lot!  </p>

```<code>    Select StateAbbr, OrderYear, OrderMonth, SUM(TotalSales) As TotalSales, SUM(TotalSales)-SUM(TaxableRevenue) As ExemptRevenue, SUM(TaxableRevenue) As TaxableRevenue, SUM(SalesTax) As SalesTax
 FROM (
 Select
        /*Get Total Sales and Total Sales Tax Collected*/
        a.stateTaxAbbreviation AS StateAbbr,
        MONTH(a.Order_Date) As OrderMonth,
        YEAR(a.Order_Date) As OrderYear,
        SUM((a.Order_TotalBaseSale + a.Order_Shipping) - (((a.Order_PercentDiscount*a.Order_TotalBaseSale)/100) + a.Order_DollarDiscount)) As TotalSales,
        SUM(0) As ExemptRevenue,
        Sum(0) As TaxableRevenue,
        SUM(a.Order_SalesTax) AS SalesTax

 FROM dbo.ORDERS a
    WHERE a.Order_Status != 'Cancelled'
    Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)

    UNION ALL

Select
    /*GET EXEMPT ORDERS*/
    a.stateTaxAbbreviation AS StateAbbr,
    MONTH(a.Order_Date) As OrderMonth,
    YEAR(a.Order_Date) As OrderYear,
    Sum(0) As TotalSales,
    Sum(OrdersItems_ItemTotal) AS ExemptRevenue,
    Sum(0) AS TaxableRevenue,
    Sum(0) As SalesTax

FROM ORDERSITEMS b
LEFT JOIN ORDERS a ON Order_ID = b.Order_FK
    WHERE b.OrdersItems_ItemChargeSalesTax = 0 and a.Order_Status != 'Cancelled'
    Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)

    UNION ALL
Select
    /*GET NON-EXEMPT ORDERS*/
    a.stateTaxAbbreviation AS StateAbbr,
    MONTH(a.Order_Date) As OrderMonth,
    YEAR(a.Order_Date) As OrderYear,
    SUM(0) As TotalSales,
    SUM(0) AS ExemptRevenue,
    Sum(OrdersItems_ItemTotal) AS TaxableRevenue,
    Sum(0) As SalesTax

FROM ORDERSITEMS b
LEFT JOIN ORDERS a ON Order_ID = b.Order_FK
WHERE b.OrdersItems_ItemChargeSalesTax <> 0 and a.Order_Status != 'Cancelled'
Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)
)t

GROUP BY StateAbbr, OrderMonth, OrderYear
ORDER BY StateAbbr ASC, OrderYear DESC, OrderMonth ASC
</code>```

Title: SQL NESTED JOIN ISSUES

Body:
I'm having a heck of a time getting my query to work properly.  I have 3 tables (ORDERS, ORDERSITEMS, ORDERPAYMENTS) that I'm trying to build a report for monthly sales taxes due which will look like this:

MONTH      YEAR        TOTAL RECEIPTS        EXEMPT RECEIPTS     NON-EXEMPT RECEIPTS        SALES TAX
1           2020        $5,000                $4,500                $500                      $31.25

TOTAL RECEIPTS:  To get this number you have to add together all of the C.OrderPayments_Amount for the given time frame, in this case  MONTH(C.OrderPayments_Date) = 1  AND YEAR(C.OrderPayments_Date) = 2020

EXEMPT RECEIPTS: You have to determine if an item is taxable (eg. digital files are not sales taxable, physical prints are).  To get this you have determine if the item is taxable by checking the B.OrdersItems_ItemChargeSalesTax.  If this field is 0 it does not get charged sales tax and if it is 1 then it does.  You then have to filter to only get ORDERSITEMS for the Jan 2020 time frame using  by grouping by the C.OrderPayments_Date column that have the B.OrdersItems_ItemChargeSalesTax = 0 and finally add the B.OrdersItems_Total together.

NON-EXEMPT RECEIPTS:  To get this number you do the same exact thing for EXEMPT RECEIPTS above except you look for B.OrdersItems_ItemChargeSalesTax = 1 and add the B.OrdersItems_Total together.

SALES TAX: To get this number you use the same date filter as before MONTH(C.OrderPayments_Date) = 1  AND YEAR(C.OrderPayments_Date) = 2020 and then add the A.Order_SalesTax column together.

The first query I have listed is working fine to bring me the total taxes paid and the total income for the month (right now I have hard coded the WHERE statement but that is going to be applied via filters on my list page).  What I
need to get from the ORDERSITEMS table is a field called ORDERSITEMS_ItemTotal and sum that field so it is a single line entry on the query.  I have seen another person do a nested join.  Any suggestions would be greatly appreciated.

**ORDERS TABLE "A"**
  Order_ID,
  Order_SalesTax,
  stateTaxAbbreviation

**ORDERSITEMS TABLE "B"**
  Order_FK,
  OrdersItems_ItemChargeSalesTax,
  OrdersItems_Total

NOTE:  In the ORDERSITEMS table a single Order_FK may appear several times as there can be many items on an order

**ORDERPAYMENTS TABLE "C"**
  Order_FK,
  OrderPayments_PaymentDate,
  OrderPayments_Amount

NOTE:  In the ORDERPAYMENTS table a single Order_FK may appear several times as there can be multiple payments on an order

While writing this out it seems to be an easy task but when I attempt to put it all together the numbers are wrong because it is adding entries multiple times because there are multiple items on an order and thus it is adding the total payment every time.

Here is the code that I've been tinkering with and I would really appreciate any guidance.  Thank you in advance and hopefully I've explained my situation clearly enough.

Select
    a.stateTaxAbbreviation AS StateAbbr,
    MONTH(c.OrderPayments_Date) AS PaymentMonth,
    YEAR(c.OrderPayments_Date) AS PaymentYear,
    SUM(c.OrderPayments_Amount) AS TotalPayments,
    SUM(a.Order_SalesTax) AS sales_tax
FROM dbo.ORDERS a
   INNER JOIN ORDERPAYMENTS as c ON c.Order_FK = a.Order_ID
      LEFT OUTER JOIN ORDERITEMS b on b.Order_FK = a.Order_ID
  WHERE a.stateTaxAbbreviation = 'MA' AND Month(b.OrderPayments_Date) = 1 AND YEAR(b.OrderPayments_Date) = 2020
  GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)

Body:
Thanks to Wouter for pointing me in the right direction.  After looking at his suggestion I went back and evaluated what I needed and I create the solution that worked that was based on his idea.  Thanks for your patience Wouter, your insight helped a lot!

    Select StateAbbr, OrderYear, OrderMonth, SUM(TotalSales) As TotalSales, SUM(TotalSales)-SUM(TaxableRevenue) As ExemptRevenue, SUM(TaxableRevenue) As TaxableRevenue, SUM(SalesTax) As SalesTax
 FROM (
 Select
        /*Get Total Sales and Total Sales Tax Collected*/
        a.stateTaxAbbreviation AS StateAbbr,
        MONTH(a.Order_Date) As OrderMonth,
        YEAR(a.Order_Date) As OrderYear,
        SUM((a.Order_TotalBaseSale + a.Order_Shipping) - (((a.Order_PercentDiscount*a.Order_TotalBaseSale)/100) + a.Order_DollarDiscount)) As TotalSales,
        SUM(0) As ExemptRevenue,
        Sum(0) As TaxableRevenue,
        SUM(a.Order_SalesTax) AS SalesTax

 FROM dbo.ORDERS a
    WHERE a.Order_Status != 'Cancelled'
    Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)

    UNION ALL

Select
    /*GET EXEMPT ORDERS*/
    a.stateTaxAbbreviation AS StateAbbr,
    MONTH(a.Order_Date) As OrderMonth,
    YEAR(a.Order_Date) As OrderYear,
    Sum(0) As TotalSales,
    Sum(OrdersItems_ItemTotal) AS ExemptRevenue,
    Sum(0) AS TaxableRevenue,
    Sum(0) As SalesTax

FROM ORDERSITEMS b
LEFT JOIN ORDERS a ON Order_ID = b.Order_FK
    WHERE b.OrdersItems_ItemChargeSalesTax = 0 and a.Order_Status != 'Cancelled'
    Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)

    UNION ALL
Select
    /*GET NON-EXEMPT ORDERS*/
    a.stateTaxAbbreviation AS StateAbbr,
    MONTH(a.Order_Date) As OrderMonth,
    YEAR(a.Order_Date) As OrderYear,
    SUM(0) As TotalSales,
    SUM(0) AS ExemptRevenue,
    Sum(OrdersItems_ItemTotal) AS TaxableRevenue,
    Sum(0) As SalesTax

FROM ORDERSITEMS b
LEFT JOIN ORDERS a ON Order_ID = b.Order_FK
WHERE b.OrdersItems_ItemChargeSalesTax <> 0 and a.Order_Status != 'Cancelled'
Group By a.stateTaxAbbreviation, MONTH(a.Order_Date), YEAR(a.Order_Date)
)t

GROUP BY StateAbbr, OrderMonth, OrderYear
ORDER BY StateAbbr ASC, OrderYear DESC, OrderMonth ASC


来源: stackexchange

问:
STM32F072RB does not receive/send data over SPI in slave mode
I am using the
STM32F072RB
uC to receive and transmit data over SPI2 in slave mode with the following configuration:

```<code>CR1 = 0x0078
CR2 = 0x0700
AFRH = 0x55353500
MODER = 0xa2a0556a
</code>```

The register APB1ENR is also properly configured.

The current program just checks the RXNE flag, reads the received data from DR and sends a random value writing to DR.

The status register when I receive data has the following value:

```<code>SR = 0x1403
</code>```

The master sends data properly and I checked the signals at the slave pins (clock phase and polarity are identical on both sides and the NSS signal is cleared before sending SCK and data over MOSI).

I even configured the pins as inputs and I know I could read any digital signal the master could send.
With the current configuration it seems the slave receives something because the RXNE is set when the master sends data but the read value is always 0x00.

I have tried different configurations (software/hardware NSS, different data sizes, etc.) but I always get 0x00.
Moreover, the random value I send after reading DR is not sent to the outputs.

This is my current function, which is called continuously:

```<code>unsigned char spi_rx_slave(unsigned char spiPort, unsigned char *receiveBuffer)
{
    uint8_t temp;
    static unsigned long sr;
    if (!spi_isOpen(spiPort))
    {
        sendDebug("%s() Error: spiPort not in use!\r\n",__func__);
        return false;
    }
    if (spiDescriptor[spiPort]->powerdown == true)
    {
        sendDebug("%s() Error: spiPort in powerdown!\r\n",__func__);
        return false;
    }
    /* wait till spi is not busy anymore */
    while((spiDescriptor[spiPort]->spiBase->SR) & SPI_SR_BSY)
    {
        sendDebug("SPI is busy(1)\r\n");
        vTaskDelay(2);
    }
    sendDebug("CR1 = 0x%04x, ", spiDescriptor[spiPort]->spiBase->CR1);
    sendDebug("CR2 = 0x%04x, ", spiDescriptor[spiPort]->spiBase->CR2);
    sendDebug("AFRH address = 0x%08x, AFRH value = %08x, ", (unsigned long*)(GPIOB_BASE+0x24), *(unsigned long*)(GPIOB_BASE+0x24));
    sendDebug("MODER address = 0x%08x, MODER value = %08x\r\n", (unsigned long*)(GPIOB_BASE), *(unsigned long*)(GPIOB_BASE));
    sr = spiDescriptor[spiPort]->spiBase->SR;
    while(sr & SPI_SR_RXNE)
    {
        /* get RX byte */
        temp = *(uint8_t *)&(spiDescriptor[spiPort]->spiBase->DR);
        spiDescriptor[spiPort]->spiBase->DR = 0x53;
        sendDebug("-------->DR address = 0x%08x, data received: 0x%02x\r\n", &spiDescriptor[spiPort]->spiBase->DR, temp);
        sendDebug("SR = 0x%04x\r\n", sr);
        vTaskDelay(1);
        sr = spiDescriptor[spiPort]->spiBase->SR;
    }
    while((spiDescriptor[spiPort]->spiBase->SR) & SPI_SR_BSY)
    {
        sendDebug("SPI is busy(2)\r\n");
        vTaskDelay(2);
    }
    return true;
}
</code>```

What am I doing wrong?
Is there anything I did not configure properly?

Thanks in advance.
Regards,
Javier

Edit:

I switched to software NSS and copied the register values from a STM32CubeMX example I found online. I cannot use those libraries for this project but I would like to have the same behaviour.

The new values are:

```<code>CR1 = 0x0278
</code>```

which means

fPCLK/256 (the proper one for the communication speed),

SPI enabled and

SSM = 1 (software NSS).

```<code>CR2 = 0x1700
</code>```

which means

8-bit data and

RXNE event is generated if the FIFO level is greater than or equal to 1/4 (8-bit).

```<code>AFRH = 0x55303500
MODER = 0xa8a1556a
</code>```

which means

MISO, MOSI and SCK alternate function 5 (SPI2)

NSS is not configured because now it is in software mode (slave is always selected).

I am still getting the same results and the eval kit with those libraries works fine using SPI1 instead.
Therefore there must be another issue that has nothing to do with the register values.

Might there be any clock issue e.g. the pins need to get some clock?

Thanks!

答:
The question points to a couple of mistakes which may explain why no receive has been observed:

GPIO configuration points to some wrong Alternate Functions / Modes:
The question didn't state it precisely, but I assume that

```<code>AFRH = 0x55303500
MODER = 0xa8a1556a
</code>```

refers to GPIOB (otherwise, it wouldn't make sense with SPI2).
This corresponds to the following pin configuration (see the
Reference Manual,
sec. 8.4.1, 8.4.10 and the
Datasheet,
Table 16):

```<code>PB15 - Alternate Function - AF5 = [INVALID]
PB14 - Alternate Function - AF5 = [I2C2_SDA]
PB13 - Alternate Function - AF3 = [TSC_G6_IO3]
PB12 - GP Input (reset state)
PB11 - Alternate Function - AF3 = [TIM_CH4]
PB10 - Alternate Function - AF5 = [SPI2_SCK / I2S2_CK]
PB09 - GP Input (reset state)
PB08 - GP Output
PB07 - Alternate Function - (unknown which, see register AFRL)
PB06 - GP Output
PB05 - Alternate Function - (unknown which, see register AFRL)
PB04 - GP Output
PB03 - GP Output
PB02 - Alternate Function - (unknown which, see register AFRL)
PB01 - Alternate Function - (unknown which, see register AFRL)
PB00 - Alternate Function - (unknown which, see register AFRL)
</code>```

This is obviously not what the software is required to do.

Solution: Make sure to configure PB15=>AF0, PB14=>AF0, either PB13=>AF0 or PB10=>AF0, depending on your hardware.

In order to avoid mistakes in doing so, you should follow the hint of @P__J__ and use speaking macros for constants assigned to MODER, AFRH etc.
Using the HAL library provided by ST is a truly controversial subject among SO users, but one should really consider to use at least a header like stm32f072xb.h with macros like GPIO_AFRH_AFSEL15.
If one represents all configuration register values as (bitwise) ORs of such macros, it is easier to re-check configuration against datasheets, and the famous
rubber duck
will directly know what an unhappy developer is talking about.

Other clock activations might be missing:
The question confirms that

The register APB1ENR is also properly configured.

This is correct (as long as bit 14 is set).

Additionally, GPIOB must be powered, i. e., bit 18 of RCC_AHBENR must be set.
See again the
Reference Manual,
sec. 6.4.8 and 6.4.6.

GPIO pins may be in wrong mode during debugging:

I even configured the pins as inputs and I know I could read any digital signal the master could send. With the current configuration it seems the slave receives something because the RXNE is set when the master sends data but the read value is always 0x00.

Please note that for every GPIO pin, a unique mode is selected through the MODER register. If this is set to "Input" (0b00), the Alternate Function is disconnected and won't work with external signals.

ContentLicense: CC BY-SA 4.0

Body:
I am using the
STM32F072RB
uC to receive and transmit data over SPI2 in slave mode with the following configuration:

CR1 = 0x0078
CR2 = 0x0700
AFRH = 0x55353500
MODER = 0xa2a0556a

The register APB1ENR is also properly configured.

The current program just checks the RXNE flag, reads the received data from DR and sends a random value writing to DR.

The status register when I receive data has the following value:

SR = 0x1403

The master sends data properly and I checked the signals at the slave pins (clock phase and polarity are identical on both sides and the NSS signal is cleared before sending SCK and data over MOSI).

I even configured the pins as inputs and I know I could read any digital signal the master could send.
With the current configuration it seems the slave receives something because the RXNE is set when the master sends data but the read value is always 0x00.

I have tried different configurations (software/hardware NSS, different data sizes, etc.) but I always get 0x00.
Moreover, the random value I send after reading DR is not sent to the outputs.

This is my current function, which is called continuously:

unsigned char spi_rx_slave(unsigned char spiPort, unsigned char *receiveBuffer)
{
    uint8_t temp;
    static unsigned long sr;
    if (!spi_isOpen(spiPort))
    {
        sendDebug("%s() Error: spiPort not in use!\r\n",__func__);
        return false;
    }
    if (spiDescriptor[spiPort]->powerdown == true)
    {
        sendDebug("%s() Error: spiPort in powerdown!\r\n",__func__);
        return false;
    }
    /* wait till spi is not busy anymore */
    while((spiDescriptor[spiPort]->spiBase->SR) & SPI_SR_BSY)
    {
        sendDebug("SPI is busy(1)\r\n");
        vTaskDelay(2);
    }
    sendDebug("CR1 = 0x%04x, ", spiDescriptor[spiPort]->spiBase->CR1);
    sendDebug("CR2 = 0x%04x, ", spiDescriptor[spiPort]->spiBase->CR2);
    sendDebug("AFRH address = 0x%08x, AFRH value = %08x, ", (unsigned long*)(GPIOB_BASE+0x24), *(unsigned long*)(GPIOB_BASE+0x24));
    sendDebug("MODER address = 0x%08x, MODER value = %08x\r\n", (unsigned long*)(GPIOB_BASE), *(unsigned long*)(GPIOB_BASE));
    sr = spiDescriptor[spiPort]->spiBase->SR;
    while(sr & SPI_SR_RXNE)
    {
        /* get RX byte */
        temp = *(uint8_t *)&(spiDescriptor[spiPort]->spiBase->DR);
        spiDescriptor[spiPort]->spiBase->DR = 0x53;
        sendDebug("-------->DR address = 0x%08x, data received: 0x%02x\r\n", &spiDescriptor[spiPort]->spiBase->DR, temp);
        sendDebug("SR = 0x%04x\r\n", sr);
        vTaskDelay(1);
        sr = spiDescriptor[spiPort]->spiBase->SR;
    }
    while((spiDescriptor[spiPort]->spiBase->SR) & SPI_SR_BSY)
    {
        sendDebug("SPI is busy(2)\r\n");
        vTaskDelay(2);
    }
    return true;
}

What am I doing wrong?
Is there anything I did not configure properly?

Thanks in advance.
Regards,
Javier

Edit:

I switched to software NSS and copied the register values from a STM32CubeMX example I found online. I cannot use those libraries for this project but I would like to have the same behaviour.

The new values are:

CR1 = 0x0278

which means

fPCLK/256 (the proper one for the communication speed),

SPI enabled and

SSM = 1 (software NSS).

CR2 = 0x1700

which means

8-bit data and

RXNE event is generated if the FIFO level is greater than or equal to 1/4 (8-bit).

AFRH = 0x55303500
MODER = 0xa8a1556a

which means

MISO, MOSI and SCK alternate function 5 (SPI2)

NSS is not configured because now it is in software mode (slave is always selected).

I am still getting the same results and the eval kit with those libraries works fine using SPI1 instead.
Therefore there must be another issue that has nothing to do with the register values.

Might there be any clock issue e.g. the pins need to get some clock?

Thanks!

Body:
The question points to a couple of mistakes which may explain why no receive has been observed:

GPIO configuration points to some wrong Alternate Functions / Modes:
The question didn't state it precisely, but I assume that

AFRH = 0x55303500
MODER = 0xa8a1556a

refers to GPIOB (otherwise, it wouldn't make sense with SPI2).
This corresponds to the following pin configuration (see the
Reference Manual,
sec. 8.4.1, 8.4.10 and the
Datasheet,
Table 16):

PB15 - Alternate Function - AF5 = [INVALID]
PB14 - Alternate Function - AF5 = [I2C2_SDA]
PB13 - Alternate Function - AF3 = [TSC_G6_IO3]
PB12 - GP Input (reset state)
PB11 - Alternate Function - AF3 = [TIM_CH4]
PB10 - Alternate Function - AF5 = [SPI2_SCK / I2S2_CK]
PB09 - GP Input (reset state)
PB08 - GP Output
PB07 - Alternate Function - (unknown which, see register AFRL)
PB06 - GP Output
PB05 - Alternate Function - (unknown which, see register AFRL)
PB04 - GP Output
PB03 - GP Output
PB02 - Alternate Function - (unknown which, see register AFRL)
PB01 - Alternate Function - (unknown which, see register AFRL)
PB00 - Alternate Function - (unknown which, see register AFRL)

This is obviously not what the software is required to do.

Solution: Make sure to configure PB15=>AF0, PB14=>AF0, either PB13=>AF0 or PB10=>AF0, depending on your hardware.

In order to avoid mistakes in doing so, you should follow the hint of @P__J__ and use speaking macros for constants assigned to MODER, AFRH etc.
Using the HAL library provided by ST is a truly controversial subject among SO users, but one should really consider to use at least a header like stm32f072xb.h with macros like GPIO_AFRH_AFSEL15.
If one represents all configuration register values as (bitwise) ORs of such macros, it is easier to re-check configuration against datasheets, and the famous
rubber duck
will directly know what an unhappy developer is talking about.

Other clock activations might be missing:
The question confirms that

The register APB1ENR is also properly configured.

This is correct (as long as bit 14 is set).

Additionally, GPIOB must be powered, i. e., bit 18 of RCC_AHBENR must be set.
See again the
Reference Manual,
sec. 6.4.8 and 6.4.6.

GPIO pins may be in wrong mode during debugging:

I even configured the pins as inputs and I know I could read any digital signal the master could send. With the current configuration it seems the slave receives something because the RXNE is set when the master sends data but the read value is always 0x00.

Please note that for every GPIO pin, a unique mode is selected through the MODER register. If this is set to "Input" (0b00), the Alternate Function is disconnected and won't work with external signals.


问:
How to centralize text vertically and horizontally in the square
I used some boxes in the website below with the title Products.I want to text vertically and horizontally be in the center in the boxes (Square).Already tried:

```<code>display:table-cell;
vertical-align: middle;
</code>```

but nothing happens at all. what should i do?

website: http://www.titanotrade.com.tr/

答:
Use the line-height property to adjust the position of the text in your boxes e.g.</p>

```<code>.title-product a {
    line-height: 270px;
}
</code>```

Body:
I used some boxes in the website below with the title Products.I want to text vertically and horizontally be in the center in the boxes (Square).Already tried:

display:table-cell;
vertical-align: middle;

but nothing happens at all. what should i do?

website: http://www.titanotrade.com.tr/

Body:
Use the line-height property to adjust the position of the text in your boxes e.g.

.title-product a {
    line-height: 270px;
}


问:
Statically typed open source cross platform modern programming language
May be it's a silly question. Is there an alternative to Java and .NET platform?

Which:

Is a programming language itself. Language ports unless they become dominant are not really successfull IMO.

May have it's own execution platform like JVM, which is a big plus. But interpreter is also ok.

Is statically typed.

Is open source and developed by open community.

Is cross platform like Java: compile once, run everywhere.

Is modern: multiparadigm (OOP and generic, functional is a plus), concurrent (at least allowing to write concurrently), garbage collection is a plus, reflection is a plus.

I'd be glad to know about unpopular or experimental languages which satisfy this criteria too. Dead languages are not ok.

A language for which all of the above (subjective) conditions is true probably falls in one of two categories

Statically typed interpreted language project. Which would provide cross platform interpreter and library.

Java-like language but with two distinctions: not being Java port and developed by community.

答: May be scala. It runs on JVM, it's statically typed. Lift is web framework developed in scala. I heard IDE support is not good. IntelliJ IDE may be best one to consider.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How do I get a phone number from firebase?
private func showCreateProfileVC() {</p>

```<code>    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let dvc = storyboard.instantiateViewController(withIdentifier: "CreateProfileVC") as! CreateProfileVC

    dvc.currentUser = Firebase.Auth // there's an error "Cannot assign value of type 'Auth.Type' to type 'User'"

    self.present(dvc, animated: true)

}
</code>```

答:
The error in your code here

```<code>// there's an error "Cannot assign value of type 'Auth.Type' to type 'User'"
dvc.currentUser = Firebase.Auth
</code>```

because you need to access the currentUser property of Firebase auth.

```<code>if let user = Auth.auth().currentUser {
   //do something with the user object
   dvc.currentUser = user

   //to get the current users uid
   let uid = user.uid
}
</code>```

Assume you are using the Real Time Database and have your users stored like this

```<code>users
   uid_0
      phone_number: "111-222-3333"
</code>```

and you want to retrieve the user with uid_0 phone number. Here's the code

```<code>func getUsersPhoneNumber() {
    let uid = //the current users uid from above
    self.ref.child("users").child(uid).observeSingleEvent(of: .value) { snapshot in
        let phone = snapshot.childSnapshot(forPath: "phone_number").value as? String ?? "No Number"
        print(phone)
    }
}
</code>```

and the output is

```<code>111-222-3333
</code>```

Body:
private func showCreateProfileVC() {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let dvc = storyboard.instantiateViewController(withIdentifier: "CreateProfileVC") as! CreateProfileVC

    dvc.currentUser = Firebase.Auth // there's an error "Cannot assign value of type 'Auth.Type' to type 'User'"

    self.present(dvc, animated: true)

}

Body:
The error in your code here

// there's an error "Cannot assign value of type 'Auth.Type' to type 'User'"
dvc.currentUser = Firebase.Auth

because you need to access the currentUser property of Firebase auth.

if let user = Auth.auth().currentUser {
   //do something with the user object
   dvc.currentUser = user

   //to get the current users uid
   let uid = user.uid
}

Assume you are using the Real Time Database and have your users stored like this

users
   uid_0
      phone_number: "111-222-3333"

and you want to retrieve the user with uid_0 phone number. Here's the code

func getUsersPhoneNumber() {
    let uid = //the current users uid from above
    self.ref.child("users").child(uid).observeSingleEvent(of: .value) { snapshot in
        let phone = snapshot.childSnapshot(forPath: "phone_number").value as? String ?? "No Number"
        print(phone)
    }
}

and the output is

111-222-3333


问:
Does DolphinDB support -inf and inf when dividing by 0 like numpy?
I know in Numpy, if it is divided by 0, it could become -inf or inf. In DolphinDB, if dividing by 0, it will turn into NULL, it is hard for me to tell if the value is just NULL or caused by 0 division. </p>

答: The current version of DolphinDB doesn't support INF.</p>


问:
Dice rolling program with counter
I'm new to programming and I have a task that I can't figure out on my own.

The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.

here is my code:

```<code>import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
    while True:
        numDices=int(input("How many dices to throw? (1-5) "))
        if numDices<1 or numDices>5:
            print("Wrong input, try again")
            break
        while True:
            if reset==True:
                break
            for i in range(numDices):
                dicesArray = list(range(numDices))
                dicesArray[i] = random.randint(1, 6)
                print(dicesArray[i])
                total += dicesArray[i]
                if dicesArray[i] == 1:
                    print("You rolled a one, the total is: ",str(total))
                elif dicesArray[i] == 2:
                    print("You rolled a two, the total is: ",str(total))
                elif dicesArray[i] == 3:
                    print("You rolled a three, the total is: ",str(total))
                elif dicesArray[i] == 4:
                    print("You rolled a four, the total is: ",str(total))
                elif dicesArray[i] == 5:
                    print("You rolled a five, the total is: ",str(total))
                elif dicesArray[i] == 6:
                    total-=6
                    numDices+=2
                    print("You rolled a six, rolling two new dices")
                    reset=True
        print("The total sum is",str(total),"with",numDices,"number of rolls.")
        print()
        restart=(input("Do you want to restart press Enter, to quit press 9. "))
        if restart=="9":
            exit=True
            break
        else:
            print()
            break
    if exit==True:
        break
</code>```

答:
You could do it the following way, slightly modifying your code, counting the available dices. I reduced the nested loops there too</p>

```<code>import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
    numDices=int(input("How many dices to throw? (1-5) "))
    if numDices<1 or numDices>5:
        print("Wrong input, try again")
        break
    total = 0
    dices_counter = 0
    while numDices > 0 :
        eyes = random.randint(1, 6)
        dices_counter+=1
        total += eyes
        if eyes == 1:
            print("You rolled a one, the total is: ",str(total))
            numDices-=1
        elif eyes == 2:
            print("You rolled a two, the total is: ",str(total))
            numDices-=1
        elif eyes == 3:
            print("You rolled a three, the total is: ",str(total))
            numDices-=1
        elif eyes == 4:
            print("You rolled a four, the total is: ",str(total))
            numDices-=1
        elif eyes == 5:
            print("You rolled a five, the total is: ",str(total))
            numDices-=1
        elif eyes == 6:
            total-=6
            numDices+=2
            print("You rolled a six, rolling two new dices")
    print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
    print()
    start=(input("Do you want to restart press Enter, to quit press 9. "))
    if start=="9":
        break
    else:
        print()
        start = True
</code>```

Title: Dice rolling program with counter

Body:
I'm new to programming and I have a task that I can't figure out on my own.

The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.

here is my code:

import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
    while True:
        numDices=int(input("How many dices to throw? (1-5) "))
        if numDices<1 or numDices>5:
            print("Wrong input, try again")
            break
        while True:
            if reset==True:
                break
            for i in range(numDices):
                dicesArray = list(range(numDices))
                dicesArray[i] = random.randint(1, 6)
                print(dicesArray[i])
                total += dicesArray[i]
                if dicesArray[i] == 1:
                    print("You rolled a one, the total is: ",str(total))
                elif dicesArray[i] == 2:
                    print("You rolled a two, the total is: ",str(total))
                elif dicesArray[i] == 3:
                    print("You rolled a three, the total is: ",str(total))
                elif dicesArray[i] == 4:
                    print("You rolled a four, the total is: ",str(total))
                elif dicesArray[i] == 5:
                    print("You rolled a five, the total is: ",str(total))
                elif dicesArray[i] == 6:
                    total-=6
                    numDices+=2
                    print("You rolled a six, rolling two new dices")
                    reset=True
        print("The total sum is",str(total),"with",numDices,"number of rolls.")
        print()
        restart=(input("Do you want to restart press Enter, to quit press 9. "))
        if restart=="9":
            exit=True
            break
        else:
            print()
            break
    if exit==True:
        break

Body:
You could do it the following way, slightly modifying your code, counting the available dices. I reduced the nested loops there too

import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
    numDices=int(input("How many dices to throw? (1-5) "))
    if numDices<1 or numDices>5:
        print("Wrong input, try again")
        break
    total = 0
    dices_counter = 0
    while numDices > 0 :
        eyes = random.randint(1, 6)
        dices_counter+=1
        total += eyes
        if eyes == 1:
            print("You rolled a one, the total is: ",str(total))
            numDices-=1
        elif eyes == 2:
            print("You rolled a two, the total is: ",str(total))
            numDices-=1
        elif eyes == 3:
            print("You rolled a three, the total is: ",str(total))
            numDices-=1
        elif eyes == 4:
            print("You rolled a four, the total is: ",str(total))
            numDices-=1
        elif eyes == 5:
            print("You rolled a five, the total is: ",str(total))
            numDices-=1
        elif eyes == 6:
            total-=6
            numDices+=2
            print("You rolled a six, rolling two new dices")
    print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
    print()
    start=(input("Do you want to restart press Enter, to quit press 9. "))
    if start=="9":
        break
    else:
        print()
        start = True


问:
Undefined return value using useState and firebase for objects in React Native
I'm writing an app using React Native and I came across an issue when trying to update an Object with the useState method. Here's my code:

```<code>const Screen = ({route}) => {

    var roomKey = route.params;

    const [room, setRoom] = useState({});
    db.ref('rooms').on('value', (data) => {
        setRoom(() => (data.val())[roomKey]);
    });

    console.log(room);

// rest of the code ...
</code>```

My code works as follows: first it takes a key outputted by another screen with react navigation, and then calls the firebase database with the ref method (db is defined as Firebase.initializeApp(config).database(), where config is the object with all the firebase datas needed). If I log out the data.val())[roomKey] it correctly outputs the object I'm downloading from database, however the room object is not updated by the useState method (it outputs undefined, making the following part of the code crash). What am I doing wrong?

答:
In your code, setRoom is a function to change the value of room state. So, you have to pass the value into the setRoom.

Please check the following code.

```<code>const Screen = ({route}) => {

    var roomKey = route.params;

    const [room, setRoom] = useState({});
    db.ref('rooms').on('value', (data) => {
        setRoom(data.val()[roomKey]);
    });

    console.log(room);

// rest of the code ...
</code>```

Body:
I'm writing an app using React Native and I came across an issue when trying to update an Object with the useState method. Here's my code:

const Screen = ({route}) => {

    var roomKey = route.params;

    const [room, setRoom] = useState({});
    db.ref('rooms').on('value', (data) => {
        setRoom(() => (data.val())[roomKey]);
    });

    console.log(room);

// rest of the code ...

My code works as follows: first it takes a key outputted by another screen with react navigation, and then calls the firebase database with the ref method (db is defined as Firebase.initializeApp(config).database(), where config is the object with all the firebase datas needed). If I log out the data.val())[roomKey] it correctly outputs the object I'm downloading from database, however the room object is not updated by the useState method (it outputs undefined, making the following part of the code crash). What am I doing wrong?

Body:
In your code, setRoom is a function to change the value of room state. So, you have to pass the value into the setRoom.

Please check the following code.

const Screen = ({route}) => {

    var roomKey = route.params;

    const [room, setRoom] = useState({});
    db.ref('rooms').on('value', (data) => {
        setRoom(data.val()[roomKey]);
    });

    console.log(room);

// rest of the code ...


问:
Decode case class, String or Int in circe
I use some Rest API responding with json containing a sort of "mixed" field. By mixed I mean that it can take values of a different type. In my case Object, String and Int are allowed. The Object itself consists of 1 Int and 1 String.

The object I need to decode looks as:

I

```<code>{
   field1: 32,
   ...
   value: {
      id: 23,
      text: "text"
   }
}
</code>```

II

```<code>{
   field1: 32,
   ...
   value: 21
}
</code>```

III

```<code>{
   field1: 32,
   ...
   value: "value"
}
</code>```

How to deal with such objects in circe?

答:
Let's say your case class would be:

```<code>@JsonCodec(decodeOnly = true)
case class X(id: Int, text: String)
</code>```

Then I could assume that your field would be of type:

```<code>type Mixed = X Either Int Either String
</code>```

decode for which could look like:

```<code>implicit val mixedDecoder: Decoder[Mixed] =
  Decoder[X].map[Mixed](x => Left(Left(x))) or Decoder[Int].map[Mixed](i => Left(Right(i))) or Decoder[String].map[Mixed](s => Right(s))
</code>```

You could derive codecs for Either if you define how they would be combined: left wins, right wins, or whatever you prefer:

```<code>implicit def eitherDecode[L: Decoder, R: Decoder]: Decoder[L Either R] =
  Decoder[L].map[L Either R](Left(_)) or Decoder[R].map[L Either R](Right(_))
</code>```

Alternatively, you can create your own ADT (sealed trait + case classes) and then writing handwritten decoder to avoid using discriminator field.

The bottom line is that you have to somehow express that polymorphism in the type you are decoding into (in a sane manner - Any doesn't count) and then provide a decoder that would decode into it. And then you could simply use it:

```<code>@JsonCodec(decodeOnly = true)
case class BigClass(field1: String, value: Mixed)
</code>```

Body:
I use some Rest API responding with json containing a sort of "mixed" field. By mixed I mean that it can take values of a different type. In my case Object, String and Int are allowed. The Object itself consists of 1 Int and 1 String.

The object I need to decode looks as:

I

{
   field1: 32,
   ...
   value: {
      id: 23,
      text: "text"
   }
}

II

{
   field1: 32,
   ...
   value: 21
}

III

{
   field1: 32,
   ...
   value: "value"
}

How to deal with such objects in circe?

Body:
Let's say your case class would be:

@JsonCodec(decodeOnly = true)
case class X(id: Int, text: String)

Then I could assume that your field would be of type:

type Mixed = X Either Int Either String

decode for which could look like:

implicit val mixedDecoder: Decoder[Mixed] =
  Decoder[X].map[Mixed](x => Left(Left(x))) or Decoder[Int].map[Mixed](i => Left(Right(i))) or Decoder[String].map[Mixed](s => Right(s))

You could derive codecs for Either if you define how they would be combined: left wins, right wins, or whatever you prefer:

implicit def eitherDecode[L: Decoder, R: Decoder]: Decoder[L Either R] =
  Decoder[L].map[L Either R](Left(_)) or Decoder[R].map[L Either R](Right(_))

Alternatively, you can create your own ADT (sealed trait + case classes) and then writing handwritten decoder to avoid using discriminator field.

The bottom line is that you have to somehow express that polymorphism in the type you are decoding into (in a sane manner - Any doesn't count) and then provide a decoder that would decode into it. And then you could simply use it:

@JsonCodec(decodeOnly = true)
case class BigClass(field1: String, value: Mixed)


问:
Using FetchContent_Declare together with CMAKE_ARGS
I'm using cmake v3.13 and I want to change my ExternalProject_Add() for the SEAL library to:

```<code>include(FetchContent)
# Get the seal library
set(SEAL "seal")
FetchContent_Declare(
        ${SEAL}
        GIT_REPOSITORY  https://github.com/microsoft/SEAL
        GIT_TAG         v3.5.2

)
FetchContent_GetProperties(${SEAL})
if(NOT ${SEAL}_POPULATED)
    FetchContent_Populate(${SEAL})
    add_subdirectory(${${SEAL}_SOURCE_DIR} ${${SEAL}_BINARY_DIR})
endif()
</code>```

When I was using ExternalProject_Add() I've used CMAKE_ARGS -DBUILD_SHARED_LIBS=ON and this doesn't work with FetchContent_Declare() that only downloads the library.

The SEAL v3.5.2 CMakeLists.txt uses this to check if a shared library needs to be built:

```<code># Should we build also the shared library?
set(BUILD_SHARED_LIBS_STR "Build shared library")
option(BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS_STR} OFF)
if(MSVC AND BUILD_SHARED_LIBS)
    message(WARNING "This build system only supports a static build; disabling `BUILD_SHARED_LIBS`")
    set(BUILD_SHARED_LIBS OFF CACHE BOOL ${BUILD_SHARED_LIBS_STR} FORCE)
endif()

# Conditionally build the shared library
if(BUILD_SHARED_LIBS)
    add_library(seal_shared SHARED $<TARGET_OBJECTS:seal_obj>)
    set_target_properties(seal_shared PROPERTIES OUTPUT_NAME seal)
    seal_set_version(seal_shared)
    seal_set_soversion(seal_shared)
    seal_set_language(seal_shared)
    seal_set_include_directories(seal_shared)
    seal_link_threads(seal_shared)

    # Conditionally add MSGSL include directory to build interface
    if(SEAL_USE_MSGSL AND NOT MSVC)
        target_include_directories(seal_shared PUBLIC $<BUILD_INTERFACE:${MSGSL_INCLUDE_DIR}>)
    endif()

    if(SEAL_USE_ZLIB AND NOT MSVC)
        # In the shared build we link zlibstatic into the shared library
        target_link_libraries(seal_shared PRIVATE zlibstatic)
    endif()

    seal_install_target(seal_shared SEALTargets)
endif()

</code>```

Is there a way to download the SEAL library using FetchContent_Declare() and then use some CMakeLists setting to pass the CMAKE_ARGS -DBUILD_SHARED_LIBS=ON argument to the downloaded library when building it?

答:
When build some project at the top-level, you may pass a parameter to it using command line option

```<code>-D<VARIABLE>=<VALUE>
</code>```

(ExternalProject_Add builds the project "as if" top-level, so the option passing is technically the same).

When build some project as a subproject using add_subdirectory approach, you may use the same command line option

```<code>-D<VARIABLE>=<VALUE>
</code>```

for top-level project, and this parameter will be propagated to the subproject too.

If passing the parameter to the top-level project is not desired, then you may emulate the parameter setting inside CMakeLists.txt using set(CACHE INTERNAL) command flow:

```<code>set(<PARAMETER> <VALUE> CACHE INTERNAL "<some description>")
</code>```

Make sure this line is issued before add_subdirectory() call (otherwise it won't affect the subproject).

So in your case you may use following code:

```<code>if(NOT ${SEAL}_POPULATED)
    FetchContent_Populate(${SEAL})
    # Make subproject to use 'BUILD_SHARED_LIBS=ON' setting.
    set(BUILD_SHARED_LIBS ON CACHE INTERNAL "Build SHARED libraries")
    add_subdirectory(${${SEAL}_SOURCE_DIR} ${${SEAL}_BINARY_DIR})
endif()
</code>```

All above works perfectly when top-level project doesn't use the parameter set for subproject.

If both top-level project and subproject are affected by the same parameter, and you want to hardcode the parameter for the subdproject only, then things become more complicated. You need to restore the parameter after add_subdirectory call:

```<code>if(NOT ${SEAL}_POPULATED)
    FetchContent_Populate(${SEAL})

    # Store the old value of the 'BUILD_SHARED_LIBS'
    set(BUILD_SHARED_LIBS_OLD ${BUILD_SHARED_LIBS})
    # Make subproject to use 'BUILD_SHARED_LIBS=ON' setting.
    set(BUILD_SHARED_LIBS ON CACHE INTERNAL "Build SHARED libraries")

    add_subdirectory(${${SEAL}_SOURCE_DIR} ${${SEAL}_BINARY_DIR})

    # Restore the old value of the parameter
    set(BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS_OLD} CACHE BOOL "Type of libraries to build" FORCE)
endif()

# ...

# The library will be created according to "original" value for BUILD_SHARED_LIBS option.
add_library(top_lib top_lib.c)
</code>```

Note, that in case of restoring parameter, set(CACHE TYPE FORCE) command flow is used instead of set(CACHE INTERNAL). This restores not only a value of the CACHE variable, but also its type, which is shown in CMake GUI.

Body:
I'm using cmake v3.13 and I want to change my ExternalProject_Add() for the SEAL library to:

include(FetchContent)
# Get the seal library
set(SEAL "seal")
FetchContent_Declare(
        ${SEAL}
        GIT_REPOSITORY  https://github.com/microsoft/SEAL
        GIT_TAG         v3.5.2

)
FetchContent_GetProperties(${SEAL})
if(NOT ${SEAL}_POPULATED)
    FetchContent_Populate(${SEAL})
    add_subdirectory(${${SEAL}_SOURCE_DIR} ${${SEAL}_BINARY_DIR})
endif()

When I was using ExternalProject_Add() I've used CMAKE_ARGS -DBUILD_SHARED_LIBS=ON and this doesn't work with FetchContent_Declare() that only downloads the library.

The SEAL v3.5.2 CMakeLists.txt uses this to check if a shared library needs to be built:

# Should we build also the shared library?
set(BUILD_SHARED_LIBS_STR "Build shared library")
option(BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS_STR} OFF)
if(MSVC AND BUILD_SHARED_LIBS)
    message(WARNING "This build system only supports a static build; disabling `BUILD_SHARED_LIBS`")
    set(BUILD_SHARED_LIBS OFF CACHE BOOL ${BUILD_SHARED_LIBS_STR} FORCE)
endif()

# Conditionally build the shared library
if(BUILD_SHARED_LIBS)
    add_library(seal_shared SHARED $<TARGET_OBJECTS:seal_obj>)
    set_target_properties(seal_shared PROPERTIES OUTPUT_NAME seal)
    seal_set_version(seal_shared)
    seal_set_soversion(seal_shared)
    seal_set_language(seal_shared)
    seal_set_include_directories(seal_shared)
    seal_link_threads(seal_shared)

    # Conditionally add MSGSL include directory to build interface
    if(SEAL_USE_MSGSL AND NOT MSVC)
        target_include_directories(seal_shared PUBLIC $<BUILD_INTERFACE:${MSGSL_INCLUDE_DIR}>)
    endif()

    if(SEAL_USE_ZLIB AND NOT MSVC)
        # In the shared build we link zlibstatic into the shared library
        target_link_libraries(seal_shared PRIVATE zlibstatic)
    endif()

    seal_install_target(seal_shared SEALTargets)
endif()

Is there a way to download the SEAL library using FetchContent_Declare() and then use some CMakeLists setting to pass the CMAKE_ARGS -DBUILD_SHARED_LIBS=ON argument to the downloaded library when building it?

Body:
When build some project at the top-level, you may pass a parameter to it using command line option

-D<VARIABLE>=<VALUE>

(ExternalProject_Add builds the project "as if" top-level, so the option passing is technically the same).

When build some project as a subproject using add_subdirectory approach, you may use the same command line option

-D<VARIABLE>=<VALUE>

for top-level project, and this parameter will be propagated to the subproject too.

If passing the parameter to the top-level project is not desired, then you may emulate the parameter setting inside CMakeLists.txt using set(CACHE INTERNAL) command flow:

set(<PARAMETER> <VALUE> CACHE INTERNAL "<some description>")

Make sure this line is issued before add_subdirectory() call (otherwise it won't affect the subproject).

So in your case you may use following code:

if(NOT ${SEAL}_POPULATED)
    FetchContent_Populate(${SEAL})
    # Make subproject to use 'BUILD_SHARED_LIBS=ON' setting.
    set(BUILD_SHARED_LIBS ON CACHE INTERNAL "Build SHARED libraries")
    add_subdirectory(${${SEAL}_SOURCE_DIR} ${${SEAL}_BINARY_DIR})
endif()

All above works perfectly when top-level project doesn't use the parameter set for subproject.

If both top-level project and subproject are affected by the same parameter, and you want to hardcode the parameter for the subdproject only, then things become more complicated. You need to restore the parameter after add_subdirectory call:

if(NOT ${SEAL}_POPULATED)
    FetchContent_Populate(${SEAL})

    # Store the old value of the 'BUILD_SHARED_LIBS'
    set(BUILD_SHARED_LIBS_OLD ${BUILD_SHARED_LIBS})
    # Make subproject to use 'BUILD_SHARED_LIBS=ON' setting.
    set(BUILD_SHARED_LIBS ON CACHE INTERNAL "Build SHARED libraries")

    add_subdirectory(${${SEAL}_SOURCE_DIR} ${${SEAL}_BINARY_DIR})

    # Restore the old value of the parameter
    set(BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS_OLD} CACHE BOOL "Type of libraries to build" FORCE)
endif()

# ...

# The library will be created according to "original" value for BUILD_SHARED_LIBS option.
add_library(top_lib top_lib.c)

Note, that in case of restoring parameter, set(CACHE TYPE FORCE) command flow is used instead of set(CACHE INTERNAL). This restores not only a value of the CACHE variable, but also its type, which is shown in CMake GUI.


问:
How do I get an asynchronous TCP object stream in C#?
I'm pretty new to serialization so please bear with me.

I want two instances of my application to communicate with each other over the internet.  I have successfully rigged up a TCP client/server relationship and used a binary formatter to get the two sides to swap a single pair of messages.  Here's the client side...

```<code>using (TcpClient clientSocket = new TcpClient(ipAddress, currentPort))
{
    using (NetworkStream stream = clientSocket.GetStream())
    {
        // send
        bformatter.Serialize(stream, new Message());

        // recv
        return (Message)bformatter.Deserialize(stream);
    }
}
</code>```

It's cool, but not very useful for an application that needs to send messages in response to user events.  So I need to be able to send and receive asynchronously.

I basically want an interface that behaves like this:

```<code>class BidirectionalObjectStream
{
    public BidirectionalObjectStream(TcpClient client)
    {
        //...
    }

    // objects go in here
    public void SendObject(object o)
    {
        //...
    }

    // objects come out here
    public event Action<object> ObjectReceived;
}
</code>```

Is there a class like this that's part of .NET?  If not, how should I implement the receive event?  Maybe a dedicated thread calling bformatter.Deserialize() repeatedly...?

Any help appreciated.

答:
The question is a little broad.

I can think of two options:

Use asynchronous socket. Using an Asynchronous Client Socket

Create separate threads for receiving and sending. There many ways to achieve it, raw Thread, ThreadPool, delegate.Invoke, new TPL features like Task and Parallel.

Body:
I'm pretty new to serialization so please bear with me.

I want two instances of my application to communicate with each other over the internet.  I have successfully rigged up a TCP client/server relationship and used a binary formatter to get the two sides to swap a single pair of messages.  Here's the client side...

using (TcpClient clientSocket = new TcpClient(ipAddress, currentPort))
{
    using (NetworkStream stream = clientSocket.GetStream())
    {
        // send
        bformatter.Serialize(stream, new Message());

        // recv
        return (Message)bformatter.Deserialize(stream);
    }
}

It's cool, but not very useful for an application that needs to send messages in response to user events.  So I need to be able to send and receive asynchronously.

I basically want an interface that behaves like this:

class BidirectionalObjectStream
{
    public BidirectionalObjectStream(TcpClient client)
    {
        //...
    }

    // objects go in here
    public void SendObject(object o)
    {
        //...
    }

    // objects come out here
    public event Action<object> ObjectReceived;
}

Is there a class like this that's part of .NET?  If not, how should I implement the receive event?  Maybe a dedicated thread calling bformatter.Deserialize() repeatedly...?

Any help appreciated.


问:
how to improve Max Potential First Input Delay when you have no javascript?
Chrome Lighthouse is telling me that to improve my performance I need to decrease my Max Potential First Input Delay (as it calls it). I searched how to improve it but I only found things related to javascript and my page is only using html and css (no javascript). Please can someone tell me how to improve it?
( I already minified my html and css ) </p>

答:
Without seeing source it's hard to pinpoint exactly, but from my experience the following can be used to improve Potential First Input Delay scores:

Analytics scripts had a huge impact when loaded in the header.

Deferring CSS loading can return huge rewards, but you need to weigh this up against any undesirable Flashes of Unstyled Content.

Usage of rel="preload" to any external assets (images/fonts are prime culprits).

Good luck.


问:
Vertically Assignment of Block in Page
I am learning DJANGO and while proceeding wanted to give nice look to some pages. I am currently new in programming (only 4 months coding) and mostly spent time with Python, could find time to properly learn front-end.

So my problem is I can`t center LOGIN block in the page. I am using Bootstrap4.5 and gave some Shadow to make object like floating. I now there were similar questions here with answers and tons of tutorial of centering elements either with custom CSS or Bootstrap Flex or Justify and I really tried almost everything I found with no result. Every time time position of Block is getting somewhere else but not center.

My Base HTML:

```<code><!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
          integrity="sha384-
          9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
          crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'css/base.css' %}">

    <title>Newspaper Project</title>
  </head>

  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
      <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse"
          data-target="#navbarCollapse" aria-controls="navbarCollapse"
          aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarCollapse">
        {% if user.is_authenticated %}
          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              <a class="nav-link dropdown-toggle" href="#" id="userMenu"
                data-toggle="dropdown" aria-haspopup="true"
                aria-expanded="false">
                {{ user.username }}
              </a>
              <div class="dropdown-menu dropdown-menu-right"
                aria-labelledby="userMenu">
                <a class="dropdown-item" href="{% url 'password_change'%}">Change
                                                                           password</a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="{% url 'logout' %}">Log Out</a>
              </div>
            </li>
          </ul>
        {% else %}
          <form class="form-inline ml-auto">
            <a href="{% url 'login' %}" class="btn btn-outline-secondary">Log In</a>
            <a href="{% url 'users:signup' %}" class="btn btn-outline-info ml-2">Sign up</a>
          </form>
        {% endif %}
      </div>
    </nav>

<div class="container">
  {% block content %}

  {% endblock %}
</div>

<!-- JAVASCRIPT BOOTSTRAP -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

  </body>
</html>
</code>```

My Login HTML:

```<code>{% extends "base.html" %}

{% load crispy_forms_tags %}

{% block content %}

  {% if user.is_authenticated %}
    <h2>You are already logged in!</h2>
    <a href="{% url 'logout' %}">Log Out</a>
  {% else %}
      <form class="shadow-lg p-3 mb-5 bg-white rounded login" method="post">
        {% csrf_token %}
        {{ form|crispy }}
        <button class="btn btn-success" type="submit">Log In</button>
      </form>
  {% endif %}

{% endblock %}
</code>```

And attached image how the page is looking.
I really dont know what else I can try to center the login block. All I want is to center it below navbar in remaining space.

Thanks in advance!

答:
You can use text-align attribute for this as following.

```<code><div style="text-align:center"><form id="form_login"><!--form content here--></form></div>
</code>```

This will center all the content inside the parent DIV. An optional way is to use margin: auto CSS attribute with predefined widths and heights. Please follow the following thread for more information.

Title: Vertically Assignment of Block in Page

Body:
I am learning DJANGO and while proceeding wanted to give nice look to some pages. I am currently new in programming (only 4 months coding) and mostly spent time with Python, could find time to properly learn front-end.

So my problem is I can`t center LOGIN block in the page. I am using Bootstrap4.5 and gave some Shadow to make object like floating. I now there were similar questions here with answers and tons of tutorial of centering elements either with custom CSS or Bootstrap Flex or Justify and I really tried almost everything I found with no result. Every time time position of Block is getting somewhere else but not center.

My Base HTML:

<!DOCTYPE html>
{% load static %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
          integrity="sha384-
          9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
          crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'css/base.css' %}">

    <title>Newspaper Project</title>

      Newspaper
      <button class="navbar-toggler" type="button" data-toggle="collapse"
          data-target="#navbarCollapse" aria-controls="navbarCollapse"
          aria-expanded="false" aria-label="Toggle navigation">

      </button>

        {% if user.is_authenticated %}

                {{ user.username }}

                Change
                                                                           password

                Log Out

        {% else %}
          <form class="form-inline ml-auto">
            Log In
            Sign up
          </form>
        {% endif %}

  {% block content %}

  {% endblock %}

My Login HTML:

{% extends "base.html" %}

{% load crispy_forms_tags %}

{% block content %}

  {% if user.is_authenticated %}

You are already logged in!

    Log Out
  {% else %}
      <form class="shadow-lg p-3 mb-5 bg-white rounded login" method="post">
        {% csrf_token %}
        {{ form|crispy }}
        <button class="btn btn-success" type="submit">Log In</button>
      </form>
  {% endif %}

{% endblock %}

And attached image how the page is looking.
I really dont know what else I can try to center the login block. All I want is to center it below navbar in remaining space.

Thanks in advance!

Body:
You can use text-align attribute for this as following.

<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>

This will center all the content inside the parent DIV. An optional way is to use margin: auto CSS attribute with predefined widths and heights. Please follow the following thread for more information.


问:
JavaFx Exception in Application start method and Exception in Application start method
I have created this javaFx class to shuffle and show play cards in different angles. But Suddenly I got an error. I tried to fix it but I still couldn't able to make it work. Code explanation is given with the code below.
The program supposes to pick random png card images and display on the first row. The second row shows three joker cards in different angles. The third row shows another three different cards in 3 different angles

The code:

```<code>import java.util.ArrayList;
import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

//Creating class JavaFXCardGUI which is extending Application class
//Now JavaFXCardGUI class will act as an JavaFX Application
public class JavaFXCards extends Application{

   //Overriding start method of Application class which is always a starting point of any JavaFX Application
   @Override
   public void start(Stage stage) throws Exception {

       //Creating a VBox object
       VBox vBox=new VBox();
       //Setting its spacing and padding
       vBox.setSpacing(50);
       vBox.setPadding(new Insets(20, 40, 40, 60));

       //Creating a HBox object which will store the first row cards and setting its spacing property
       HBox firstRowHBox=new HBox();
       firstRowHBox.setSpacing(50);

       //Creating a HBox object which will store the second row cards and setting its spacing property
       HBox secondRowHBox=new HBox();
       secondRowHBox.setSpacing(50);

       //Creating a HBox object which will store the third row cards and setting its spacing property
       HBox thirdRowHBox=new HBox();
       thirdRowHBox.setSpacing(50);

       //Creating a arraylist of unique 52 cards which will store the each card number
       //If that card number will be already present in the arraylist then that card will not be added
       ArrayList<Integer> lstUnique52Cards=new ArrayList<Integer>();

       //Creating a random class object
       Random random=new Random();

      //This loop will add the three cards in first row
       while(lstUnique52Cards.size()<3) {
           //Generate a randomNumber between 1 and 52 both inclusive
           //Since random.NextInt(52) will return number from 0 to 51 Hence adding 1 to
           //make it from 1 to 52
           int randomNumber=random.nextInt(52)+1;

           //If the current random generated is not present in the array list lstUnique52Cards
           //it means that the random number is unique then add that random number in array list lstUnique52Cards
           //then create the correpsonding ImageView with the card number represented by randomNumber
           //Then add the image to the firstRowHBox
           if(!lstUnique52Cards.contains(randomNumber)) {
               lstUnique52Cards.add(randomNumber);
               ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
               firstRowHBox.getChildren().add(imgViewCard);
           }
       }

      //This loop will add the three joker cards in second row
       //Here the uniqueness doesn't matter for the card
       for(int i=1;i<=3;i++) {
           //Below statement random.nextInt(2) will generate two random numbers 0 and 1 only as we are having
           //only two joker cards. Since two joker cards images number are 53.png and 54.png.
           //Hence adding 53 to get that correpsonding joker card number
           int randomNumber=random.nextInt(2)+53;

           //Creating ImageView object with the given card number image
           ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));

           //If the value of i is 1 i.e. it is first card then set the rotation angle as 45
           if(i==1)
               imgViewCard.setRotate(45);

           //If the value of i is 2 i.e. it is second card then set the rotation angle as 90
           if(i==2)
               imgViewCard.setRotate(90);

           //If the value of i is 3 i.e. it is third card then set the rotation angle as 135
           if(i==3)
               imgViewCard.setRotate(135);

           //Add the imgViewCard in secondRowHBox
           secondRowHBox.getChildren().add(imgViewCard);
       }

       //This loop will add the three more unique cards
       //Initializing cardNumber with 1
       int cardNumber=1;
       while(lstUnique52Cards.size()<6) {
           //Generate a randomNumber between 1 and 52 both inclusive
           //Since random.NextInt(52) will return number from 0 to 51 Hence adding 1 to
           //make it from 1 to 52
           int randomNumber=random.nextInt(52)+1;

           //If the current random generated is not present in the array list lstUnique52Cards
           //it means that the random number is unique then add that random number in array list lstUnique52Cards
           //then create the correpsonding ImageView with the card number represented by randomNumber
           //Also set the correpsonding angle to the cardNumber of this thirdRowHBox
           //Then add the image view card to the thirdRowHBox
           if(!lstUnique52Cards.contains(randomNumber)) {
               lstUnique52Cards.add(randomNumber);
               ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
               if(cardNumber==1)
                   imgViewCard.setRotate(135);
               if(cardNumber==2)
                   imgViewCard.setRotate(90);
               if(cardNumber==3)
                   imgViewCard.setRotate(45);
               thirdRowHBox.getChildren().add(imgViewCard);
               cardNumber++; //Increment cardNumber by 1
           }
       }

       //Add all the three HBox objects in the vBox
       vBox.getChildren().add(firstRowHBox);
       vBox.getChildren().add(secondRowHBox);
       vBox.getChildren().add(thirdRowHBox);

       //Create a scene object with the child as vBox
       Scene scene = new Scene(vBox ,450, 450);

       //Setting the stage title as Cards
       stage.setTitle("Cards");

       //Setting the scene to the stage
       stage.setScene(scene);

       //Showing the stage
       stage.show();
   }

   //Main method it will invoke start method of Application class
   public static void main(String[] args) {
       launch(args);
   }
}
</code>```

The error:

```<code>ant -f c:\Users\Desktop\Tempory\card jfxsa-run
init:
Deleting: c:\Users\Desktop\Tempory\card\build\built-jar.properties
deps-jar:
Updating property file: c:\Users\Desktop\Tempory\card\build\built-jar.properties
compile:
Detected JavaFX Ant API version 1.3
jfx-deployment:
jar:
Copying 12 files to c:\Users\Desktop\Tempory\card\dist\run395293642
jfx-project-run:
Executing c:\Users\Desktop\Tempory\card\dist\run395293642\JavaFXCards.jar using platform C:\Program Files\Java\jdk1.8.0_221\jre/bin/java
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
    at javafx.scene.image.Image.validateUrl(Image.java:1121)
    at javafx.scene.image.Image.<init>(Image.java:620)
    at JavaFXCardGUI.start(JavaFXCardGUI.java:58)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$3(WinApplication.java:177)
    ... 1 more
Caused by: java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:607)
    at java.net.URL.<init>(URL.java:497)
    at java.net.URL.<init>(URL.java:446)
    at javafx.scene.image.Image.validateUrl(Image.java:1115)
    ... 11 more
Exception running application JavaFXCardGUI
Java Result: 1
Deleting directory c:\Users\Desktop\Tempory\card\dist\run395293642
jfxsa-run:
BUILD SUCCESSFUL (total time: 2 seconds)
</code>```

答:
MalformedURLException - you provided a wrong URL string; all you need to do is prepend "file:" before the path to your image, like this - new Image("file:c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png").
Remember to always prefix local file paths with the file: protocol.

Body:
I have created this javaFx class to shuffle and show play cards in different angles. But Suddenly I got an error. I tried to fix it but I still couldn't able to make it work. Code explanation is given with the code below.
The program supposes to pick random png card images and display on the first row. The second row shows three joker cards in different angles. The third row shows another three different cards in 3 different angles

The code:

import java.util.ArrayList;
import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

//Creating class JavaFXCardGUI which is extending Application class
//Now JavaFXCardGUI class will act as an JavaFX Application
public class JavaFXCards extends Application{

   //Overriding start method of Application class which is always a starting point of any JavaFX Application
   @Override
   public void start(Stage stage) throws Exception {

       //Creating a VBox object
       VBox vBox=new VBox();
       //Setting its spacing and padding
       vBox.setSpacing(50);
       vBox.setPadding(new Insets(20, 40, 40, 60));

       //Creating a HBox object which will store the first row cards and setting its spacing property
       HBox firstRowHBox=new HBox();
       firstRowHBox.setSpacing(50);

       //Creating a HBox object which will store the second row cards and setting its spacing property
       HBox secondRowHBox=new HBox();
       secondRowHBox.setSpacing(50);

       //Creating a HBox object which will store the third row cards and setting its spacing property
       HBox thirdRowHBox=new HBox();
       thirdRowHBox.setSpacing(50);

       //Creating a arraylist of unique 52 cards which will store the each card number
       //If that card number will be already present in the arraylist then that card will not be added
       ArrayList<Integer> lstUnique52Cards=new ArrayList<Integer>();

       //Creating a random class object
       Random random=new Random();

      //This loop will add the three cards in first row
       while(lstUnique52Cards.size()<3) {
           //Generate a randomNumber between 1 and 52 both inclusive
           //Since random.NextInt(52) will return number from 0 to 51 Hence adding 1 to
           //make it from 1 to 52
           int randomNumber=random.nextInt(52)+1;

           //If the current random generated is not present in the array list lstUnique52Cards
           //it means that the random number is unique then add that random number in array list lstUnique52Cards
           //then create the correpsonding ImageView with the card number represented by randomNumber
           //Then add the image to the firstRowHBox
           if(!lstUnique52Cards.contains(randomNumber)) {
               lstUnique52Cards.add(randomNumber);
               ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
               firstRowHBox.getChildren().add(imgViewCard);
           }
       }

      //This loop will add the three joker cards in second row
       //Here the uniqueness doesn't matter for the card
       for(int i=1;i<=3;i++) {
           //Below statement random.nextInt(2) will generate two random numbers 0 and 1 only as we are having
           //only two joker cards. Since two joker cards images number are 53.png and 54.png.
           //Hence adding 53 to get that correpsonding joker card number
           int randomNumber=random.nextInt(2)+53;

           //Creating ImageView object with the given card number image
           ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));

           //If the value of i is 1 i.e. it is first card then set the rotation angle as 45
           if(i==1)
               imgViewCard.setRotate(45);

           //If the value of i is 2 i.e. it is second card then set the rotation angle as 90
           if(i==2)
               imgViewCard.setRotate(90);

           //If the value of i is 3 i.e. it is third card then set the rotation angle as 135
           if(i==3)
               imgViewCard.setRotate(135);

           //Add the imgViewCard in secondRowHBox
           secondRowHBox.getChildren().add(imgViewCard);
       }

       //This loop will add the three more unique cards
       //Initializing cardNumber with 1
       int cardNumber=1;
       while(lstUnique52Cards.size()<6) {
           //Generate a randomNumber between 1 and 52 both inclusive
           //Since random.NextInt(52) will return number from 0 to 51 Hence adding 1 to
           //make it from 1 to 52
           int randomNumber=random.nextInt(52)+1;

           //If the current random generated is not present in the array list lstUnique52Cards
           //it means that the random number is unique then add that random number in array list lstUnique52Cards
           //then create the correpsonding ImageView with the card number represented by randomNumber
           //Also set the correpsonding angle to the cardNumber of this thirdRowHBox
           //Then add the image view card to the thirdRowHBox
           if(!lstUnique52Cards.contains(randomNumber)) {
               lstUnique52Cards.add(randomNumber);
               ImageView imgViewCard=new ImageView(new Image("c:\\Users\\Desktop\\Tempory\\card"+randomNumber+".png"));
               if(cardNumber==1)
                   imgViewCard.setRotate(135);
               if(cardNumber==2)
                   imgViewCard.setRotate(90);
               if(cardNumber==3)
                   imgViewCard.setRotate(45);
               thirdRowHBox.getChildren().add(imgViewCard);
               cardNumber++; //Increment cardNumber by 1
           }
       }

       //Add all the three HBox objects in the vBox
       vBox.getChildren().add(firstRowHBox);
       vBox.getChildren().add(secondRowHBox);
       vBox.getChildren().add(thirdRowHBox);

       //Create a scene object with the child as vBox
       Scene scene = new Scene(vBox ,450, 450);

       //Setting the stage title as Cards
       stage.setTitle("Cards");

       //Setting the scene to the stage
       stage.setScene(scene);

       //Showing the stage
       stage.show();
   }

   //Main method it will invoke start method of Application class
   public static void main(String[] args) {
       launch(args);
   }
}

The error:

ant -f c:\Users\Desktop\Tempory\card jfxsa-run
init:
Deleting: c:\Users\Desktop\Tempory\card\build\built-jar.properties
deps-jar:
Updating property file: c:\Users\Desktop\Tempory\card\build\built-jar.properties
compile:
Detected JavaFX Ant API version 1.3
jfx-deployment:
jar:
Copying 12 files to c:\Users\Desktop\Tempory\card\dist\run395293642
jfx-project-run:
Executing c:\Users\Desktop\Tempory\card\dist\run395293642\JavaFXCards.jar using platform C:\Program Files\Java\jdk1.8.0_221\jre/bin/java
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
    at javafx.scene.image.Image.validateUrl(Image.java:1121)
    at javafx.scene.image.Image.<init>(Image.java:620)
    at JavaFXCardGUI.start(JavaFXCardGUI.java:58)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$3(WinApplication.java:177)
    ... 1 more
Caused by: java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:607)
    at java.net.URL.<init>(URL.java:497)
    at java.net.URL.<init>(URL.java:446)
    at javafx.scene.image.Image.validateUrl(Image.java:1115)
    ... 11 more
Exception running application JavaFXCardGUI
Java Result: 1
Deleting directory c:\Users\Desktop\Tempory\card\dist\run395293642
jfxsa-run:
BUILD SUCCESSFUL (total time: 2 seconds)


问:
How to build a fully secure login: do I need SSL?

context

I'm building a project to better understand login/security, and SSL is really tripping me up.
So far I have a front end (vue.js), an API (node/express), and a DB (postgreSQL).

This is the general auth flow:

When a user logs in they send an email and password (via Axios) to the API.

The API queries the database for a matching username and then using bcrypt.compare it checks the password that is hashed in the database.

If this is successful, the API signs a JWT and sends it to the client.

The client then saves the JWT in local storage and is used for future queries.

question(s)

So far I think that all of the above is the best practice EXCEPT for the first step. From the reading, I've done so far the client needs SSL to securely send a password to the API. Is this the case? Does my server also need to be SSL or just the client/host?

I'm ultimately going to try to use firebase hosting (which is automatically SSL) for the frontend, and heroku for the API and database. If there are more secure options I'm open to suggestions.

Also, in general, I'm new to all of this security stuff - If I'm missing anything or if something else isn't secure, I would love the advice!

答:
SSL creates a secure connection between two points. In our scenario between the client, and the server. After some initial negotiation, the client encrypts its messages in a way that only the server can decrypt. And the server does the same with its answers, or its own questions.  By using SSL between these two end points, nobody but the client and server can read the messages.

This is important, since a message sent between client and server is actually seen by many more machines/processes in between. Dozens of other processes can thus see the message, and if the message is not encrypted that means all those processes can know exactly what's in the message. When the client and server communicate over SSL, the other processes still see the messages, but they can't decrypt them.

To your concrete questions: the client opens a secure connection to the server. Both the client and the server need to support this. If you write a custom server, that means you'll need to ensure it has a SSL certificate. A very common place to get these for free these days is letsencrypt.org.


问:
How should I set the replication factor in Cassandra to account for node failure?
Lets say we have a cassandra deployment with a replication factor of 2. By this I mean that we can tolerate the total loss of one node of persistent storage without overall data loss. I understand this to mean that each of the values are stored on at least two different nodes at any given time. Therefore the total storage required is at least the total data of the values x 2. Ie, if we need to store 100TB in the cluster, we would need at least 200TB persistent storage across the nodes.

However, as the node count increases, so does the likelyhood of more than 1 node failing. Therefore, do we need to increase the replication factor as the number of nodes increases?

For example:

Lets assume that all components are 100% reliable, except for my nodes local storage controllers, which for time to time completely corrupt all local storage with no possibility for restoration (ie, data loss is total). All rack equipment, switches, power, cooling etc are all perfect. I know this is not realistic.

Lets also assume that any data loss is really, really bad for this application.

Lets say my nodes have 1TB each of storage. For 100TB of values, I would need 200 machines to achieve a replication factor of 2 (ie, I can lose any one node and still retain data). However, if I believe that the simultaneous failure of 2 nodes in that set of 200 is likely I will need to raise the replication factor to 3. Therefore now I need three copies of each value (on three different nodes) and now I need 300 nodes. I now feel that the simultaneous loss of 3 or more nodes is likely, so I have to add more nodes again, etc...

Surely this isn't actually how this scales? What is wrong with my logic?

答:
There are several types of failures that you need to take into account:

Individual node failure (hardware/os/...) - your node is failed, either completely (data is lost), or partially (for example, power adapter has failed)

Rack/data center failure - when nodes in specific part of data center, or data center completely failed, or not available over network

Replication helps to avoid complete data unavailability, but it may also depend on the deployment strategy.

For example, if all your servers in one data center, if it's not available, you'll lose access to the data. Or if you didn't setup cluster to have rack-aware data placement, replicas could be put into the same rack, and if it's going down, you lose your replica.

Typically, it's recommended to use replication factor 3, and if you're planning big deployment, definitely use rack-aware data placement - but you should be careful, so number of racks should match RF (in cloud deployments, usually the rack is mapped to the availability zone).

Availability is also depends on your business requirements - in simplest case, if you use  consistency levels ONE or LOCAL_ONE, your data is available even only one replica is available, but if your business logic requires stronger consistency, you need to have more replicas available. And replication factor also affects the consistency levels - if you use RF=2, and require CL=QUORUM, you can't tolerate single node failure, while it's possible to achieve that CL with RF=3 and one node failed.


问:
Unable to load staticfiles after deploying django app on aws-ec2
I am a beginner in aws and I am trying to deploy a django app on aws-ec2. I have set-up gunicorn application server and nginx web server and app loads but without static files. I have followed many answers on stackoverflow but I am unable to fix my problem.

I tried with both root and alias but they didn't work. The project structure is as follows:-
/home/ubuntu/myskillhut/

django.conf(nginx configuration file)

```<code>server {
        ...

        location / {
                include proxy_params;
                proxy_pass http://unix:/home/ubuntu/myskillhut/app.sock;
        }

        location /static/ {
                autoindex on;
                alias /home/ubuntu/myskillhut/static/;
        }
}
</code>```

settings.py

```<code>...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"), )
...
</code>```

答:
Configuration below works for my project

```<code>location ~* \.(jpe?g|gif|png)$ {
    root /home/ubuntu/myskillhut/static/;
    expires 1M;
}

location ~* \.(css|js)$ {
    root /home/ubuntu/myskillhut/static/;
    expires 1d;
}
</code>```

Also, make sure nginx can access those files in that dir (../static/)

Body:
I am a beginner in aws and I am trying to deploy a django app on aws-ec2. I have set-up gunicorn application server and nginx web server and app loads but without static files. I have followed many answers on stackoverflow but I am unable to fix my problem.

I tried with both root and alias but they didn't work. The project structure is as follows:-
/home/ubuntu/myskillhut/

django.conf(nginx configuration file)

server {
        ...

        location / {
                include proxy_params;
                proxy_pass http://unix:/home/ubuntu/myskillhut/app.sock;
        }

        location /static/ {
                autoindex on;
                alias /home/ubuntu/myskillhut/static/;
        }
}

settings.py

...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"), )
...

Body:
Configuration below works for my project

location ~* \.(jpe?g|gif|png)$ {
    root /home/ubuntu/myskillhut/static/;
    expires 1M;
}

location ~* \.(css|js)$ {
    root /home/ubuntu/myskillhut/static/;
    expires 1d;
}

Also, make sure nginx can access those files in that dir (../static/)


问:
Java - Pattern Matching
I have some code in php I made using preg_grep for matching several words in any order that can exist in any context. I'm trying to convert it to java but i can't seem to figure it out.

My php code for converting a keyword to a regex string is:

```<code>function createRegexSearch($keywords)
{
    $regex = '';
    foreach ($keywords as $key)
        $regex .= '(?=.*' . $key . ')';
    return '/^' . $regex . '/i';
}
</code>```

It would create a regex string similar to: /^(?=.*bot)/i - which should match robot, robots, bots etc. The same regex string doesn't seem to work in java which is leaving me confused. Currently in java I created a similar effect with contains but would rather use regex.

```<code>for (Map.Entry<String, String> entry : mKeyList.entrySet())
{
    boolean found = true;
    String val = entry.getValue().toLowerCase();
    for (int i = 0; i < keywords.length; i++)
    {
        if (!val.contains(keywords[i].toLowerCase()))
            found = false;
    }

    if (found)
        ret.add(entry.getValue());
}
</code>```

答:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.</p>

```<code>   import org.kl.state.Else;
   import static org.kl.pattern.DeconstructPattern.matches;
   import static org.kl.pattern.DeconstructPattern.foreach;
   import static org.kl.pattern.DeconstructPattern.let;

   let(figure, (int w, int h) -> {
      System.out.println("border: " + w + " " + h));
   });

   matches(figure).as(
      Rectangle.class, (int w, int h) -> System.out.println("square: " + (w * h)),
      Circle.class,    (int r)        -> System.out.println("square: " + (2 * Math.PI * r)),
      Else.class,      ()             -> System.out.println("Default square: " + 0)
   );

   foreach(listRectangles, (int w, int h) -> {
      System.out.println("square: " + (w * h));
   });
</code>```

Title: Java - Pattern Matching

Body:
I have some code in php I made using preg_grep for matching several words in any order that can exist in any context. I'm trying to convert it to java but i can't seem to figure it out.

My php code for converting a keyword to a regex string is:

function createRegexSearch($keywords)
{
    $regex = '';
    foreach ($keywords as $key)
        $regex .= '(?=.*' . $key . ')';
    return '/^' . $regex . '/i';
}

It would create a regex string similar to: /^(?=.*bot)/i - which should match robot, robots, bots etc. The same regex string doesn't seem to work in java which is leaving me confused. Currently in java I created a similar effect with contains but would rather use regex.

for (Map.Entry<String, String> entry : mKeyList.entrySet())
{
    boolean found = true;
    String val = entry.getValue().toLowerCase();
    for (int i = 0; i < keywords.length; i++)
    {
        if (!val.contains(keywords[i].toLowerCase()))
            found = false;
    }

    if (found)
        ret.add(entry.getValue());
}

Body:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.

   import org.kl.state.Else;
   import static org.kl.pattern.DeconstructPattern.matches;
   import static org.kl.pattern.DeconstructPattern.foreach;
   import static org.kl.pattern.DeconstructPattern.let;

   let(figure, (int w, int h) -> {
      System.out.println("border: " + w + " " + h));
   });

   matches(figure).as(
      Rectangle.class, (int w, int h) -> System.out.println("square: " + (w * h)),
      Circle.class,    (int r)        -> System.out.println("square: " + (2 * Math.PI * r)),
      Else.class,      ()             -> System.out.println("Default square: " + 0)
   );

   foreach(listRectangles, (int w, int h) -> {
      System.out.println("square: " + (w * h));
   });


问:
Finding the longest word in a .txt file without punctuation marks
I am doing Python file I/O exercises and albeit made a huge progress on an exercise in which I try to find the longest words in each line of a .txt file, I can't get rid of the punctuation marks.

Here is the code I have:

```<code>with open("original-3.txt", 'r') as file1:
lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(line.split(), key=len))
</code>```

This is the output I get

This is the original-3.txt file where I am reading the data from

```<code>'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

He took his vorpal sword in hand:
Long time the manxome foe he sought,
So rested he by the Tumtum tree,
And stood a while in thought.

And, as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One two! One two! And through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!"
"Oh frabjous day! Callooh! Callay!"
He chortled in his joy.

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
</code>```

As you can see, I am getting the punctuation marks like ["," ";" "?" "!"]

How do you think I can only get the words themselves?

Thank you

答:
Using Regex it is very easy to get what is the length of longest word:

```<code>import re

for line in lines:
    found_strings = re.findall(r'\w+', line)
    print(max([len(txt) for txt in found_strings]))
</code>```

Body:
I am doing Python file I/O exercises and albeit made a huge progress on an exercise in which I try to find the longest words in each line of a .txt file, I can't get rid of the punctuation marks.

Here is the code I have:

with open("original-3.txt", 'r') as file1:
lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(line.split(), key=len))

This is the output I get

This is the original-3.txt file where I am reading the data from

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

He took his vorpal sword in hand:
Long time the manxome foe he sought,
So rested he by the Tumtum tree,
And stood a while in thought.

And, as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One two! One two! And through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!"
"Oh frabjous day! Callooh! Callay!"
He chortled in his joy.

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.

As you can see, I am getting the punctuation marks like ["," ";" "?" "!"]

How do you think I can only get the words themselves?

Thank you

Body:
Using Regex it is very easy to get what is the length of longest word:

import re

for line in lines:
    found_strings = re.findall(r'\w+', line)
    print(max([len(txt) for txt in found_strings]))