答:
You can use lag to get previous value of LastTime and subtract it with next OrigTime for each UserId.

```<code>library(dplyr)

df1 <- df %>%
  group_by(UserId) %>%
  mutate(duration_min = as.numeric(difftime(OrigTime, lag(LastTime), units = "mins"))) %>%
  ungroup

#check ouput
df1 %>% filter(UserId == "5697a38454")  %>% data.frame()

#             OrigTime            LastTime Count       Date     UserId duration_min
#1 2021-06-06 22:42:39 2021-06-06 23:06:57     1 2021-06-06 5697a38454           NA
#2 2021-06-09 19:18:41 2021-06-09 19:26:31     1 2021-06-09 5697a38454     4091.732
#3 2021-06-13 18:05:41 2021-06-13 18:48:01     3 2021-06-13 5697a38454     5679.178
</code>```

Title: Determining duration between lead/lag datetime stamps by group in R

Body:
I am trying to determine the time difference between lead and lag timestamps per UserId in my dataframe. Here is a mock example of the data that I am using:-

df<-structure(list(OrigTime = structure(c(1622918877.032, 1622990559.267,
                                      1623523623.486, 1622964997.979, 1622906958.74, 1622926722.027,
                                      1622995932.538, 1623007146.343, 1622852334.564, 1623060816.584,
                                      1623088121.297, 1623106707.248, 1623157212.89, 1623193304.839,
                                      1623274436.729, 1623043054.385, 1623538988.387, 1623005857.513,
                                      1622910331.285, 1622896371.372, 1623578741.851, 1623587705.782,
                                      1622962414.979, 1623537531.112, 1622903658.463, 1622919800.373,
                                      1623141876.369, 1622853086.032, 1623160223.889, 1623550454.237,
                                      1622977109.735, 1622897061.318, 1622905574.829, 1622975250.648,
                                      1622926151.326, 1623051278.279, 1623155086.613, 1622903064.758,
                                      1623548739.613, 1622926195.481, 1622909740.446, 1622886108.56,
                                      1623571384.742, 1623605761.052, 1622993030.692, 1622970165.788,
                                      1623011480.065, 1622988209.8, 1623322872.845, 1622920880.023,
                                      1623086821.623, 1623612400.05, 1622999424.629, 1622884467.164,
                                      1622909027.54, 1623357575.019, 1623520403.778, 1623506301.231,
                                      1623500077.499, 1622940184.402, 1623495635.381, 1623546311.154,
                                      1623160176.129, 1623346026.209, 1623536993.306, 1622909817.164,
                                      1623530930.965, 1622877595.896, 1622935176.086, 1622966029.777,
                                      1623000495.258, 1623143927.116, 1623174826.058, 1623251814.229,
                                      1623334538.838, 1623340615.546, 1623583357.417, 1622888019.697,
                                      1622987815.488, 1622985968.726, 1622992132.955, 1623074972.982,
                                      1623163375.997, 1622963144.848, 1623314383.152, 1623338313.831,
                                      1623551534.787, 1623309944.257, 1622976858.145, 1622917035.885,
                                      1623004832.589, 1623503830.715, 1622909067.695, 1623237521.393,
                                      1623560279.459, 1623536321.051, 1623519172.633, 1622904213.48,
                                      1622930692.598, 1623534517.344), class = c("POSIXct", "POSIXt"
                                      ), tzone = ""),
               LastTime = structure(c(1622920407.314, 1622992017.446,
               1623523816.193, 1622967138.074, 1622908479.07, 1622929803.083,
               1622998806.578, 1623009559.964, 1622852937.119, 1623060829.114,
               1623088500.114, 1623107957.757, 1623160460.245, 1623196568.13,
               1623277115.719, 1623043075.018, 1623541056.552, 1623009099.355,
               1622912024.838, 1622896604.061, 1623581281.396, 1623587723.349,
               1622964263.202, 1623540285.881, 1622904906.681, 1622920279.246,
               1623145192.007, 1622853411.776, 1623161274.767, 1623552259.907,
               1622979765.947, 1622900302.79, 1622908080.385, 1622977216.257,
               1622926569.129, 1623052916.319, 1623157846.969, 1622906004.01,
               1623550464.577, 1622926894.527, 1622909784.953, 1622888260.143,
               1623574636.082, 1623608199.766, 1622993135.284, 1622972841.446,
               1623011795.668, 1622991602.355, 1623325007.005, 1622920971.11,
               1623089131.737, 1623615902.665, 1623001797.927, 1622884502.675,
               1622909092.535, 1623358953.803, 1623522069.405, 1623506926.633,
               1623500257.459, 1622943093.707, 1623496149.811, 1623546362.939,
               1623161795.166, 1623346301.719, 1623538246.607, 1622910287.546,
               1623531717.106, 1622878786.985, 1622935344.171, 1622967457.633,
               1623003649.624, 1623146488.585, 1623175049.705, 1623254364.036,
               1623337920.846, 1623343354.911, 1623584490.558, 1622890693.611,
               1622990339.013, 1622988379.946, 1622993619.888, 1623077241.267,
               1623164370.961, 1622963916.184, 1623314543.741, 1623340169.331,
               1623551844.722, 1623309979.964, 1622976999.899, 1622918705.036,
               1623007011.831, 1623506533.509, 1622910346.854, 1623237991.188,
               1623563695.799, 1623537537.925, 1623520857.21, 1622904770.506,
               1622931363.125, 1623535224.247), class = c("POSIXct", "POSIXt"), tzone = ""),
               Count = c(1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L,
               1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 4L, 1L, 1L, 3L, 1L, 2L, 1L, 1L,
               1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 1L,
               1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
               2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L,
               1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
               1L, 1L, 1L, 3L, 1L, 4L, 1L, 1L, 1L, 1L, 1L),
               Date = structure(c(18783,18784, 18790, 18784, 18783, 18783, 18784, 18784, 18783, 18785,
                                        18785, 18785, 18786, 18787, 18787, 18785, 18791, 18784, 18783,
                                        18783, 18791, 18791, 18784, 18790, 18783, 18783, 18786, 18783,
                                        18786, 18791, 18784, 18783, 18783, 18784, 18783, 18785, 18786,
                                        18783, 18791, 18783, 18783, 18783, 18791, 18791, 18784, 18784,
                                        18784, 18784, 18788, 18783, 18785, 18791, 18784, 18783, 18783,
                                        18788, 18790, 18790, 18790, 18784, 18790, 18791, 18786, 18788,
                                        18790, 18783, 18790, 18783, 18784, 18784, 18784, 18786, 18786,
                                        18787, 18788, 18788, 18791, 18783, 18784, 18784, 18784, 18785,
                                        18786, 18784, 18788, 18788, 18791, 18788, 18784, 18783, 18784,
                                        18790, 18783, 18787, 18791, 18790, 18790, 18783, 18783, 18790
                                        ), class = "Date"),
               UserId = c("853a97958b", "5697a38454", "c634a20759","ccf82840cd", "c083d8b935", "0410501e6b", "44c7c67c09", "9df7bcac8a",
                          "83db724191", "ebebd2505c", "9718c1ac40", "70e04f7a77", "8d6640a636",
                          "5ae2fb243b", "ebebd2505c", "7183f894ba", "83db724191", "0587f9f73b",
                          "875b5bcf85", "b1e4fc6c16", "5697a38454", "6cd922ee02", "503297a15f",
                          "def09e5b6a", "c083d8b935", "b7a17366f5", "44c7c67c09", "ee96fb2ea5",
                          "1053a213ea", "44c7c67c09", "5ae2fb243b", "e34de6863b", "7cf03078e8",
                          "bdfe5fe4d0", "bdfe5fe4d0", "c4c834065b", "36d0a2a630", "acfef8373f",
                          "ccf82840cd", "708885c8e0", "a1ce5e9964", "a5d5a264b4", "def09e5b6a",
                          "779cb9e811", "b1e4fc6c16", "c083d8b935", "a5d5a264b4", "5ae2fb243b",
                          "8d6a062f0f", "3e7700d63e", "9df7bcac8a", "44c7c67c09", "dfb1730f71",
                          "4646f53bd2", "c58f3eea85", "70e04f7a77", "de91cac214", "def09e5b6a",
                          "4646f53bd2", "875b5bcf85", "70e04f7a77", "65a2416cbc", "b3896de6fe",
                          "efe44e7d92", "44c7c67c09", "ebebd2505c", "0587f9f73b", "0393eacfee",
                          "8fccf03fc1", "83db724191", "de91cac214", "9718c1ac40", "779cb9e811",
                          "49f14ca03c", "0410501e6b", "a5d5a264b4", "e2c5bb55c9", "a1ce5e9964",
                          "3e7700d63e", "875b5bcf85", "70e04f7a77", "dfb1730f71", "46e37e426c",
                          "708885c8e0", "875b5bcf85", "e2c5bb55c9", "1053a213ea", "7cf03078e8",
                          "50da214747", "7cf03078e8", "0410501e6b", "779cb9e811", "9df7bcac8a",
                          "5697a38454", "ddf466ccaa", "c083d8b935", "3e7700d63e", "def09e5b6a",
                          "f52c20cd44", "5ae2fb243b")), row.names = c(NA, 100L), class = "data.frame")

library(tidyverse)
df<-df%>%
  arrange(UserId,OrigTime)

What I want is to be able to group the data by UserId and then calculate the difference (minutes) in time between the LastTime in one row and the OrigTime in the following row. Here is an example of the type of outcome I am after, using one UserId as an example:-

#5697a38454

          #OrigTime            LastTime    Count   Date     UserId        duration_min
#1 2021-06-06 15:42:39 2021-06-06 16:06:57     1 2021-06-06 5697a38454        NA
#2 2021-06-09 12:18:41 2021-06-09 12:26:31     1 2021-06-09 5697a38454      4091.73
#3 2021-06-13 11:05:41 2021-06-13 11:48:01     3 2021-06-13 5697a38454      6399.17

For the first instance per UserId, the time difference will be NA, as there is no previous LastTime to base a calculation of. Should a particular UserId only have one row/instance, then the duration_min variable should be NA also. Can anyone demonstrate a way to do this? much appreciated :)

Body:
You can use lag to get previous value of LastTime and subtract it with next OrigTime for each UserId.

library(dplyr)

df1 <- df %>%
  group_by(UserId) %>%
  mutate(duration_min = as.numeric(difftime(OrigTime, lag(LastTime), units = "mins"))) %>%
  ungroup

#check ouput
df1 %>% filter(UserId == "5697a38454")  %>% data.frame()

#             OrigTime            LastTime Count       Date     UserId duration_min
#1 2021-06-06 22:42:39 2021-06-06 23:06:57     1 2021-06-06 5697a38454           NA
#2 2021-06-09 19:18:41 2021-06-09 19:26:31     1 2021-06-09 5697a38454     4091.732
#3 2021-06-13 18:05:41 2021-06-13 18:48:01     3 2021-06-13 5697a38454     5679.178


来源: stackexchange

问:
Communicate with Elfin EW11 RS485 wifi converter
I am trying to communicate with an electrical meter (Orno WE-517) that has an RS485 modbus interface. This serial interface is connected to an Elfin EW11 modbus to Wifi converter.

Using pymodbus, I can connect to the adapter but I don't manage to read anything from the meter.
Here is my code:

```<code>from pymodbus.client.sync import ModbusTcpClient

from pprint import pprint

import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s '
          '%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()

log.setLevel(logging.DEBUG)

client = ModbusTcpClient('192.168.0.18', 502)
if not client.connect():
    print('Error connecting')
    exit()

print('holding register')
result = client.read_holding_registers(28,1)
response = client.execute(result)
pprint(vars(response))

client.close()
</code>```

Here is the output of the script:

python3 modBus.py

```<code>2021-12-30 10:46:44,112 MainThread      DEBUG    sync           :216      Connection to Modbus server established. Socket ('192.168.0.10', 47763)
holding register
2021-12-30 10:46:44,113 MainThread      DEBUG    transaction    :140      Current transaction state - IDLE
2021-12-30 10:46:44,114 MainThread      DEBUG    transaction    :145      Running transaction 1
2021-12-30 10:46:44,114 MainThread      DEBUG    transaction    :273      SEND: 0x0 0x1 0x0 0x0 0x0 0x6 0x0 0x3 0x0 0x1c 0x0 0x1
2021-12-30 10:46:44,115 MainThread      DEBUG    sync           :76       New Transaction state 'SENDING'
2021-12-30 10:46:44,115 MainThread      DEBUG    transaction    :287      Changing transaction state from 'SENDING' to 'WAITING FOR REPLY'
2021-12-30 10:46:44,216 MainThread      DEBUG    transaction    :375      Changing transaction state from 'WAITING FOR REPLY' to 'PROCESSING REPLY'
2021-12-30 10:46:44,217 MainThread      DEBUG    transaction    :297      RECV: 0x0 0x1 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x3e 0xf0
2021-12-30 10:46:44,218 MainThread      DEBUG    socket_framer  :147      Processing: 0x0 0x1 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x3e 0xf0
2021-12-30 10:46:44,218 MainThread      DEBUG    factory        :266      Factory Response[ReadHoldingRegistersResponse: 3]
2021-12-30 10:46:44,219 MainThread      DEBUG    transaction    :454      Adding transaction 1
2021-12-30 10:46:44,220 MainThread      DEBUG    transaction    :465      Getting transaction 1
2021-12-30 10:46:44,220 MainThread      DEBUG    transaction    :224      Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
2021-12-30 10:46:44,221 MainThread      DEBUG    transaction    :140      Current transaction state - TRANSACTION_COMPLETE
2021-12-30 10:46:44,221 MainThread      DEBUG    transaction    :145      Running transaction 2
2021-12-30 10:46:44,222 MainThread      DEBUG    transaction    :273      SEND: 0x0 0x2 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x3e 0xf0
2021-12-30 10:46:44,222 MainThread      DEBUG    sync           :76       New Transaction state 'SENDING'
2021-12-30 10:46:44,223 MainThread      DEBUG    transaction    :287      Changing transaction state from 'SENDING' to 'WAITING FOR REPLY'
2021-12-30 10:46:47,227 MainThread      DEBUG    transaction    :303      Transaction failed. (Modbus Error: [Invalid Message] No response received, expected at least 8 bytes (0 received))
2021-12-30 10:46:47,228 MainThread      DEBUG    socket_framer  :147      Processing:
2021-12-30 10:46:47,228 MainThread      DEBUG    transaction    :465      Getting transaction 2
2021-12-30 10:46:47,229 MainThread      DEBUG    transaction    :224      Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
{'fcode': 3,
 'message': '[Input/Output] Modbus Error: [Invalid Message] No response '
            'received, expected at least 8 bytes (0 received)',
 'string': '[Input/Output] Modbus Error: [Invalid Message] No response '
           'received, expected at least 8 bytes (0 received)'}
</code>```

As you can see, pymodbus manages to connect, send a request and receive a response.
But I can't find the way to do something from that response.

Would anyone have an idea to help me?

In advance, thanks a lot for your help :)

答:
Persevering in the look for a solution, I discovered that the values are actually float.
This lead me to the following solution:

```<code>from pymodbus.client.sync import ModbusTcpClient
from pymodbus.payload import BinaryPayloadDecoder

client = ModbusTcpClient('192.168.0.18', 502)
if not client.connect():
    print('Error connecting')
    exit()

result = client.read_holding_registers(0x1C, 2)
decoder = BinaryPayloadDecoder.fromRegisters(result.registers, '>', '>')
print(decoder.decode_32bit_float())

client.close()
</code>```

The solution was really to find the various methods of BinaryPayloadDecoder.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to communicate with an electrical meter (Orno WE-517) that has an RS485 modbus interface. This serial interface is connected to an Elfin EW11 modbus to Wifi converter.

Using pymodbus, I can connect to the adapter but I don't manage to read anything from the meter.
Here is my code:

from pymodbus.client.sync import ModbusTcpClient

from pprint import pprint

import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s '
          '%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()

log.setLevel(logging.DEBUG)

client = ModbusTcpClient('192.168.0.18', 502)
if not client.connect():
    print('Error connecting')
    exit()

print('holding register')
result = client.read_holding_registers(28,1)
response = client.execute(result)
pprint(vars(response))

client.close()

Here is the output of the script:

python3 modBus.py

2021-12-30 10:46:44,112 MainThread      DEBUG    sync           :216      Connection to Modbus server established. Socket ('192.168.0.10', 47763)
holding register
2021-12-30 10:46:44,113 MainThread      DEBUG    transaction    :140      Current transaction state - IDLE
2021-12-30 10:46:44,114 MainThread      DEBUG    transaction    :145      Running transaction 1
2021-12-30 10:46:44,114 MainThread      DEBUG    transaction    :273      SEND: 0x0 0x1 0x0 0x0 0x0 0x6 0x0 0x3 0x0 0x1c 0x0 0x1
2021-12-30 10:46:44,115 MainThread      DEBUG    sync           :76       New Transaction state 'SENDING'
2021-12-30 10:46:44,115 MainThread      DEBUG    transaction    :287      Changing transaction state from 'SENDING' to 'WAITING FOR REPLY'
2021-12-30 10:46:44,216 MainThread      DEBUG    transaction    :375      Changing transaction state from 'WAITING FOR REPLY' to 'PROCESSING REPLY'
2021-12-30 10:46:44,217 MainThread      DEBUG    transaction    :297      RECV: 0x0 0x1 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x3e 0xf0
2021-12-30 10:46:44,218 MainThread      DEBUG    socket_framer  :147      Processing: 0x0 0x1 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x3e 0xf0
2021-12-30 10:46:44,218 MainThread      DEBUG    factory        :266      Factory Response[ReadHoldingRegistersResponse: 3]
2021-12-30 10:46:44,219 MainThread      DEBUG    transaction    :454      Adding transaction 1
2021-12-30 10:46:44,220 MainThread      DEBUG    transaction    :465      Getting transaction 1
2021-12-30 10:46:44,220 MainThread      DEBUG    transaction    :224      Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
2021-12-30 10:46:44,221 MainThread      DEBUG    transaction    :140      Current transaction state - TRANSACTION_COMPLETE
2021-12-30 10:46:44,221 MainThread      DEBUG    transaction    :145      Running transaction 2
2021-12-30 10:46:44,222 MainThread      DEBUG    transaction    :273      SEND: 0x0 0x2 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x3e 0xf0
2021-12-30 10:46:44,222 MainThread      DEBUG    sync           :76       New Transaction state 'SENDING'
2021-12-30 10:46:44,223 MainThread      DEBUG    transaction    :287      Changing transaction state from 'SENDING' to 'WAITING FOR REPLY'
2021-12-30 10:46:47,227 MainThread      DEBUG    transaction    :303      Transaction failed. (Modbus Error: [Invalid Message] No response received, expected at least 8 bytes (0 received))
2021-12-30 10:46:47,228 MainThread      DEBUG    socket_framer  :147      Processing:
2021-12-30 10:46:47,228 MainThread      DEBUG    transaction    :465      Getting transaction 2
2021-12-30 10:46:47,229 MainThread      DEBUG    transaction    :224      Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
{'fcode': 3,
 'message': '[Input/Output] Modbus Error: [Invalid Message] No response '
            'received, expected at least 8 bytes (0 received)',
 'string': '[Input/Output] Modbus Error: [Invalid Message] No response '
           'received, expected at least 8 bytes (0 received)'}

As you can see, pymodbus manages to connect, send a request and receive a response.
But I can't find the way to do something from that response.

Would anyone have an idea to help me?

In advance, thanks a lot for your help :)

Body:
Persevering in the look for a solution, I discovered that the values are actually float.
This lead me to the following solution:

from pymodbus.client.sync import ModbusTcpClient
from pymodbus.payload import BinaryPayloadDecoder

client = ModbusTcpClient('192.168.0.18', 502)
if not client.connect():
    print('Error connecting')
    exit()

result = client.read_holding_registers(0x1C, 2)
decoder = BinaryPayloadDecoder.fromRegisters(result.registers, '>', '>')
print(decoder.decode_32bit_float())

client.close()

The solution was really to find the various methods of BinaryPayloadDecoder.


问:
How to get access token from refresh token in gmail api in asp.net
I'm using oAuth 2.0 to authenticate gmail api v1 and getting the access token and refresh token but how to get access token using refresh token.</p>

```<code>UserCredential credential;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
       new ClientSecrets
       {
          ClientId = "my client id",
          ClientSecret = "my client secret"
       },
       new[] { GmailService.Scope.GmailSend },
       "user",
       CancellationToken.None).Result;

// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
   HttpClientInitializer = credential,
   ApplicationName = ApplicationName,
});

string RefreshToken = credential.Token.RefreshToken;
</code>```

答:
working code</p>
```<code>string[] scopes = new string[] { "https://mail.google.com/" };

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
         new ClientSecrets
         {
            ClientId = "my client id",
            ClientSecret = "my client secret"
         },
         scopes,
        "user",
         CancellationToken.None).Result;
string RefreshToken = credential.Token.RefreshToken;//you will get Refreshtoken
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using oAuth 2.0 to authenticate gmail api v1 and getting the access token and refresh token but how to get access token using refresh token.

UserCredential credential;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
       new ClientSecrets
       {
          ClientId = "my client id",
          ClientSecret = "my client secret"
       },
       new[] { GmailService.Scope.GmailSend },
       "user",
       CancellationToken.None).Result;

// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
   HttpClientInitializer = credential,
   ApplicationName = ApplicationName,
});

string RefreshToken = credential.Token.RefreshToken;

Body:
working code

string[] scopes = new string[] { "https://mail.google.com/" };

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
         new ClientSecrets
         {
            ClientId = "my client id",
            ClientSecret = "my client secret"
         },
         scopes,
        "user",
         CancellationToken.None).Result;
string RefreshToken = credential.Token.RefreshToken;//you will get Refreshtoken


问:
How to filter null returning method in stream?
I have a list, it has some method like getSummary(), and this method returns null in some cases. How can I filter to avoid getting the null result?

Here is my code:

```<code>List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}
</code>```

答:
A filter predicate, like the following, needs to be added in the stream:

.filter(event -> event.getSummary() != null)

The code after the addition is provided hereafter for reference:

```<code>List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
             //filter to keep only events with non-null event.getSummary()
            .filter(event -> event.getSummary() != null)
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}
</code>```

Body:
I have a list, it has some method like getSummary(), and this method returns null in some cases. How can I filter to avoid getting the null result?

Here is my code:

List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}

Body:
A filter predicate, like the following, needs to be added in the stream:

.filter(event -> event.getSummary() != null)

The code after the addition is provided hereafter for reference:

List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
             //filter to keep only events with non-null event.getSummary()
            .filter(event -> event.getSummary() != null)
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}


问:
Use preg_replace() to add two backslashes before each match
I have code below, what I need to change to get result mercedes\\-benz instead of mercedes\-benz

```<code>$value = 'mercedes-benz';
$pattern = '/(\+|-|\/|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';
$replace = '\\\\${1}';
echo preg_replace($pattern, $replace, $value);
</code>```

答:
I can't be sure that I've 100% translated your original attempt, but this works for your lone sample input.

The pattern uses a character class and curly braced quantifiers to improve readability and brevity.  Using \K eliminates the need for the reference in the replacement string.

Code: (Demo)

```<code>$value = 'mercedes-benz';
$pattern = '`&{2}|\|{2}|[-+/!(){}[\]^"~*?:\\\]\K`';
$replace = '\\\\\\';
echo preg_replace($pattern, $replace, $value);
</code>```

Ultimately, the trick was to keep adding backslashes to the replacement to get them to show up.

Body:
I have code below, what I need to change to get result mercedes\\-benz instead of mercedes\-benz

$value = 'mercedes-benz';
$pattern = '/(\+|-|\/|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';
$replace = '\\\\${1}';
echo preg_replace($pattern, $replace, $value);

Body:
I can't be sure that I've 100% translated your original attempt, but this works for your lone sample input.

The pattern uses a character class and curly braced quantifiers to improve readability and brevity.  Using \K eliminates the need for the reference in the replacement string.

Code: (Demo)

$value = 'mercedes-benz';
$pattern = '`&{2}|\|{2}|[-+/!(){}[\]^"~*?:\\\]\K`';
$replace = '\\\\\\';
echo preg_replace($pattern, $replace, $value);

Ultimately, the trick was to keep adding backslashes to the replacement to get them to show up.


问:
Next JS : Loading Screen While the dom is rendeing
How can I show my own loader instead of a blank white screen?
For Example, Tweeter Shows the logo while the page is loading, same for Facebook, google AdSense, etc.
Look at this Gif, I want something like this in Next Js.

I guess this is something to do with the _document.js. There is a similar question for react js (render the loader in index.html)
But I cant figure out how to do it in next js.

答:
You can use router.event.

See this link:

https://github.com/vercel/next.js/blob/canary/examples/with-loading/pages/_app.js

useEffect(() => {
const handleStart = (url) => {
console.log(Loading: ${url})
NProgress.start()
}
const handleStop = () => {
NProgress.done()
}

```<code>router.events.on('routeChangeStart', handleStart)
router.events.on('routeChangeComplete', handleStop)
router.events.on('routeChangeError', handleStop)

return () => {
  router.events.off('routeChangeStart', handleStart)
  router.events.off('routeChangeComplete', handleStop)
  router.events.off('routeChangeError', handleStop)
}
</code>```

}, [router]);

Body:
You can use router.event.

See this link:

https://github.com/vercel/next.js/blob/canary/examples/with-loading/pages/_app.js

useEffect(() => {
const handleStart = (url) => {
console.log(Loading: ${url})
NProgress.start()
}
const handleStop = () => {
NProgress.done()
}

router.events.on('routeChangeStart', handleStart)
router.events.on('routeChangeComplete', handleStop)
router.events.on('routeChangeError', handleStop)

return () => {
  router.events.off('routeChangeStart', handleStart)
  router.events.off('routeChangeComplete', handleStop)
  router.events.off('routeChangeError', handleStop)
}

}, [router]);


问:
ImportError: Could not import PIL.Image. The use of `load_img` requires PIL. even after using pillow library
My program is a feature extraction for an image processing program, we are loading the model and extracting features from each image.

We load the image from file

convert the pixels of image to numpy array

extract features

store features

save to file(pkl)

This is the code snippet.

```<code>from os import listdir
from pickle import dump
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.inception_v3 import preprocess_input
from keras.models import Model
import string
from timeit import default_timer as timer
from PIL import Image
import sys

</code>```
```<code>for name in listdir(directory):
    # load an image from file
    filename = directory + '/' + name
    image = load_img(filename, target_size=(230,230))
    # convert the image pixels to a numpy array
    image = img_to_array(image)
    # reshape data for the model
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    # prepare the image for the VGG model
    image = preprocess_input(image)
    # get features
    feature = model.predict(image, verbose=0)
    # get image id
    image_id = name.split('.')[0]
    # store feature
    features[image_id] = feature
    #print('>%s' % name)
return features
</code>```

It gives me this error

```<code> ---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-5-566a23558a68> in <module>
     46 # extract features from all images
     47 directory = 'data/caption/1'
---> 48 features = extract_features(directory)
     49 #print('Extracted Features: %d' % len(features))
     50 # save to file

<ipython-input-5-566a23558a68> in extract_features(directory)
     27         # load an image from file
     28         filename = directory + '/' + name
---> 29         image = load_img(filename, target_size=(230,230))
     30         # convert the image pixels to a numpy array
     31         image = img_to_array(image)

c:\users\likith\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\keras\preprocessing\image.py in load_img(path, grayscale, color_mode, target_size, interpolation)
    298       ValueError: if interpolation method is not supported.
    299   """
--> 300   return image.load_img(path, grayscale=grayscale, color_mode=color_mode,
    301                         target_size=target_size, interpolation=interpolation)
    302

c:\users\likith\appdata\local\programs\python\python38\lib\site-packages\keras_preprocessing\image\utils.py in load_img(path, grayscale, color_mode, target_size, interpolation)
    109         color_mode = 'grayscale'
    110     if pil_image is None:
--> 111         raise ImportError('Could not import PIL.Image. '
    112                           'The use of `load_img` requires PIL.')
    113     with open(path, 'rb') as f:

ImportError: Could not import PIL.Image. The use of `load_img` requires PIL.
</code>```

I've installed pillow and imported it into the program but it still gives me the same error.

答: Do "" pip install Image"" that will resolve your error, don't forget to uninstall PIL first</p>

Body:
My program is a feature extraction for an image processing program, we are loading the model and extracting features from each image.

We load the image from file

convert the pixels of image to numpy array

extract features

store features

save to file(pkl)

This is the code snippet.

from os import listdir
from pickle import dump
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.inception_v3 import preprocess_input
from keras.models import Model
import string
from timeit import default_timer as timer
from PIL import Image
import sys

for name in listdir(directory):
    # load an image from file
    filename = directory + '/' + name
    image = load_img(filename, target_size=(230,230))
    # convert the image pixels to a numpy array
    image = img_to_array(image)
    # reshape data for the model
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    # prepare the image for the VGG model
    image = preprocess_input(image)
    # get features
    feature = model.predict(image, verbose=0)
    # get image id
    image_id = name.split('.')[0]
    # store feature
    features[image_id] = feature
    #print('>%s' % name)
return features

It gives me this error

 ---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-5-566a23558a68> in <module>
     46 # extract features from all images
     47 directory = 'data/caption/1'
---> 48 features = extract_features(directory)
     49 #print('Extracted Features: %d' % len(features))
     50 # save to file

<ipython-input-5-566a23558a68> in extract_features(directory)
     27         # load an image from file
     28         filename = directory + '/' + name
---> 29         image = load_img(filename, target_size=(230,230))
     30         # convert the image pixels to a numpy array
     31         image = img_to_array(image)

c:\users\likith\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\keras\preprocessing\image.py in load_img(path, grayscale, color_mode, target_size, interpolation)
    298       ValueError: if interpolation method is not supported.
    299   """
--> 300   return image.load_img(path, grayscale=grayscale, color_mode=color_mode,
    301                         target_size=target_size, interpolation=interpolation)
    302

c:\users\likith\appdata\local\programs\python\python38\lib\site-packages\keras_preprocessing\image\utils.py in load_img(path, grayscale, color_mode, target_size, interpolation)
    109         color_mode = 'grayscale'
    110     if pil_image is None:
--> 111         raise ImportError('Could not import PIL.Image. '
    112                           'The use of `load_img` requires PIL.')
    113     with open(path, 'rb') as f:

ImportError: Could not import PIL.Image. The use of `load_img` requires PIL.

I've installed pillow and imported it into the program but it still gives me the same error.


问:
Where are the best explanations of memory management for iPhone?
I am looking for good explanations out there. I have a 1000 pages book about objective-c, but unfortunately the part about memory management, retain counting, is described pretty bad and hard to understand.</p>

答:
Memory Management in Objective-C
Learn Obj-C Memory Management

They've got some simple answers, but also links to Apple's documentation.

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: gs


问:
React Native Timer UI
I'm looking for a component who display the picker, for a timer. I'm using react-native-datetimepicker but doesn't solve my problem. Need only that timer picker. It's difficult to find in Google because the results are irrelevant.</p>

答:
Try using react-duration-picker

```<code>const onChange = duration => {
  const { hours, minutes, seconds } = duration;
  setState({ hours, minutes, seconds });
};

return (
  <Modal open={isOpen}>
    <DurationPicker
      onChange={onChange}
      initialDuration={{ hours: 1, minutes: 2, seconds: 3 }}
      maxHours={5}
    />
    <button onClick={closeModal} />
  </Modal>
);
</code>```

Example code Here

Title: React Native Timer UI

Body:
Try using react-duration-picker

const onChange = duration => {
  const { hours, minutes, seconds } = duration;
  setState({ hours, minutes, seconds });
};

return (
  <Modal open={isOpen}>
    <DurationPicker
      onChange={onChange}
      initialDuration={{ hours: 1, minutes: 2, seconds: 3 }}
      maxHours={5}
    />
    <button onClick={closeModal} />
  </Modal>
);

Example code Here


问:
Error: error:0308010C:digital envelope routines::unsupported - Next.js
This problem occurs in the Next.js project with Node version 17 I tried a lot of solutions but this solution is the best you can solve this problem if it occurred with you</p>
```<code>
> landing-page@0.0.1 dev
> next dev

Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
ready - started server on http://localhost:3000
node:internal/crypto/hash:67
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:67:19)
    at Object.createHash (node:crypto:130:10)
    at module.exports (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\util\createHash.js:135:53)
    at NormalModule._initBuildHash (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing
Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\NormalModule.js:417:16)
    at handleParseError (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\NormalModule.js:471:10)
    at E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\NormalModule.js:503:5
    at E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\NormalModule.js:358:12
    at E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\loader-runner\lib\LoaderRunner.js:373:3
    at iterateNormalLoaders (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, B    at Array.<anonymous> (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\loader-runner\lib\LoaderRunner.js:205:4) {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}
Node.js v17.2.0

</code>```

答:
First, install  cross-env

```<code>npx install cross-env
</code>```

then, Just set this in scripts in package.json

```<code>"dev": "cross-env NODE_OPTIONS='--openssl-legacy-provider' next dev",
</code>```

Last run this command

```<code>npm run dev
</code>```

Body:
This problem occurs in the Next.js project with Node version 17 I tried a lot of solutions but this solution is the best you can solve this problem if it occurred with you

> landing-page@0.0.1 dev
> next dev

Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
ready - started server on http://localhost:3000
node:internal/crypto/hash:67
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:67:19)
    at Object.createHash (node:crypto:130:10)
    at module.exports (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\util\createHash.js:135:53)
    at NormalModule._initBuildHash (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing
Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\NormalModule.js:417:16)
    at handleParseError (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\NormalModule.js:471:10)
    at E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\NormalModule.js:503:5
    at E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\webpack\lib\NormalModule.js:358:12
    at E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\loader-runner\lib\LoaderRunner.js:373:3
    at iterateNormalLoaders (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, B    at Array.<anonymous> (E:\Collage\COURSES\react.js projects2\01.Build and Deploy a Premium Next JS React Website _ Landing Page, Business Website, Portfolio\nextjs_landing_page\node_modules\loader-runner\lib\LoaderRunner.js:205:4) {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}
Node.js v17.2.0

Body:
First, install  cross-env

npx install cross-env

then, Just set this in scripts in package.json

"dev": "cross-env NODE_OPTIONS='--openssl-legacy-provider' next dev",

Last run this command

npm run dev


问:
structure vs class in swift language
From Apple book
"One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference."

Can anyone help me understand what that means? To me, classes and structs seem to be the same.

答:
As many have already pointed out the differences in copying structs and classes, it can all be understood from where they come from in c, a struct like

```<code>struct A {
    let a: Int
    let c: Bool
}
</code>```

in memory local to the func parent object or struct it will be something like

```<code>64bit for int
8 bytes for bool
</code>```

now for

```<code>class A {
    let a: Int
    let c: Bool
}
</code>```

instead of the contents of the data being stored in local memory or struct or class it will be a single pointer

```<code>64bit address of class A instance
</code>```

When you copy the two its easy to see why there are difference, copy the first, you copy the 64bit for the int and the 8 bit for the bool, copy the second you copy the 64bit address to the instance of class A, you can have multiple copies of the same memory address, all pointing to the same instance, but each copy of the struct will be its own copy.

Now things can get complicated because you can mix the two you have to something like

```<code>struct A {
    let a: ClassA
    let c: Bool
}
</code>```

your memory will look something like

```<code>64bit address of class A instance
8 bytes for bool
</code>```

This is a problem because even though you have multiple copies of the struct in your program, they all have a copy to the same object ClassA, this means just like multiples reference to instance ClassA you pass around have to have a reference count kept of how many reference to the object exists to know when to delete them, you program can have multiple references to struct A that need to keep a reference count to their ClassA instances, this can be time consuming if your struct has a lot of classes in them, or the structs it contains has lots of classes in them, now when you copy your struct, the compiler has to generate code that goes through every single class instance referenced in your struct and substructs, and increment there reference count to keep track of how many references there are. This can make classes much faster to pass around as you just need to copy its single address, and it won't need to increase the reference count of any of its children because it want reduce the reference count of any child it contains until its own reference count reaches 0.

The thing gets even more complicated with some Apple struct types, that they actually have object types in them, the good thing about data that is reference to, is it can be stored in memory and be lengthened and contractor at will and they can be very large, unlike data stored on local stack, so types like String, Array, Set, Dictionary though they act like struct and will even make a duplicate of there internal data if you try to modify them so you don't change all occurrence, there data still has to be reference counted and so a struct containing a lots of these types can still be slow, because the internal data for each one has to be retained.

Of cause passing struct types can reduce the possibility of lots of error, but they can also slow your program down depending on the types the contain.

Title: structure vs class in swift language

Body:
As many have already pointed out the differences in copying structs and classes, it can all be understood from where they come from in c, a struct like

struct A {
    let a: Int
    let c: Bool
}

in memory local to the func parent object or struct it will be something like

64bit for int
8 bytes for bool

now for

class A {
    let a: Int
    let c: Bool
}

instead of the contents of the data being stored in local memory or struct or class it will be a single pointer

64bit address of class A instance

When you copy the two its easy to see why there are difference, copy the first, you copy the 64bit for the int and the 8 bit for the bool, copy the second you copy the 64bit address to the instance of class A, you can have multiple copies of the same memory address, all pointing to the same instance, but each copy of the struct will be its own copy.

Now things can get complicated because you can mix the two you have to something like

struct A {
    let a: ClassA
    let c: Bool
}

your memory will look something like

64bit address of class A instance
8 bytes for bool

This is a problem because even though you have multiple copies of the struct in your program, they all have a copy to the same object ClassA, this means just like multiples reference to instance ClassA you pass around have to have a reference count kept of how many reference to the object exists to know when to delete them, you program can have multiple references to struct A that need to keep a reference count to their ClassA instances, this can be time consuming if your struct has a lot of classes in them, or the structs it contains has lots of classes in them, now when you copy your struct, the compiler has to generate code that goes through every single class instance referenced in your struct and substructs, and increment there reference count to keep track of how many references there are. This can make classes much faster to pass around as you just need to copy its single address, and it won't need to increase the reference count of any of its children because it want reduce the reference count of any child it contains until its own reference count reaches 0.

The thing gets even more complicated with some Apple struct types, that they actually have object types in them, the good thing about data that is reference to, is it can be stored in memory and be lengthened and contractor at will and they can be very large, unlike data stored on local stack, so types like String, Array, Set, Dictionary though they act like struct and will even make a duplicate of there internal data if you try to modify them so you don't change all occurrence, there data still has to be reference counted and so a struct containing a lots of these types can still be slow, because the internal data for each one has to be retained.

Of cause passing struct types can reduce the possibility of lots of error, but they can also slow your program down depending on the types the contain.


问:
Getting Rounding errors in Bigdecimal for RoundingModes - HALF_UP/EVEN in JRE 7/8/11
When I try the below code I am getting 2 strange outputs

42.01
42.01

82.00
82.00

Is anyone sure about why this is happening ?  and can it be resolved with the using the below RoundingMode for BigDecimal in java 7/8.

```<code>import java.math.*;
class HelloWorld {
    public static void main(String[] args) {

      BigDecimal hup = new BigDecimal(42.0050).setScale(2,
                                            RoundingMode.HALF_UP);
      BigDecimal hev = new BigDecimal(42.0050).setScale(2,
                                        RoundingMode.HALF_EVEN);

      BigDecimal hup2 = new BigDecimal(82.0050).setScale(2,
                                            RoundingMode.HALF_UP);
      BigDecimal hev2 = new BigDecimal(82.0050).setScale(2,
                                        RoundingMode.HALF_EVEN);

       System.out.println(hup);
       System.out.println(hev);
       System.out.println(hup2);
       System.out.println(hev2);
}}
</code>```

Thanks.

答:
That's a funny question.

Change your input to this and see the difference:

```<code>BigDecimal hup = new BigDecimal("42.0050").setScale(2,
    RoundingMode.HALF_UP);
BigDecimal hev = new BigDecimal("42.0050").setScale(2,
    RoundingMode.HALF_EVEN);
</code>```

The result will be:

42.01
42.00

The problem, in reality, is how the input to BigDecimal is given.

In IntelliJ, for example, you see a warning when using BigDecimal not as String:

Body:
When I try the below code I am getting 2 strange outputs

42.01
42.01

82.00
82.00

Is anyone sure about why this is happening ?  and can it be resolved with the using the below RoundingMode for BigDecimal in java 7/8.

import java.math.*;
class HelloWorld {
    public static void main(String[] args) {

      BigDecimal hup = new BigDecimal(42.0050).setScale(2,
                                            RoundingMode.HALF_UP);
      BigDecimal hev = new BigDecimal(42.0050).setScale(2,
                                        RoundingMode.HALF_EVEN);

      BigDecimal hup2 = new BigDecimal(82.0050).setScale(2,
                                            RoundingMode.HALF_UP);
      BigDecimal hev2 = new BigDecimal(82.0050).setScale(2,
                                        RoundingMode.HALF_EVEN);

       System.out.println(hup);
       System.out.println(hev);
       System.out.println(hup2);
       System.out.println(hev2);
}}

Thanks.

Body:
That's a funny question.

Change your input to this and see the difference:

BigDecimal hup = new BigDecimal("42.0050").setScale(2,
    RoundingMode.HALF_UP);
BigDecimal hev = new BigDecimal("42.0050").setScale(2,
    RoundingMode.HALF_EVEN);

The result will be:

42.01
42.00

The problem, in reality, is how the input to BigDecimal is given.

In IntelliJ, for example, you see a warning when using BigDecimal not as String:


问:
react-native-chart-kit error while updating property "d" of a view managed by RNSVGPath:
I am using react-native-chart-kit pie chart.

In the data array, instead of writing a number in the population, I am writing “this.state.data” as shown below since I am getting the numbers from an API.

```<code>const pieData1 = [
  {
    name: ': East',
    population: this.state.data,
    color: '#00664f',
    legendFontColor: 'black',
    legendFontSize: 12,
  },
</code>```

]

But I get the error "error while updating property "d" of a view managed by RNSVGPath:". Any idea how to solve it please?

答:
I confirm this is the fix for the issue.
I experienced same error on PieChart until I realized that property I pass to as a float turned out to be a string.
JavaScript is not strong typed language - hence adding parseFloat resolved the issue.</p>

Body:
I am using react-native-chart-kit pie chart.

In the data array, instead of writing a number in the population, I am writing “this.state.data” as shown below since I am getting the numbers from an API.

const pieData1 = [
  {
    name: ': East',
    population: this.state.data,
    color: '#00664f',
    legendFontColor: 'black',
    legendFontSize: 12,
  },

]

But I get the error "error while updating property "d" of a view managed by RNSVGPath:". Any idea how to solve it please?


问:
Creating fake URL in Java
I am working on an ERP project.
We have a URL like this: domain.com/home-appns
keeping this URL for the request I want to display another URL in address bar like: domain.com\home\home-appns.

I an looking for solutions using Java/javascript.

答: Create a servlet and in web.xml, where the servlet is defined, add tag url-pattern. Write corresponding url pattern in it. In this servlet, now use response.sendRedirect("URL"). Now your browser will show url-pattern instead of URL.

Title: Creating fake URL in Java


问:
How do I get my function to refer to a variable set outside of the function?
When I try and use the code below, even when I run the set_list_index function it doesn't change the list_index variable. I.E. I pass it a 2 and list_index stays as a 0. I don't understand why it is failing to make this change, but it seems like it is failing to recognize the list_index variable because it is not within the function?</p>
```<code>list = ["adam", "bob", "carmen"]
list_index = 0

def useful_function_1():
    print(1)

def set_list_index(num):
    list_index == num

def refers_to_list(num):
    print(list[num])

def print_list_index():
    print(list[list_index])

set_list_index(2)
print_list_index()
</code>```

答:
Step 1 to fix: define the list_index as "global"
step 2: remove unneccessary second =

resulting fixed code:

```<code>list = ["adam", "bob", "carmen"]
list_index = 0

def useful_function_1():
    print(1)

def set_list_index(num):
    global list_index
    list_index = num

def refers_to_list(num):
    print(list[num])

def print_list_index():
    print(list[list_index])

set_list_index(2)
print_list_index()
</code>```

Body:
When I try and use the code below, even when I run the set_list_index function it doesn't change the list_index variable. I.E. I pass it a 2 and list_index stays as a 0. I don't understand why it is failing to make this change, but it seems like it is failing to recognize the list_index variable because it is not within the function?

list = ["adam", "bob", "carmen"]
list_index = 0

def useful_function_1():
    print(1)

def set_list_index(num):
    list_index == num

def refers_to_list(num):
    print(list[num])

def print_list_index():
    print(list[list_index])

set_list_index(2)
print_list_index()

Body:
Step 1 to fix: define the list_index as "global"
step 2: remove unneccessary second =

resulting fixed code:

list = ["adam", "bob", "carmen"]
list_index = 0

def useful_function_1():
    print(1)

def set_list_index(num):
    global list_index
    list_index = num

def refers_to_list(num):
    print(list[num])

def print_list_index():
    print(list[list_index])

set_list_index(2)
print_list_index()


问:
Project inside SpringBoot 2.6.0 working, forced to use Log4J1 and JCL redirect working but JUL not
I have a project whereby the latest build is now SpringBoot 2.6.0 (and older one is a WAR for Tomcat 8). I have a sub-project/component that connects to stuff that forces me to use Log4J1. Logback was working beautifully but I've had to disable it (due to Log4J2 eclipsing and breaking the code that requires Log4J1 and also a new vendor component requiring Log4J2 as well).

I've:

disabled Logback by excluding spring-boot-starter-logging

Added a dependency for spring-boot-starter-log4j

Via the Dependency hierarchy tab (in Eclipse) I can see the jcl and jul libraries and in my logs (Console and File appenders) it is clear that SpringBoot (jcl stuff) and any of my project jcl calls are logged, but any JUL are not.

I've read tons of different tickets on here, gleaned together the info and got to this point. So it's all good except I cannot seem to pipe the JUL calls to the Log4J1 setup.

I can see jul-to-slf4j brought in via spring-boot-starter-log4j.

I thought I'd write here as I'm sure it's something simple I've missed but I think I've been staring at it for too long this afternoon! :)

What have I missed?

```<code>        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j</artifactId>
        <version>1.3.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.32</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.32</version>
    </dependency>
</code>```

答:
I got the JUL bits piping via adding this:

```<code>SLF4JBridgeHandler.install();
java.util.logging.LogManager.getLogManager().getLogger("").setLevel( Level.INFO);
</code>```

Which I found on question JUL to SLF4J Bridge

Body:
I have a project whereby the latest build is now SpringBoot 2.6.0 (and older one is a WAR for Tomcat 8). I have a sub-project/component that connects to stuff that forces me to use Log4J1. Logback was working beautifully but I've had to disable it (due to Log4J2 eclipsing and breaking the code that requires Log4J1 and also a new vendor component requiring Log4J2 as well).

I've:

disabled Logback by excluding spring-boot-starter-logging

Added a dependency for spring-boot-starter-log4j

Via the Dependency hierarchy tab (in Eclipse) I can see the jcl and jul libraries and in my logs (Console and File appenders) it is clear that SpringBoot (jcl stuff) and any of my project jcl calls are logged, but any JUL are not.

I've read tons of different tickets on here, gleaned together the info and got to this point. So it's all good except I cannot seem to pipe the JUL calls to the Log4J1 setup.

I can see jul-to-slf4j brought in via spring-boot-starter-log4j.

I thought I'd write here as I'm sure it's something simple I've missed but I think I've been staring at it for too long this afternoon! :)

What have I missed?

        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j</artifactId>
        <version>1.3.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.32</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.32</version>
    </dependency>

Body:
I got the JUL bits piping via adding this:

SLF4JBridgeHandler.install();
java.util.logging.LogManager.getLogManager().getLogger("").setLevel( Level.INFO);

Which I found on question JUL to SLF4J Bridge


问:
How to escape \" in eval ? It throws error: expected identifier
when iam trying to eval :

```<code><span style=\"color: #ff0000;\">
</code>```

It throws error when unexpected identifier. How to escape it?

I get result from server aaaas follows:, the EXT Js (JS framework) reader not able to read it.

```<code>{
    "items": [{
        "id": "671",
        "post_title": "Seche Vite Dry Fast Top Coat",
        "post_content": "<span style=\"color: #ff0000;\"><strong>Roy Recommends:<\/strong>\u00c2\u00a0 Edith, our in-house nail expert, swears by this product.\u00c2\u00a0 No manicure or pedicure is complete without adding this top coat as the finishing touch.<\/span>\r\n\r\nSeche Vite\u00e2\u201e\u00a2 dry fast top coat is widely acknowledged as the world\'s finest top coat.\u00c2\u00a0 Specially formulated to penetrate through nail lacquer to the base coat forming a single solid coating over the nail plate for a much more durable finish. Guaranteed not to yellow while leaving nails silky, stronger and resistant to chipping and peeling.\r\n\r\n ",
        "post_excerpt": "",
        "post_status": "publish",
        "post_parent": "0",
        "parent_sort_id": "671",
        "prod_meta_data_key": "_wpsc_product_metadata",
        "category": "Roy Recommends,Nail Care",
        "_wpsc_price": "10",
        "_wpsc_special_price": "0",
        "_wpsc_sku": "",
        "_wpsc_stock": "4",
        "unpublish_when_none_left": "1",
        "weight": 8.5,
        "weight_unit": "ounce",
        "height": "0",
        "height_unit": "in",
        "width": "0       ",
        "width_unit": "in",
        "length": "0",
        "length_unit": "in",
        "local": "0",
        "international": "0",
        "no_shipping": "0"
    }],
    "totalCount": "1"
}
</code>```

答:
Try to use single quotes instead of double quotes ...

Or instead of html formatting it directly, just send the data and handle the formatting client-side, you know the identifier of the data so you will be able to single it out and format it.

Body:
when iam trying to eval :

It throws error when unexpected identifier. How to escape it?

I get result from server aaaas follows:, the EXT Js (JS framework) reader not able to read it.

{
    "items": [{
        "id": "671",
        "post_title": "Seche Vite Dry Fast Top Coat",
        "post_content": "Roy Recommends:<\/strong>\u00c2\u00a0 Edith, our in-house nail expert, swears by this product.\u00c2\u00a0 No manicure or pedicure is complete without adding this top coat as the finishing touch.<\/span>\r\n\r\nSeche Vite\u00e2\u201e\u00a2 dry fast top coat is widely acknowledged as the world\'s finest top coat.\u00c2\u00a0 Specially formulated to penetrate through nail lacquer to the base coat forming a single solid coating over the nail plate for a much more durable finish. Guaranteed not to yellow while leaving nails silky, stronger and resistant to chipping and peeling.\r\n\r\n ",
        "post_excerpt": "",
        "post_status": "publish",
        "post_parent": "0",
        "parent_sort_id": "671",
        "prod_meta_data_key": "_wpsc_product_metadata",
        "category": "Roy Recommends,Nail Care",
        "_wpsc_price": "10",
        "_wpsc_special_price": "0",
        "_wpsc_sku": "",
        "_wpsc_stock": "4",
        "unpublish_when_none_left": "1",
        "weight": 8.5,
        "weight_unit": "ounce",
        "height": "0",
        "height_unit": "in",
        "width": "0       ",
        "width_unit": "in",
        "length": "0",
        "length_unit": "in",
        "local": "0",
        "international": "0",
        "no_shipping": "0"
    }],
    "totalCount": "1"
}

Body:
Try to use single quotes instead of double quotes <span color='blue'>...</span>

Or instead of html formatting it directly, just send the data and handle the formatting client-side, you know the identifier of the data so you will be able to single it out and format it.


问:
How to check if a value exists in array with .includes?
I know we can use .includes but I've been struggling to get it to work with my array. What I want is for my function to check if the value already exists and if it does to remove it from the array.

The value is a string. That value comes from an object that has .name as a property within the object.

```<code>0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}

1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go'}
</code>```

I mapped through the data and assigned each button with a value of {d.name}

I am using a button to get the value with this function below

and adding the values to 'favs'.

```<code>const favs = [];

  function checkId(e) {
    if (e.target.value !== "")

      favs.push(e.target.value);

      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
    }
</code>```

console.log
favs

```<code>[
    "3-Bit-CNC-Starter-Pack",
    "3-Bit-CNC-Starter-Pack"
]
</code>```

How can I check to see if the value already exists within the array using .includes?

答:
["Sam", "Great", "Sample", "High"].includes("Sam"); // true

if not false

Body:
I know we can use .includes but I've been struggling to get it to work with my array. What I want is for my function to check if the value already exists and if it does to remove it from the array.

The value is a string. That value comes from an object that has .name as a property within the object.

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}

1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go'}

I mapped through the data and assigned each button with a value of {d.name}

I am using a button to get the value with this function below

and adding the values to 'favs'.

const favs = [];

  function checkId(e) {
    if (e.target.value !== "")

      favs.push(e.target.value);

      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
    }

console.log
favs

[
    "3-Bit-CNC-Starter-Pack",
    "3-Bit-CNC-Starter-Pack"
]

How can I check to see if the value already exists within the array using .includes?


问:
TypeScript: Typing a value based on an object key
I need some help on my TypeScript adventure.

Here's my example type:

type Target = {
  names: string[]
  addresses: {
      location: string
    }[]
};
```
<p>Here's my example object:</p>
<pre class="lang-js prettyprint-override"><code>const myTarget: Target = {
  names: ["Alex", "Nico"],
  addresses: [
    {
      location: "Miami",
    },
    {
      location: "New York",
    },
  ],
};
</code>```

And here's my function example:

const changeValue = (
    key: keyof Target,
    value: string | Record<string, unknown>
) => {
 myTarget[key] = [...myTarget[key], value]
}

changeValue('names', 'Elvis')
changeValue('addresses', { location: "Atlanta" })
```

I've an error on the myTarget[key] saying this:

Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[] & { location: string; }[]'.

Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[]'.

Cannot assign type 'string | Record<string, unknown>' of type 'string'.

Cannot assign type 'Record<string, unknown>' to type 'string'
.ts(2322)

From what I understand is that, for example, TypeScript is testing all combinations, including adding an object  to the names array, which is invalid, or adding a string inside addresses array.

Can someone please help me to understand what's the problem and how can I handle it. ( the real project is so much more complicated, but maybe with this example I'll understand a bit..)

Thanks a lot.

答:
In general, where you want to pass a key of an object type and a value of the type of that key, you can do so like this:

```<code>const changeValue = <K extends keyof Target, V extends Target[K]>(
    key: K,
    value: V
) => {
 myTarget[key] = value;
}
</code>```

That is, you tell the compiler that value is not only the same type of some value of the object, but the same type as the one given by key.

However, you upped the difficult by playing with arrays.  There is not, so far as I know, a utility type to extract the type of an array, so I wrote one:

```<code>type ArrayType<T> = T extends Array<infer U>? U : never;
</code>```

Now we can use it:

```<code>const appendValue = <K extends keyof Target, V extends ArrayType<Target[K]>>(
    key: K,
    value: V
) => {
 myTarget[key] = [...myTarget[key], value] as Target[K];
}
</code>```

Unfortunately, as you see, the compiler gets a little confused about the relationship between V[] and Target[K], so it needs the hint in the form of as.

Now the calls compile cleanly:

```<code>appendValue('names', 'Elvis')
appendValue('addresses', { location: "Atlanta" })
</code>```

Incidentally, you do some things in your example code (though perhaps not in your actual code) that I would urge you not to do.

First, you have mutable global data, myTarget.  Hic fons lacrimis, do not do this, in any language, if you can at all avoid it.

Also, mutating data in general is a bad idea.  Consider this instead:

```<code>const appendValue = <K extends keyof Target, V extends ArrayType<Target[K]>>(
    target: Target,
    key: K,
    value: V
): Target => ({
    ...target,
    [key]: [...myTarget[key], value] as Target[K]
})
</code>```

Body:
I need some help on my TypeScript adventure.

Here's my example type:

type Target = {
  names: string[]
  addresses: {
      location: string
    }[]
};

Here's my example object:

const myTarget: Target = {
  names: ["Alex", "Nico"],
  addresses: [
    {
      location: "Miami",
    },
    {
      location: "New York",
    },
  ],
};

And here's my function example:

const changeValue = (
    key: keyof Target,
    value: string | Record<string, unknown>
) => {
 myTarget[key] = [...myTarget[key], value]
}

changeValue('names', 'Elvis')
changeValue('addresses', { location: "Atlanta" })

I've an error on the myTarget[key] saying this:

Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[] & { location: string; }[]'.

Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[]'.

Cannot assign type 'string | Record<string, unknown>' of type 'string'.

Cannot assign type 'Record<string, unknown>' to type 'string'
.ts(2322)

From what I understand is that, for example, TypeScript is testing all combinations, including adding an object  to the names array, which is invalid, or adding a string inside addresses array.

Can someone please help me to understand what's the problem and how can I handle it. ( the real project is so much more complicated, but maybe with this example I'll understand a bit..)

Thanks a lot.

Body:
In general, where you want to pass a key of an object type and a value of the type of that key, you can do so like this:

const changeValue = <K extends keyof Target, V extends Target[K]>(
    key: K,
    value: V
) => {
 myTarget[key] = value;
}

That is, you tell the compiler that value is not only the same type of some value of the object, but the same type as the one given by key.

However, you upped the difficult by playing with arrays.  There is not, so far as I know, a utility type to extract the type of an array, so I wrote one:

type ArrayType<T> = T extends Array<infer U>? U : never;

Now we can use it:

const appendValue = <K extends keyof Target, V extends ArrayType<Target[K]>>(
    key: K,
    value: V
) => {
 myTarget[key] = [...myTarget[key], value] as Target[K];
}

Unfortunately, as you see, the compiler gets a little confused about the relationship between V[] and Target[K], so it needs the hint in the form of as.

Now the calls compile cleanly:

appendValue('names', 'Elvis')
appendValue('addresses', { location: "Atlanta" })

Incidentally, you do some things in your example code (though perhaps not in your actual code) that I would urge you not to do.

First, you have mutable global data, myTarget.  Hic fons lacrimis, do not do this, in any language, if you can at all avoid it.

Also, mutating data in general is a bad idea.  Consider this instead:

const appendValue = <K extends keyof Target, V extends ArrayType<Target[K]>>(
    target: Target,
    key: K,
    value: V
): Target => ({
    ...target,
    [key]: [...myTarget[key], value] as Target[K]
})


问:
Vuetify adaptative grid layout from item list
I have what seems to be a very common issue, but I can get over it.

I have an API query that returns me a list of object.

I want to display it my page as a grid of card filled with the content.

I want my grid to be in 5 column, and the number of row will adapt to the number of element in my list.

I can figure out how to achieve it.

For example: i have a query returning

```<code>items[
   {"id":1,"title":"title1,"description":"description1"}
   {"id":2,"title":"title2,"description":"description2"}
   {"id":3,"title":"title3,"description":"description3"}
   {"id":4,"title":"title4,"description":"description4"}
   {"id":5,"title":"title5,"description":"description5"}
   {"id":6,"title":"title6,"description":"description6"}
   {"id":7,"title":"title7,"description":"description7"}
]
</code>```

My grid as to be made from 7 elements with systematically 5 columns and adaptive rows like:

And if my query returns for example 14 elements, the layout should adapt to look like this:

The closest I was able to get with the code was.

```<code><v-container class="mt-2">
      <h1>Top Rated views</h1>
      <v-row v-for="n in gridDivider" :key="n" class="n === 1 ? 'mb-6' : ''">
        <v-col v-for="(item,index) in Items" :key="index">
          <v-card class="mx-auto" max-width="300">
            <v-img
              class="white--text align-end"
              height="200px"
              src="item.avatar"
            >
              <v-card-title>anything as text</v-card-title>
            </v-img>

            <v-card-subtitle class="pb-0"> Number 10 </v-card-subtitle>

            <v-card-text class="text--primary">
              <div>Whitehaven Beach</div>

              <div>Whitsunday Island, Whitsunday Islands</div>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>
    </v-container>
</code>```

Thanks for helping

答:
It could be done if you change v-row and v-col declarations this way:

<v-row class="five-cols">
  <v-col v-for="(item,index) in Items" :key="index">
...
```
<p>and create a CSS class <code>five-cols</code> using CSS Grid Layouts:</p>
```.five-cols {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
}
```

Example at CodePen

Body:
I have what seems to be a very common issue, but I can get over it.

I have an API query that returns me a list of object.

I want to display it my page as a grid of card filled with the content.

I want my grid to be in 5 column, and the number of row will adapt to the number of element in my list.

I can figure out how to achieve it.

For example: i have a query returning

items[
   {"id":1,"title":"title1,"description":"description1"}
   {"id":2,"title":"title2,"description":"description2"}
   {"id":3,"title":"title3,"description":"description3"}
   {"id":4,"title":"title4,"description":"description4"}
   {"id":5,"title":"title5,"description":"description5"}
   {"id":6,"title":"title6,"description":"description6"}
   {"id":7,"title":"title7,"description":"description7"}
]

My grid as to be made from 7 elements with systematically 5 columns and adaptive rows like:

And if my query returns for example 14 elements, the layout should adapt to look like this:

The closest I was able to get with the code was.

<v-container class="mt-2">

Top Rated views

      <v-row v-for="n in gridDivider" :key="n" class="n === 1 ? 'mb-6' : ''">
        <v-col v-for="(item,index) in Items" :key="index">
          <v-card class="mx-auto" max-width="300">
            <v-img
              class="white--text align-end"
              height="200px"
              src="item.avatar"
            >
              <v-card-title>anything as text</v-card-title>
            </v-img>

            <v-card-subtitle class="pb-0"> Number 10 </v-card-subtitle>

            <v-card-text class="text--primary">

Whitehaven Beach

Whitsunday Island, Whitsunday Islands

            </v-card-text>
          </v-card>
        </v-col>
      </v-row>
    </v-container>

Thanks for helping

Body:
It could be done if you change v-row and v-col declarations this way:

<v-row class="five-cols">
  <v-col v-for="(item,index) in Items" :key="index">
...

and create a CSS class five-cols using CSS Grid Layouts:

.five-cols {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
}

Example at CodePen


问:
Create a Text File in Julia
I have a string

```<code>a = """
---
title: Just a test
author: Me
date: 2022-01-03
---

# Test Header
Some text.
"""
</code>```

from which I want to create a file foobar.jmd. What is the best way of doing this?

答:
```<code>fname = "foobar.jmd"
dirpath = "/tmp"
fpath = joinpath(dirpath, fname)

open(fpath, "w") do file
    write(file, a)
end
</code>```

More examples e.g. here https://en.wikibooks.org/wiki/Introducing_Julia/Working_with_text_files

Title: Create a Text File in Julia

Body:
I have a string

a = """
---
title: Just a test
author: Me
date: 2022-01-03
---

# Test Header
Some text.
"""

from which I want to create a file foobar.jmd. What is the best way of doing this?

Body:
fname = "foobar.jmd"
dirpath = "/tmp"
fpath = joinpath(dirpath, fname)

open(fpath, "w") do file
    write(file, a)
end

More examples e.g. here https://en.wikibooks.org/wiki/Introducing_Julia/Working_with_text_files


问:
Python Cryptography module save/load RSA keys to/from file
Using the Cryptography module for Python,

I want to save my generated private key in a file, to use it later on.

But from the docs I was unable to find the method needed for this.

```<code>from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

# Working RSA encryption you can run for yourself
MESSAGE = 'I am a very secret message'

# Create private key
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

# Create public key
public_key = private_key.public_key()

# Encrypt
ciphertext = public_key.encrypt(
    MESSAGE,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)

# Encrypted text
print ciphertext

# Decrypt
plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)

# Decrypted text
print plaintext

# Print human readable key
pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
)
pem_data = pem.splitlines()
print pem_data

# How to Save//Load
</code>```

I know how to generate keys, but how can I save correctly to a file. By just storing the pem_data in a file and later on loading from that file with
load_pem_public_key?

Since Cryptography is still new for me, I would like to know the correct way of storing RSA keys in a file.

This is my current try,  but I get an error.

ValueError: Could not deserialize key data.

```<code>if os.path.exists('key.pem'):
    print 'file exist'
else:
    f = open(os.path.join(__location__, 'key.pem'), 'w')
    for i in pem_data:
       f.write(i)
    f.close()

with open(os.path.join(__location__, 'key.pem'), "rb") as key_file:
   private_key = serialization.load_pem_private_key(
        key_file.read(),
        password=None,
        backend=default_backend()
    )
</code>```

答:
```<code>import rsa

if __name__ == '__main__':

  (pubkey, privkey) = rsa.newkeys(512, poolsize=4)

  message = b'Say hi!'
  crypto = rsa.encrypt(message, pubkey)

  PRIV_KEY_DST = 'your path to file'
  with open(PRIV_KEY_DST, 'wb+') as f:
    pk = rsa.PrivateKey.save_pkcs1(privkey, format='PEM')
    f.write(pk)
</code>```

Body:
Using the Cryptography module for Python,

I want to save my generated private key in a file, to use it later on.

But from the docs I was unable to find the method needed for this.

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

# Working RSA encryption you can run for yourself
MESSAGE = 'I am a very secret message'

# Create private key
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

# Create public key
public_key = private_key.public_key()

# Encrypt
ciphertext = public_key.encrypt(
    MESSAGE,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)

# Encrypted text
print ciphertext

# Decrypt
plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)

# Decrypted text
print plaintext

# Print human readable key
pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
)
pem_data = pem.splitlines()
print pem_data

# How to Save//Load

I know how to generate keys, but how can I save correctly to a file. By just storing the pem_data in a file and later on loading from that file with
load_pem_public_key?

Since Cryptography is still new for me, I would like to know the correct way of storing RSA keys in a file.

This is my current try,  but I get an error.

ValueError: Could not deserialize key data.

if os.path.exists('key.pem'):
    print 'file exist'
else:
    f = open(os.path.join(__location__, 'key.pem'), 'w')
    for i in pem_data:
       f.write(i)
    f.close()

with open(os.path.join(__location__, 'key.pem'), "rb") as key_file:
   private_key = serialization.load_pem_private_key(
        key_file.read(),
        password=None,
        backend=default_backend()
    )


问:
How to set up codecept.conf.js for both android native and ios native in the same project
I've worked through the docs and am not finding a solution to this problem.  What I'm trying to do is configure codeceptJS properly so as to be able to execute tests against both native iOS and native Android within the same project.  The docs seem to suggest that one can craft test cases which can target both android and iOS at the same time, e.g.

```<code>I.click({android: '//android.widget.Button', ios: '//UIAApplication[1]/UIAWindow[1]/UIAButton[1]'});
</code>```

However, it's not clear how one would configure the appium helper in codecept.conf.js in order to accomplish this, and I have not been able to uncover any documentation that explains it.  In particular, it seems like the Appium helper can accept either an android .apk or an iOS .app / .ipa for app, but not both.

Would appreciate any insight the community might have on how to achiever this.  I can run against with android or iOS via different projects... but I would much rather do both via the same project, and if possible from the same test cases.

答:
You gonna need to configure a script for both android and ios in your package.json, like this:

```<code>"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "ios": "PLATFORM=iOS APP='/path/to/example.app' DEVICE='iPhone 12 Pro Max' VERSION=14.4 npx codeceptjs run --steps",
  "android": "PLATFORM=Android APP='/path/to/example.apk' DEVICE='Pixel 2' VERSION=9 PACKAGE=com.exampleapp ACTIVITY=MainActivity npx codeceptjs run --steps"},
</code>```

Then you can use each of the following commands in terminal:

```<code>npm run ios

npm run android
</code>```

If you are using Appium, so you need to configure your codecept.conf.js file this way:

```<code>  helpers: {
   Appium: {
   //platform: 'Android',
   platform: 'iOS',
   //app: '/path/to/example.apk',
   app: '/path/to/example.app',
   desiredCapabilities: {
    deviceName: 'iPhone 12 Pro Max',
    platformVersion: undefined,
    appPackage: '',
    appActivity: '',
    automationName: 'XCUITest' //in case your xcode version is not updated
  }
 }
</code>```

Body:
I've worked through the docs and am not finding a solution to this problem.  What I'm trying to do is configure codeceptJS properly so as to be able to execute tests against both native iOS and native Android within the same project.  The docs seem to suggest that one can craft test cases which can target both android and iOS at the same time, e.g.

I.click({android: '//android.widget.Button', ios: '//UIAApplication[1]/UIAWindow[1]/UIAButton[1]'});

However, it's not clear how one would configure the appium helper in codecept.conf.js in order to accomplish this, and I have not been able to uncover any documentation that explains it.  In particular, it seems like the Appium helper can accept either an android .apk or an iOS .app / .ipa for app, but not both.

Would appreciate any insight the community might have on how to achiever this.  I can run against with android or iOS via different projects... but I would much rather do both via the same project, and if possible from the same test cases.

Body:
You gonna need to configure a script for both android and ios in your package.json, like this:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "ios": "PLATFORM=iOS APP='/path/to/example.app' DEVICE='iPhone 12 Pro Max' VERSION=14.4 npx codeceptjs run --steps",
  "android": "PLATFORM=Android APP='/path/to/example.apk' DEVICE='Pixel 2' VERSION=9 PACKAGE=com.exampleapp ACTIVITY=MainActivity npx codeceptjs run --steps"},

Then you can use each of the following commands in terminal:

npm run ios

npm run android

If you are using Appium, so you need to configure your codecept.conf.js file this way:

  helpers: {
   Appium: {
   //platform: 'Android',
   platform: 'iOS',
   //app: '/path/to/example.apk',
   app: '/path/to/example.app',
   desiredCapabilities: {
    deviceName: 'iPhone 12 Pro Max',
    platformVersion: undefined,
    appPackage: '',
    appActivity: '',
    automationName: 'XCUITest' //in case your xcode version is not updated
  }
 }


问:
How to get list of supported argument in V (command line)
I have installed v using the official doc on my Ubuntu 20.04 LTS.

The installation was successful as I can check the version:

```<code>$ v version
V 0.2.4 310969a
</code>```

When I tried to see the supported args using help arg, it is resulting in an error.

```<code>$ v help
`v help`: unknown help topic provided. Use `v help` for usage information.
Known help topics:
</code>```

I tried v help, v --help, v -help, v --h, v -h but all resulted in an error.

Thanks.

答:
I'd suggest you just keep checking the documentation. There's some hello world program you can try there. I also saw it mentions, symlink.

( It is recommended to add this folder to the PATH of your environment variables. This can be done with the command v.exe symlink )

Body:
I have installed v using the official doc on my Ubuntu 20.04 LTS.

The installation was successful as I can check the version:

$ v version
V 0.2.4 310969a

When I tried to see the supported args using help arg, it is resulting in an error.

$ v help
`v help`: unknown help topic provided. Use `v help` for usage information.
Known help topics:

I tried v help, v --help, v -help, v --h, v -h but all resulted in an error.

Thanks.


问:
Package ‘XXX’ was installed before R 4.0.0: please re-install it
I am using R 4.0.2.

I manually installed 2 packages from cfcdae and Stats5303lib from here. I followed the instruction here to download Rtools and use it to install packages above.

Problem is

```<code>writeLines('PATH="${RTOOLS40_HOME}\\usr\\bin;${PATH}"', con = "~/.Renviron") # runs fine
Sys.which("make") #works fine
                               make
"C:\\rtools40\\usr\\bin\\make.exe"
install.packages("Stat5303libs_0.7-5.zip",repos=NULL,type="source") # these all run fine
install.packages("cfcdae_0.8-4.zip",repos=NULL,type="source")  # these all run fine
</code>```

However, when I ran into problem below when I tried to run the libraries.

```<code>Error: package or namespace load failed for ‘cfcdae’:
 package ‘cfcdae’ was installed before R 4.0.0: please re-install it
</code>```

I tried below but still in vain.

```<code>update.packages(ask=FALSE, checkBuilt=TRUE)
</code>```

Why is this happening? Is it because the package is too old?

Update:

As requested, i have changed my .libPaths() as below and updated the SessionInfo() as well.

```<code>> .libPaths()
[1] "C:/Users/UserME/Documents/R/win-library/4.0"
[2] "C:/Program Files/R/R-4.0.2/library"

R version 4.0.2 (2020-06-22)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_Hong Kong SAR.1252  LC_CTYPE=English_Hong Kong SAR.1252
[3] LC_MONETARY=English_Hong Kong SAR.1252 LC_NUMERIC=C
[5] LC_TIME=English_Hong Kong SAR.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.4.6        rstudioapi_0.11     magrittr_1.5
 [4] splines_4.0.2       MASS_7.3-51.6       tidyselect_1.1.0
 [7] munsell_0.5.0       statmod_1.4.34      lattice_0.20-41
[10] colorspace_1.4-1    R6_2.4.1            rlang_0.4.6
[13] minqa_1.2.4         dplyr_1.0.0         tools_4.0.2
[16] grid_4.0.2          nlme_3.1-148        gtable_0.3.0
[19] ellipsis_0.3.1      lme4_1.1-23         tibble_3.0.1
[22] lifecycle_0.2.0     numDeriv_2016.8-1.1 crayon_1.3.4
[25] Matrix_1.2-18       nloptr_1.2.2.2      purrr_0.3.4
[28] ggplot2_3.3.2       vctrs_0.3.1         glue_1.4.1
[31] compiler_4.0.2      pillar_1.4.6        generics_0.0.2
[34] scales_1.1.1        boot_1.3-25         lmerTest_3.1-2
[37] pkgconfig_2.0.3
</code>```

答: In a similar situation, I renamed 'site-library' to 'old-site-library', made a new empty 'site-library' folder and proceeded from there successfully.</p>

Body:
I am using R 4.0.2.

I manually installed 2 packages from cfcdae and Stats5303lib from here. I followed the instruction here to download Rtools and use it to install packages above.

Problem is

writeLines('PATH="${RTOOLS40_HOME}\\usr\\bin;${PATH}"', con = "~/.Renviron") # runs fine
Sys.which("make") #works fine
                               make
"C:\\rtools40\\usr\\bin\\make.exe"
install.packages("Stat5303libs_0.7-5.zip",repos=NULL,type="source") # these all run fine
install.packages("cfcdae_0.8-4.zip",repos=NULL,type="source")  # these all run fine

However, when I ran into problem below when I tried to run the libraries.

Error: package or namespace load failed for ‘cfcdae’:
 package ‘cfcdae’ was installed before R 4.0.0: please re-install it

I tried below but still in vain.

update.packages(ask=FALSE, checkBuilt=TRUE)

Why is this happening? Is it because the package is too old?

Update:

As requested, i have changed my .libPaths() as below and updated the SessionInfo() as well.

> .libPaths()
[1] "C:/Users/UserME/Documents/R/win-library/4.0"
[2] "C:/Program Files/R/R-4.0.2/library"

R version 4.0.2 (2020-06-22)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_Hong Kong SAR.1252  LC_CTYPE=English_Hong Kong SAR.1252
[3] LC_MONETARY=English_Hong Kong SAR.1252 LC_NUMERIC=C
[5] LC_TIME=English_Hong Kong SAR.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.4.6        rstudioapi_0.11     magrittr_1.5
 [4] splines_4.0.2       MASS_7.3-51.6       tidyselect_1.1.0
 [7] munsell_0.5.0       statmod_1.4.34      lattice_0.20-41
[10] colorspace_1.4-1    R6_2.4.1            rlang_0.4.6
[13] minqa_1.2.4         dplyr_1.0.0         tools_4.0.2
[16] grid_4.0.2          nlme_3.1-148        gtable_0.3.0
[19] ellipsis_0.3.1      lme4_1.1-23         tibble_3.0.1
[22] lifecycle_0.2.0     numDeriv_2016.8-1.1 crayon_1.3.4
[25] Matrix_1.2-18       nloptr_1.2.2.2      purrr_0.3.4
[28] ggplot2_3.3.2       vctrs_0.3.1         glue_1.4.1
[31] compiler_4.0.2      pillar_1.4.6        generics_0.0.2
[34] scales_1.1.1        boot_1.3-25         lmerTest_3.1-2
[37] pkgconfig_2.0.3


问:
Laravel route model binding without global scope
I have following route group in my laravel 8.0 app:

Route::prefix('offline_transaction')->name('offline_transaction.')->group(function () {
    Route::post('/approve/{transaction:uuid}', [OfflineTransactionController::class, 'approve'])
        ->name('approve');

    Route::post('/reject/{transaction:uuid}', [OfflineTransactionController::class, 'reject'])
        ->name('reject');
});
```
<p>And <code>Transaction</code> model is:</p>
<pre class="lang-php prettyprint-override"><code>
class Transaction extends Model implements CreditBlocker
{
    //....
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new AuthUserScope());
    }
    //....
}
</code>```

And this is my AuthUserScope:

class AuthUserScope implements Scope
{
    private string $fieldName;

    public function __construct($fieldName = 'user_id')
    {
        $this->fieldName = $fieldName;
    }

    public function apply(Builder $builder, Model $model)
    {
        $user = Auth::user();
        if ($user) {
            $builder->where($this->fieldName, $user->id);
        }
    }
}
```

Now the problem is when an admin wants to approve or reject a transaction, 404 Not found error will throws. How can I pass this?

答:
Another approach is that I can use Route::currentRouteNamed in AuthUserScope class as following, which I prefer to use instead of Route::bind:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class AuthUserScope implements Scope
{
    private string $fieldName;

    public function __construct($fieldName = 'user_id')
    {
        $this->fieldName = $fieldName;
    }

    public function apply(Builder $builder, Model $model)
    {
        $user = Auth::user();
        if ($user && !Route::currentRouteNamed('admin.*')) {
            $builder->where($this->fieldName, $user->id);
        }
    }
}
```

Body:
I have following route group in my laravel 8.0 app:

Route::prefix('offline_transaction')->name('offline_transaction.')->group(function () {
    Route::post('/approve/{transaction:uuid}', [OfflineTransactionController::class, 'approve'])
        ->name('approve');

    Route::post('/reject/{transaction:uuid}', [OfflineTransactionController::class, 'reject'])
        ->name('reject');
});

And Transaction model is:

class Transaction extends Model implements CreditBlocker
{
    //....
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new AuthUserScope());
    }
    //....
}

And this is my AuthUserScope:

class AuthUserScope implements Scope
{
    private string $fieldName;

    public function __construct($fieldName = 'user_id')
    {
        $this->fieldName = $fieldName;
    }

    public function apply(Builder $builder, Model $model)
    {
        $user = Auth::user();
        if ($user) {
            $builder->where($this->fieldName, $user->id);
        }
    }
}

Now the problem is when an admin wants to approve or reject a transaction, 404 Not found error will throws. How can I pass this?


问:
Python pandas datafram drop colums where correlation abovethreshold
I have a pandas dataframe (adjusted_data) containing many independent variables and a target variable called RainTomorrow. I found out how I can get the correlation between the independent variables and the target variable by using:

```<code>adjusted_data.corr()['RainTomorrow'][:].abs()
</code>```

I would like to create a new dataframe (adjusted_data_narrowed) that only consists of columns where the correlation value is above a certain threshold. What is the best way to do that?

答:
This is all you need:</p>
```<code>df2 = adjusted_data.corr()['RainTomorrow'][:].abs()
df2[df2>0.05]
</code>```

Body:
I have a pandas dataframe (adjusted_data) containing many independent variables and a target variable called RainTomorrow. I found out how I can get the correlation between the independent variables and the target variable by using:

adjusted_data.corr()['RainTomorrow'][:].abs()

I would like to create a new dataframe (adjusted_data_narrowed) that only consists of columns where the correlation value is above a certain threshold. What is the best way to do that?

Body:
This is all you need:

df2 = adjusted_data.corr()['RainTomorrow'][:].abs()
df2[df2>0.05]