问:
Pytorch LSTM loss constant
I am using Pytorch to train a bilateral LSTM model for sequence labeling. During the training loop, the loss remains constant through all epochs.

After some debugging, I discovered that the grad attribute is always None, even after the first loss.backward() call. As such, the optimizer can't update the gradients and, consequently, the model doesn't learn anything.
How can I fix this issue in order for backpropagation to happen correctly?

This is the class that I used to define the model:

```<code>class biLSTM(nn.Module):
    def __init__(self, embedding_matrix, embedding_size,
                 pad_idx,
                 learning_rate,
                 n_classes):
        super(biLSTM, self).__init__()
        self.lstm_layer_size = 64
        self.embedding_size = embedding_size
        self.embedding_matrix = embedding_matrix
        self.num_layers = 1
        self.n_classes = n_classes

        self.lstm = nn.LSTM(self.embedding_size,
                            self.lstm_layer_size,
                            bidirectional=True,
                            batch_first=True) #input is given in shape (batch_size, seq_len, emb_len, dropout=0.05)

        self.fc = nn.Linear(self.lstm_layer_size * 2, self.n_classes)

        self.hidden = None

    def forward(self, x):
        lstm_out, _ = self.lstm(x)
        logits = self.fc(lstm_out)
        return logits

    def init_state(self, x):
        self.hidden = (torch.zeros(self.num_layers * 2, x.size(0), self.lstm_layer_size).to(device),
                torch.zeros(self.num_layers * 2, x.size(0), self.lstm_layer_size).to(device))

</code>```

In this network, I don´t need the embedding layer, as the input given to the network is already in the shape (batch_size, sequence_length, embedding_size).

The training loop used is the following:

```<code>model = biLSTM(embedding_matrix, EMBEDDING_SIZE, words_idx[PADDING_CLASS], learning_rate, n_classes)
loss_function = nn.CrossEntropyLoss() # CrossEntropyLoss applies log_softmax
optimizer = optim.SGD(model.parameters(), lr=1e-4)

def init_weights(m): #initialize weigths according to a normal distribution
    for name, param in m.named_parameters():
        nn.init.normal_(param.data, mean = 0, std = 0.1)
        param.requires_grad = True

model.apply(init_weights)

def train_model(model, train: pd.DataFrame):
    model.train()

    for epoch in range(num_epochs):
        losses = []
        epoch_loss = 0.0

        for (sentence, label) in train_loader:
            optimizer.zero_grad()

            model.init_state(sentence)

            logits = model(sentence)

            classes = torch.argmax(logits, dim=2)

            loss = loss_function(classes.double(), label.double())
            loss.backward()
            epoch_loss += loss.item()
            losses.append(loss.item())
            optimizer.step()

        print("Epoch: %d, loss: %1.5f, accuracy: %d" % (epoch+1, epoch_loss/sentence.size(0), categorical_accuracy(classes, label, words_idx[PADDING_CLASS])))

train_model(model, train)
</code>```

UPDATE

I managed to find the error - I was passing the output of argmax to the loss_function, which has a gradient always equal to 0.

However, my LSTM is still not performing as expected. For this sequence labeling task, it achieves categorical accuracy of approximately 50% after 20 epochs.
I am not sure what is wrong with the network, as it seems to be well-implemented according to several online tutorials.

Title: Pytorch LSTM loss constant

Body:
I am using Pytorch to train a bilateral LSTM model for sequence labeling. During the training loop, the loss remains constant through all epochs.

After some debugging, I discovered that the grad attribute is always None, even after the first loss.backward() call. As such, the optimizer can't update the gradients and, consequently, the model doesn't learn anything.
How can I fix this issue in order for backpropagation to happen correctly?

This is the class that I used to define the model:

class biLSTM(nn.Module):
    def __init__(self, embedding_matrix, embedding_size,
                 pad_idx,
                 learning_rate,
                 n_classes):
        super(biLSTM, self).__init__()
        self.lstm_layer_size = 64
        self.embedding_size = embedding_size
        self.embedding_matrix = embedding_matrix
        self.num_layers = 1
        self.n_classes = n_classes

        self.lstm = nn.LSTM(self.embedding_size,
                            self.lstm_layer_size,
                            bidirectional=True,
                            batch_first=True) #input is given in shape (batch_size, seq_len, emb_len, dropout=0.05)

        self.fc = nn.Linear(self.lstm_layer_size * 2, self.n_classes)

        self.hidden = None

    def forward(self, x):
        lstm_out, _ = self.lstm(x)
        logits = self.fc(lstm_out)
        return logits

    def init_state(self, x):
        self.hidden = (torch.zeros(self.num_layers * 2, x.size(0), self.lstm_layer_size).to(device),
                torch.zeros(self.num_layers * 2, x.size(0), self.lstm_layer_size).to(device))

In this network, I don´t need the embedding layer, as the input given to the network is already in the shape (batch_size, sequence_length, embedding_size).

The training loop used is the following:

model = biLSTM(embedding_matrix, EMBEDDING_SIZE, words_idx[PADDING_CLASS], learning_rate, n_classes)
loss_function = nn.CrossEntropyLoss() # CrossEntropyLoss applies log_softmax
optimizer = optim.SGD(model.parameters(), lr=1e-4)

def init_weights(m): #initialize weigths according to a normal distribution
    for name, param in m.named_parameters():
        nn.init.normal_(param.data, mean = 0, std = 0.1)
        param.requires_grad = True

model.apply(init_weights)

def train_model(model, train: pd.DataFrame):
    model.train()

    for epoch in range(num_epochs):
        losses = []
        epoch_loss = 0.0

        for (sentence, label) in train_loader:
            optimizer.zero_grad()

            model.init_state(sentence)

            logits = model(sentence)

            classes = torch.argmax(logits, dim=2)

            loss = loss_function(classes.double(), label.double())
            loss.backward()
            epoch_loss += loss.item()
            losses.append(loss.item())
            optimizer.step()

        print("Epoch: %d, loss: %1.5f, accuracy: %d" % (epoch+1, epoch_loss/sentence.size(0), categorical_accuracy(classes, label, words_idx[PADDING_CLASS])))

train_model(model, train)

UPDATE

I managed to find the error - I was passing the output of argmax to the loss_function, which has a gradient always equal to 0.

However, my LSTM is still not performing as expected. For this sequence labeling task, it achieves categorical accuracy of approximately 50% after 20 epochs.
I am not sure what is wrong with the network, as it seems to be well-implemented according to several online tutorials.


来源: stackexchange

问:
Pivot_wider is not working as expected with spark_apply in R
Pivot_wider is not working as expected with spark_apply

[https://github.com/sparklyr/sparklyr/issues/3304]

```<code>d <- data. Frame(
c1 = c(11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12)
, c2 = c(21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22)
, c3 = as.character(as.integer(c(0:12, 0:2)))
, c4 = as.character(as.integer(c(40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,  55)))
, c5 = as.character(as.integer(c(61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76)))
)  %\>% copy_to(sc, ., "tmp", T)

d1 <- d %\>%
spark_apply(function(df)
tidyr::pivot_wider(
df,
id_cols = c(c1, c2),
names_from = c3,
values_from = c(c4, c5)
))
</code>```

#> d1

```<code>#>  c1    c2 c4_0  c4_1  c4_2  c4_3  c4_4  c4_5  c4_6  c4_7  c4_8  c4_9  c5_0  c5_1  c5_2  c5_3  c5_4  c5_5  c5_6  c5_7  c5_8  c5_9
#>   \<dbl\> \<dbl\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\>
#>  1    11    21 40    41    42    43    44    45    46    47    48    49    50    51    52    61    62    63    64    65    66    67
#>  2    12    22 53    54    55    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    74    75    76    NA    NA    NA    NA
</code>```

#> colnames(d1)

```<code>#>  [1] "c1"   "c2"   "c4_0" "c4_1" "c4_2" "c4_3" "c4_4" "c4_5" "c4_6" "c4_7" "c4_8" "c4_9" "c5_0" "c5_1" "c5_2" "c5_3" "c5_4" "c5_5" "c5_6" "c5_7" "c5_8" "c5_9"
</code>```

In C3 we have 13 columns (0 to12) but only 10 (0-9) are generated.
In the results: Values are pivoted correctly but only 9 names are generated. In the result, c4_10 to c4_12 columns are not there but values are present (c5_0 to c5_2). Actual value of c5_0 is getting printed from c5_3.

I am not sure, what is going wring here

I tried different functions with names_repair but no success. Still getting only 9 columns

ContentLicense: CC BY-SA 4.0

Body:
Pivot_wider is not working as expected with spark_apply

[https://github.com/sparklyr/sparklyr/issues/3304]

d <- data. Frame(
c1 = c(11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12)
, c2 = c(21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22)
, c3 = as.character(as.integer(c(0:12, 0:2)))
, c4 = as.character(as.integer(c(40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,  55)))
, c5 = as.character(as.integer(c(61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76)))
)  %\>% copy_to(sc, ., "tmp", T)

d1 <- d %\>%
spark_apply(function(df)
tidyr::pivot_wider(
df,
id_cols = c(c1, c2),
names_from = c3,
values_from = c(c4, c5)
))

#> d1

#>  c1    c2 c4_0  c4_1  c4_2  c4_3  c4_4  c4_5  c4_6  c4_7  c4_8  c4_9  c5_0  c5_1  c5_2  c5_3  c5_4  c5_5  c5_6  c5_7  c5_8  c5_9
#>   \<dbl\> \<dbl\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\> \<chr\>
#>  1    11    21 40    41    42    43    44    45    46    47    48    49    50    51    52    61    62    63    64    65    66    67
#>  2    12    22 53    54    55    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    74    75    76    NA    NA    NA    NA

#> colnames(d1)

#>  [1] "c1"   "c2"   "c4_0" "c4_1" "c4_2" "c4_3" "c4_4" "c4_5" "c4_6" "c4_7" "c4_8" "c4_9" "c5_0" "c5_1" "c5_2" "c5_3" "c5_4" "c5_5" "c5_6" "c5_7" "c5_8" "c5_9"

In C3 we have 13 columns (0 to12) but only 10 (0-9) are generated.
In the results: Values are pivoted correctly but only 9 names are generated. In the result, c4_10 to c4_12 columns are not there but values are present (c5_0 to c5_2). Actual value of c5_0 is getting printed from c5_3.

I am not sure, what is going wring here

I tried different functions with names_repair but no success. Still getting only 9 columns


问:
How to make watchOS use dark variant of color?
I have "Any Appearance" and "Dark" variants set for all my colors. However, the watchOS insists on using the "Any Appearance" instead of the "Dark" color which would make more sense since the watch is only dark mode.

I tried adding .preferredColorScheme(.dark) modifier in my SwiftUI, and also tried adding "Appearance" = "Dark" in my info.plist, but it insists on using the "Any Appearance" color.

How do I tell watchOS to use the dark mode variances of colors?


问:
Make a common shared writable folder in AOSP Android 12
I am compiling my own Android platform (AOSP version 12.1).

I want to basically create a new File("/data/user/somefolder"), that
different processes can write to, i.e. a world-read/write-able folder.

I have the following advantages:

```<code>android:sharedUserId="android.uid.system"
certificate: "platform"
privileged: true
</code>```

However, using common Java calls I can not create the folder unless I set SELinux in permissive mode, and then I still can't set world access rights for the folder.

The system user can make a dir such as:

```<code>drwx------   3 system system  4096 2022-12-09 15:11 somefolder
</code>```

But as can be seen other linux users (and Android users) don't get access to that folder
even with SELinux off.

Question is: What do I have to modify to make this work? Including SELinux changes if you could hint also in that direction.

Body:
I am compiling my own Android platform (AOSP version 12.1).

I want to basically create a new File("/data/user/somefolder"), that
different processes can write to, i.e. a world-read/write-able folder.

I have the following advantages:

android:sharedUserId="android.uid.system"
certificate: "platform"
privileged: true

However, using common Java calls I can not create the folder unless I set SELinux in permissive mode, and then I still can't set world access rights for the folder.

The system user can make a dir such as:

drwx------   3 system system  4096 2022-12-09 15:11 somefolder

But as can be seen other linux users (and Android users) don't get access to that folder
even with SELinux off.

Question is: What do I have to modify to make this work? Including SELinux changes if you could hint also in that direction.


问:
MySql Deadlock on already acquired locks
I encountered a deadlock which puzzles me. I read in a different post Mysql deadlock explanation needed an answer that didn't solve my confusion.
The situation is also caught in another referenced explanation page about SHOW INNODB STATUS.

I'm attaching my instance as well - which is a bit different, as it is locking an index, once with gaps and once without.

But I think the main question is still the same:

If Transaction (2) has lock A , then Transaction (1) is waiting on Lock A, can it be that Transaction (2) will be deadlocked if it asks for lock A again?

This doesn't sound right, although that is what we see in the InnoDb Status.
When I try to recreate directly in MySql, using different tabs for the different transactions - everything works fine, and there is no such deadlock. I'm also attaching my futile attempt to recreate.

I'm probably missing something in my interpretation of the situation and I would greatly appreciate a good explanation.

I am using MySql 5.1, with Hibernate 3.

```<code>------------------------
LATEST DETECTED DEADLOCK
------------------------
110918 14:56:36
*** (1) TRANSACTION:
TRANSACTION 0 40261686, ACTIVE 0 sec, process no 1686, OS thread id 1358170432 updating or deleting
mysql tables in use 1, locked 1
LOCK WAIT 9 lock struct(s), heap size 3024, undo log entries 1
MySQL thread id 101203, query id 77147262 localhost 127.0.0.1 operator Updating
update test_table set created='2011-09-18 14:56:28', customer_id=3, ended=null, lead_id=423, message=null, modified='2011-09-18 14:56:36', priority=0, project_id=74, retries=0, started='2011-09-18 14:56:36', status='PROCESS', user_id=2, inquiry_id=1542 where id=1541
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 7148 n bits 952 index `status` of table `test_table` trx id 0 40261686 lock_mode X locks gap before rec insert intention waiting
*** (2) TRANSACTION:
TRANSACTION 0 40261595, ACTIVE 0 sec, process no 1686, OS thread id 1360034112 updating or deleting, thread declared inside InnoDB 499
mysql tables in use 1, locked 1
9 lock struct(s), heap size 3024, undo log entries 2
MySQL thread id 101209, query id 77147276 localhost 127.0.0.1 operator Updating
update test_table set created='2011-09-18 14:53:22', customer_id=3, ended=null, lead_id=401, message='', modified='2011-09-18 14:56:36', priority=0, project_id=74, retries=3, started='2011-09-18 14:55:46', status='PENDING', user_id=2, inquiry_id=1474 where id=1473
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 0 page no 7148 n bits 952 index `status` of table `test_table` trx id 0 40261595 lock_mode X
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 7148 n bits 952 index `status` of table `test_table` trx id 0 40261595 lock_mode X locks gap before rec insert intention waiting
*** WE ROLL BACK TRANSACTION (1)
</code>```

attempt in recreating (I dropped a few columns that had foreign keys - as they where not mentioned in the InnoDb status) :

1) initial setup:

```<code>DROP TABLE IF EXISTS `knowledge`.`aaa`;
CREATE TABLE  `knowledge`.`aaa` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `message` longtext,
  `status` varchar(16) DEFAULT NULL,
  `priority` int(11) NOT NULL DEFAULT '0',
  `retries` int(8) NOT NULL DEFAULT '0',
  `modified` datetime DEFAULT NULL,
  `customer_id` int(11) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `status` (`status`),
  KEY `customer_id` (`customer_id`) -- ,
  -- CONSTRAINT `aaa_customer_fk` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=515 DEFAULT CHARSET=utf8;

insert into aaa
values (1, '', 'AAA', 0, 0, null, 1);
insert into aaa
values (2, '', 'AAA', 0, 0, null, 1);
insert into aaa
values (3, '', 'AAA', 0, 0, null, 1);
</code>```

2) Transaction 2: Begin transaction (I use the gui)
presumably acquiering the first lock of transaction 2

```<code>select * from aaa where status = 'AAA' for update;
</code>```

3) Transaction 1: Begin transaction
Presumably waiting for the lock - btw, the transaction does wait.

```<code>insert into aaa
values (10, '', 'BBB', 0, 0, null, 1);
</code>```

4) Transaction 2:
presumably trying to wait on the same lock again - btw, this doesn't wait at all.

```<code>update aaa set status = 'BBB' where id = 1;
update aaa set status = 'BBB' where id = 2;
</code>```

now I can commit Transaction 2, and then Transaction 1 and everything is ok... no recreation of the deadlock situation..

ContentLicense: CC BY-SA 3.0

Body:
I encountered a deadlock which puzzles me. I read in a different post Mysql deadlock explanation needed an answer that didn't solve my confusion.
The situation is also caught in another referenced explanation page about SHOW INNODB STATUS.

I'm attaching my instance as well - which is a bit different, as it is locking an index, once with gaps and once without.

But I think the main question is still the same:

If Transaction (2) has lock A , then Transaction (1) is waiting on Lock A, can it be that Transaction (2) will be deadlocked if it asks for lock A again?

This doesn't sound right, although that is what we see in the InnoDb Status.
When I try to recreate directly in MySql, using different tabs for the different transactions - everything works fine, and there is no such deadlock. I'm also attaching my futile attempt to recreate.

I'm probably missing something in my interpretation of the situation and I would greatly appreciate a good explanation.

I am using MySql 5.1, with Hibernate 3.

------------------------
LATEST DETECTED DEADLOCK
------------------------
110918 14:56:36
*** (1) TRANSACTION:
TRANSACTION 0 40261686, ACTIVE 0 sec, process no 1686, OS thread id 1358170432 updating or deleting
mysql tables in use 1, locked 1
LOCK WAIT 9 lock struct(s), heap size 3024, undo log entries 1
MySQL thread id 101203, query id 77147262 localhost 127.0.0.1 operator Updating
update test_table set created='2011-09-18 14:56:28', customer_id=3, ended=null, lead_id=423, message=null, modified='2011-09-18 14:56:36', priority=0, project_id=74, retries=0, started='2011-09-18 14:56:36', status='PROCESS', user_id=2, inquiry_id=1542 where id=1541
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 7148 n bits 952 index `status` of table `test_table` trx id 0 40261686 lock_mode X locks gap before rec insert intention waiting
*** (2) TRANSACTION:
TRANSACTION 0 40261595, ACTIVE 0 sec, process no 1686, OS thread id 1360034112 updating or deleting, thread declared inside InnoDB 499
mysql tables in use 1, locked 1
9 lock struct(s), heap size 3024, undo log entries 2
MySQL thread id 101209, query id 77147276 localhost 127.0.0.1 operator Updating
update test_table set created='2011-09-18 14:53:22', customer_id=3, ended=null, lead_id=401, message='', modified='2011-09-18 14:56:36', priority=0, project_id=74, retries=3, started='2011-09-18 14:55:46', status='PENDING', user_id=2, inquiry_id=1474 where id=1473
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 0 page no 7148 n bits 952 index `status` of table `test_table` trx id 0 40261595 lock_mode X
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 7148 n bits 952 index `status` of table `test_table` trx id 0 40261595 lock_mode X locks gap before rec insert intention waiting
*** WE ROLL BACK TRANSACTION (1)

attempt in recreating (I dropped a few columns that had foreign keys - as they where not mentioned in the InnoDb status) :

1) initial setup:

DROP TABLE IF EXISTS `knowledge`.`aaa`;
CREATE TABLE  `knowledge`.`aaa` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `message` longtext,
  `status` varchar(16) DEFAULT NULL,
  `priority` int(11) NOT NULL DEFAULT '0',
  `retries` int(8) NOT NULL DEFAULT '0',
  `modified` datetime DEFAULT NULL,
  `customer_id` int(11) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `status` (`status`),
  KEY `customer_id` (`customer_id`) -- ,
  -- CONSTRAINT `aaa_customer_fk` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=515 DEFAULT CHARSET=utf8;

insert into aaa
values (1, '', 'AAA', 0, 0, null, 1);
insert into aaa
values (2, '', 'AAA', 0, 0, null, 1);
insert into aaa
values (3, '', 'AAA', 0, 0, null, 1);

2) Transaction 2: Begin transaction (I use the gui)
presumably acquiering the first lock of transaction 2

select * from aaa where status = 'AAA' for update;

3) Transaction 1: Begin transaction
Presumably waiting for the lock - btw, the transaction does wait.

insert into aaa
values (10, '', 'BBB', 0, 0, null, 1);

4) Transaction 2:
presumably trying to wait on the same lock again - btw, this doesn't wait at all.

update aaa set status = 'BBB' where id = 1;
update aaa set status = 'BBB' where id = 2;

now I can commit Transaction 2, and then Transaction 1 and everything is ok... no recreation of the deadlock situation..


问:
Spring JPA mapping: Composite Foreign Key Generating inverted referenced columns
i have a class Pedido that represents the following table :

Here is the code for that entity:

```<code>package com.agilsistemas.construtordepedidos.model;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Essa classe mapeia a tbpedidoentrega, a tabela mais importante e onde a maioria das operações vão ocorrer.
 * @author <a href = 'https://github.com/YuriFernandes150'>Yuri Fernandes</a>
 */
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "tbpedidoentrega")
public class PedidoModel implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_pedido", nullable = false)
    @SequenceGenerator(name = "sqpedido")
    int idPedido;

    @Column(name = "data_pedido", nullable = false)
    LocalDate dataPedido;

    @Column(name = "hora_pedido", nullable = false)
    LocalTime horaPedido;

    @Column(name = "rua")
    String rua;

    @Column(name = "numero")
    String numero;

    @Column(name = "bairro")
    String bairro;

    @Column(name = "complemento")
    String complemento;

    @Column(name = "cidade")
    String cidade;

    @Column(name = "recebimento", columnDefinition = "INTEGER DEFAULT 1")
    int recebimento;

    @Column(name = "total_pedido")
    double totalPedido;

    @ManyToOne(targetEntity = FuncionarioModel.class)
    @JoinColumns(value = {
            @JoinColumn(name = "funcionario", referencedColumnName = "funcionario"),
            @JoinColumn(name = "empresa", referencedColumnName = "empresa") })
    FuncionarioModel fkFuncionario;

    @ManyToOne(targetEntity = ClienteModel.class)
    @JoinColumns(value = {
            @JoinColumn(name = "cliente", referencedColumnName = "codigo", insertable = false, updatable = false),
            @JoinColumn(name = "empresa", referencedColumnName = "empresa", insertable = false, updatable = false) })
    ClienteModel fkCliente;

    //OBS: essa coluna serve para inserir corretamente o ID do cliente, mesmo com o insertable false acima.
    @Column(name = "cliente")
    int idCliente;

    @OneToMany(mappedBy = "pedido", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    List<ItemPedidoModel> itensPedido;

}
</code>```

It generates fine, except for one of the foreign keys. The key that represents tbcadastro is reversed:

As you can see, the foreign key is reversed cliente should reference codigo and empresa should reference empresa.

straner yet, the other foreign key, representing tbfuncionario, generated correctly:

I have tried just reversing the name order:

```<code> @ManyToOne(targetEntity = ClienteModel.class)
    @JoinColumns(value = {
            @JoinColumn(name = "codigo", referencedColumnName = "cliente", insertable = false, updatable = false),
            @JoinColumn(name = "empresa", referencedColumnName = "empresa", insertable = false, updatable = false) })
    ClienteModel fkCliente;
</code>```

And it throws an Error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: referencedColumnNames(cliente, empresa) of com.agilsistemas.construtordepedidos.model.PedidoModel.fkCliente referencing com.agilsistemas.construtordepedidos.model.ClienteModel not mapped to a single property
</code>```

I tried using the PrimaryKeyJoinColumns annotation:

```<code> @ManyToOne(targetEntity = ClienteModel.class)
    @PrimaryKeyJoinColumns(value = {
            @PrimaryKeyJoinColumn(name = "cliente", referencedColumnName = "codigo"),
            @PrimaryKeyJoinColumn(name = "empresa", referencedColumnName = "empresa") })
    ClienteModel fkCliente;
</code>```

But it resulted in extra columns being created:

I also tried using the ´SecondaryTables´ annotation, but could not figure out how it worked.

Can someone help me with this? I searched the site and found nothing related to this.

Thanks in advance.

Body:
i have a class Pedido that represents the following table :

Here is the code for that entity:

package com.agilsistemas.construtordepedidos.model;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Essa classe mapeia a tbpedidoentrega, a tabela mais importante e onde a maioria das operações vão ocorrer.
 * @author Yuri Fernandes
 */
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "tbpedidoentrega")
public class PedidoModel implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_pedido", nullable = false)
    @SequenceGenerator(name = "sqpedido")
    int idPedido;

    @Column(name = "data_pedido", nullable = false)
    LocalDate dataPedido;

    @Column(name = "hora_pedido", nullable = false)
    LocalTime horaPedido;

    @Column(name = "rua")
    String rua;

    @Column(name = "numero")
    String numero;

    @Column(name = "bairro")
    String bairro;

    @Column(name = "complemento")
    String complemento;

    @Column(name = "cidade")
    String cidade;

    @Column(name = "recebimento", columnDefinition = "INTEGER DEFAULT 1")
    int recebimento;

    @Column(name = "total_pedido")
    double totalPedido;

    @ManyToOne(targetEntity = FuncionarioModel.class)
    @JoinColumns(value = {
            @JoinColumn(name = "funcionario", referencedColumnName = "funcionario"),
            @JoinColumn(name = "empresa", referencedColumnName = "empresa") })
    FuncionarioModel fkFuncionario;

    @ManyToOne(targetEntity = ClienteModel.class)
    @JoinColumns(value = {
            @JoinColumn(name = "cliente", referencedColumnName = "codigo", insertable = false, updatable = false),
            @JoinColumn(name = "empresa", referencedColumnName = "empresa", insertable = false, updatable = false) })
    ClienteModel fkCliente;

    //OBS: essa coluna serve para inserir corretamente o ID do cliente, mesmo com o insertable false acima.
    @Column(name = "cliente")
    int idCliente;

    @OneToMany(mappedBy = "pedido", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    List<ItemPedidoModel> itensPedido;

}

It generates fine, except for one of the foreign keys. The key that represents tbcadastro is reversed:

As you can see, the foreign key is reversed cliente should reference codigo and empresa should reference empresa.

straner yet, the other foreign key, representing tbfuncionario, generated correctly:

I have tried just reversing the name order:

 @ManyToOne(targetEntity = ClienteModel.class)
    @JoinColumns(value = {
            @JoinColumn(name = "codigo", referencedColumnName = "cliente", insertable = false, updatable = false),
            @JoinColumn(name = "empresa", referencedColumnName = "empresa", insertable = false, updatable = false) })
    ClienteModel fkCliente;

And it throws an Error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: referencedColumnNames(cliente, empresa) of com.agilsistemas.construtordepedidos.model.PedidoModel.fkCliente referencing com.agilsistemas.construtordepedidos.model.ClienteModel not mapped to a single property

I tried using the PrimaryKeyJoinColumns annotation:

 @ManyToOne(targetEntity = ClienteModel.class)
    @PrimaryKeyJoinColumns(value = {
            @PrimaryKeyJoinColumn(name = "cliente", referencedColumnName = "codigo"),
            @PrimaryKeyJoinColumn(name = "empresa", referencedColumnName = "empresa") })
    ClienteModel fkCliente;

But it resulted in extra columns being created:

I also tried using the ´SecondaryTables´ annotation, but could not figure out how it worked.

Can someone help me with this? I searched the site and found nothing related to this.

Thanks in advance.


问:
How to cypress test a react-router _blank Link
I have a react-router-dom (v6) Link that links to a new page in my SPA in a new tab.

<Link to="print" target="_blank"/>

To test the link with cypress (which does not work with opening new tabs) we remove / modify the target property:

cy.getByTestId('print').invoke('attr', 'target', '_self').should('be.visible').click();

This works but the document is reloaded (we do not want this as this slows the test down a lot).
How can I do a client transition / navigation?


问:
Create-react-app works with nodejs server but not with live-server
If I make an app using create-react-app-offline crao -n test, load the folder into VSCode, and run npm start I can see the app in the browser

However, if I instead run live-server and browse to http://127.0.0.1:8080/public/ I can see React App in the browser page title, but the page is blank.

What am I missing to be able to deploy on live-server, and on any other server, such as apache or xampp?


问:
MudNavGroup - change Title style
I want chage style ONLY of Title in MudNavGroup

`

```<code><MudNavGroup Title="@item.Group.GroupName" Expanded="true"
                 Style="background-color:aqua; font-size:medium">
</code>```

`

this code don't set style ONLY  Title
It change ALL style - Title-style and internal MudNavLink style
Please! help!

I try insert style

`

```<code><MudNavGroup Title="@item.Group.GroupName" Expanded="true"
                 Style="background-color:aqua; font-size:medium">
</code>```

`

but it change Title-style and internal MudNavLink-s styles.
But how change ONLY Title-style?

Title: MudNavGroup - change Title style

Body:
I want chage style ONLY of Title in MudNavGroup

`

<MudNavGroup Title="@item.Group.GroupName" Expanded="true"
                 Style="background-color:aqua; font-size:medium">

`

this code don't set style ONLY  Title
It change ALL style - Title-style and internal MudNavLink style
Please! help!

I try insert style

`

<MudNavGroup Title="@item.Group.GroupName" Expanded="true"
                 Style="background-color:aqua; font-size:medium">

`

but it change Title-style and internal MudNavLink-s styles.
But how change ONLY Title-style?


问:
GithubCodespaces - xdg-open not working for html files
Currently we are using Github Codespaces as part of our development flow (via VSCode Local) and on the language that we are running our app (Elixir), we have a command called open_browser(view) that should open a screenshot of the current UI on some test.

This base container run as Alpine Linux.

Previously, when we were running full local, it should open this screenshot on Chrome and expose to the developer to find out what is happening for this test.

With Codespaces, when we perform the same command nothing happens.

I have done a debug and find out that what this command do is:

xdg-open /tmp/PATH_TO_FILE.html

If i try xdg-open "https://google.com.br" it works fine.
if i try xdg-open "PATH_TO_FILE" nothing happends.

Do someone knows how we can handle this?

Maybe start a firefox/browser service in parallel with the app and make the xdg-open pointing there?

Thanks a lot!

I have tried to install into our codespaces via docker-compose a instance of a firefox
Tried to tune xdg-open as well, with no success.


问:
git: rebase two branches that are interconnected with merge commits
I have a history like:

```<code> A - B - C - D - E                       [master]
         |\
         |  I - J - m1 - K - L - m2 - O  [topic-a]
          \       /             /
            P - R - S ------- T - U      [topic-b]

</code>```

i.e. topic-b is periodically merged into topic-a.

Now I want to rebase both topic-a and topic-B branches onto the new master (E), while also preserving merge commits (but preferably without the need to manually reapply them like the git rebase --rebase-merges seems to require, especially that in my case the rebase does not change the merged files, so the exact same merge result could be automatically taken), so that I can continue my workflow (merging topic-b into topic-a) with the access to all previous merges. So, the expected result is:

```<code>A - B - C - D - E                       [master]
                |\
                |  I' - J' - m1' - K' - L' - m2' - O'  [topic-a]
                 \         /                /
                   P' -  R' - S' -------- T' - U'      [topic-b]

</code>```

The next step for me is to rebase not onto master but onto a completely disjoint master-2 branch, which I'd normally do with rebase --onto.

I have looked at most of the basic git commands, including rebase (with options like --rebase-merges), merge, cherry-pick, apply and am, but none of them or their combination seems to provide the solution.

Body:
I have a history like:

 A - B - C - D - E                       [master]
         |\
         |  I - J - m1 - K - L - m2 - O  [topic-a]
          \       /             /
            P - R - S ------- T - U      [topic-b]

i.e. topic-b is periodically merged into topic-a.

Now I want to rebase both topic-a and topic-B branches onto the new master (E), while also preserving merge commits (but preferably without the need to manually reapply them like the git rebase --rebase-merges seems to require, especially that in my case the rebase does not change the merged files, so the exact same merge result could be automatically taken), so that I can continue my workflow (merging topic-b into topic-a) with the access to all previous merges. So, the expected result is:

A - B - C - D - E                       [master]
                |\
                |  I' - J' - m1' - K' - L' - m2' - O'  [topic-a]
                 \         /                /
                   P' -  R' - S' -------- T' - U'      [topic-b]

The next step for me is to rebase not onto master but onto a completely disjoint master-2 branch, which I'd normally do with rebase --onto.

I have looked at most of the basic git commands, including rebase (with options like --rebase-merges), merge, cherry-pick, apply and am, but none of them or their combination seems to provide the solution.


问:
Github: Pushing to protected branches with fine-grained token
I'm using semantic release in a Github repository to create automatic releases on push.
The release needs to commit package.json and CHANGELOG.md to my protected branch.

I used to provide a personal token from my admin account to allow semantic-release to push to protected branch.
In order to improve security, I wanted to replace the PT through a new fine-grained token.
So I created a fine-grained PT from the same admin account as the old PT and gave it write permission to content.
Unfortunately, that doesn't seem to be enough to push to the protected branch.

Any idea which permission might be needed?

UPDATE:
Not sure this is even supported yet.
I posted the question in the fine-grained personal token feedback discussion


问:
Can not find physical file downloaded by wget
I am new to Google Colab.

I tried to get some CSV data and put them into folder. Here is what I do :

Mount the drive

```<code>from google.colab import drive
drive.mount('/content/drive')
</code>```

Get the file :

```<code>!wget https://github.com/datasciencedojo/datasets/blob/master/titanic.csv -P /drive/MyDrive/test_colab
</code>```

and also I tried:
`

```<code>!wget https://github.com/datasciencedojo/datasets/blob/master/titanic.csv -P /sample_data/folder1
</code>```

Combine them and become :

```<code>from google.colab import drive
drive.mount('/content/drive')
!wget https://github.com/datasciencedojo/datasets/blob/master/titanic.csv -P /drive/MyDrive/test_colab
</code>```

Run it. No error.

Search for the file in those folders. Can not see any files.

Issue List command and I can see that there are some files :

```<code>!ls /sample_data/folder1
!ls /drive/MyDrive/test_colab
</code>```

Outputs :

```<code>titanic.csv  titanic.csv.1  titanic.csv.2
titanic.csv  titanic.csv.1
</code>```

Where are the physic of the files?

Thanks

Body:
I am new to Google Colab.

I tried to get some CSV data and put them into folder. Here is what I do :

Mount the drive

from google.colab import drive
drive.mount('/content/drive')

Get the file :

!wget https://github.com/datasciencedojo/datasets/blob/master/titanic.csv -P /drive/MyDrive/test_colab

and also I tried:
`

!wget https://github.com/datasciencedojo/datasets/blob/master/titanic.csv -P /sample_data/folder1

Combine them and become :

from google.colab import drive
drive.mount('/content/drive')
!wget https://github.com/datasciencedojo/datasets/blob/master/titanic.csv -P /drive/MyDrive/test_colab

Run it. No error.

Search for the file in those folders. Can not see any files.

Issue List command and I can see that there are some files :

!ls /sample_data/folder1
!ls /drive/MyDrive/test_colab

Outputs :

titanic.csv  titanic.csv.1  titanic.csv.2
titanic.csv  titanic.csv.1

Where are the physic of the files?

Thanks


问:
Starting babel takes 80% of startup time when running simple unit tests
I have a pretty big project with lots of modules. When I try to run a simple test like:

```<code>it('foo', () => {
    console.log('Running test');
});
</code>```

the command yarn run jest --runTestsByPath src/simple-test.js takes 10 seconds. Babel will use the transformed JavaScript from the cache.

After doing some profiling, I found that roughly 8 seconds of that are spent loading 32'000 files from node_modules/@babel*.

Is there a way to compile all of this into a single (big) JavaScript file once with webpack and then reuse it for all my tests?

Other than that, is it possible to see why each module is loaded (= which module imports the others) so we can maybe trim this?

Body:
I have a pretty big project with lots of modules. When I try to run a simple test like:

it('foo', () => {
    console.log('Running test');
});

the command yarn run jest --runTestsByPath src/simple-test.js takes 10 seconds. Babel will use the transformed JavaScript from the cache.

After doing some profiling, I found that roughly 8 seconds of that are spent loading 32'000 files from node_modules/@babel*.

Is there a way to compile all of this into a single (big) JavaScript file once with webpack and then reuse it for all my tests?

Other than that, is it possible to see why each module is loaded (= which module imports the others) so we can maybe trim this?


问:
getErros stays empty even when there are errors
My action:

```<code>public function profile(Request $request): Response
    {
        $form = $this->createForm(UserUpdateType::class, options: [
            'action' => $this->generateUrl('app_profile'),
            'method' => 'POST'
        ]);

        if ($request->getMethod() === 'POST') {
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {

            } else {
                dd($form->getErrors());
            }
        }

        return
            $this->renderForm('login/profile.html.twig', [
                'form' => $form
            ])
        ;
    }
</code>```

Giving example with this field:

```<code>->add('_password', PasswordType::class, [
                'label' => 'New Password',
                'attr' => [
                    'class' => 'form-control'
                ],
                'constraints' => [
                    new Length([
                        'min' => 6
                    ])
                ]
            ])
</code>```

Even when I set a password like 123, which is clearly shorter than what is expected (6), getErrors() returns empty array.

Body:
My action:

public function profile(Request $request): Response
    {
        $form = $this->createForm(UserUpdateType::class, options: [
            'action' => $this->generateUrl('app_profile'),
            'method' => 'POST'
        ]);

        if ($request->getMethod() === 'POST') {
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {

            } else {
                dd($form->getErrors());
            }
        }

        return
            $this->renderForm('login/profile.html.twig', [
                'form' => $form
            ])
        ;
    }

Giving example with this field:

->add('_password', PasswordType::class, [
                'label' => 'New Password',
                'attr' => [
                    'class' => 'form-control'
                ],
                'constraints' => [
                    new Length([
                        'min' => 6
                    ])
                ]
            ])

Even when I set a password like 123, which is clearly shorter than what is expected (6), getErrors() returns empty array.


问:
How to get all tooltips to show with Chart.js
Chart.js allows you to show tooltips like this:

This is explained in the official docs here: https://www.chartjs.org/docs/latest/samples/tooltip/content.html

My question is: How can I make all tooltips show at the same time? So instead of having to hover, the tooltip for every point is visible.

Is this something that's possible using Chart.js?


问:
Why I am unable to use Border radius and Border collapse at the simultaneously?
While I am doing my HTML project I was working with tables , At that time I am unable to use Border-radius and Border-collapse at the same time in a table....

Is there any possible way to use them both in a table ....?


问:
How to fix the mobile menu so the logo and "x" button wont disappear & remove space that isn't needed so there won't be a need for a scroll bar
When I scroll down after I've opened the menu bar in mobile and then scroll up, the logo and "x" button disappears and other areas of the page are showing instead. I know that the solution to it is make it so there won't be anything to scrol down since it's a menu bar but I can't find a way to it. I know that one thing that causes a scroll bar to appear is when you have margin and I've checked and no margin.
I've taken a video of the screen but apparentley can't upload a video here...
I've tried using h-screen and h-full, changed fixed property to sticky
Anyway here's the code

```<code>const Navbar = () => {
  const [nav, setNav] = useState(false);
  const { user, logout } = UserAuth();
  const navigate = useNavigate();

  const handleNav = () => {
    setNav(!nav);
  };

  const handleSignOut = async () => {
    try {
      await logout();
      navigate("/");
    } catch (e) {
      console.log(e.message);
    }
  };

  return (
    <div className=" md:rounded-div flex items-center justify-between h-20 font-bold">
      <Link to="/">
        <h1 className="text-2xl">Cryptoboss</h1>
      </Link>
      <div className="hidden md:block">
        <ThemeToggle />
      </div>

      {user?.email ? (
        <div>
          <Link to="/account" className="hidden md:block p-4">
            Account
          </Link>
        </div>
      ) : (
        <div className="hidden md:block">
          <Link to="/signin" className="p-4 hover:text-accent">
            Sign In
          </Link>
          <Link
            to="/signup"
            className="bg-button text-btnText px-5 py-2 ml-2 rounded-2xl shadow-lg hover:shadow-2xl"
          >
            Sign Up
          </Link>
        </div>
      )}

      {/* Menu Icon */}
      <div onClick={handleNav} className="block md:hidden cursor-pointer z-10">
        {nav ? <AiOutlineClose size={20} /> : <AiOutlineMenu size={20} />}
      </div>

      {/* Mobile Menu */}
      <div
        className={
          nav
            ? "md:hidden fixed left-0 top-20 flex flex-col items-center justify-between w-full h-full bg-primary ease-in duration-300 z-10"
            : "fixed left-[-100%] top-20 h-[90%] flex flex-col items-center justify-between ease-in duration-300"
        }
      >
        <ul className="w-full p-4">
          <li onClick={handleNav} className="border-b py-6">
            <Link to="/">Home</Link>
          </li>
          <li onClick={handleNav} className="border-b py-6">
            <Link to="/account">Account</Link>
          </li>
          <li className=" py-6">
            <ThemeToggle />
          </li>

          <div className="flex flex-row ">
            <li>
              <Link to="/signin">
                <button
                  onClick={handleNav}
                  className="flex my-2 py-3 px-10 mr-11 ml-5 bg-primary text-primary border border-secondary rounded-2xl shadow-xl"
                >
                  Sign In
                </button>
              </Link>
            </li>
            <li>
              <Link onClick={handleNav} to="/signup">
                <button className="flex my-2 py-3 px-10 bg-button text-btnText rounded-2xl shadow-xl">
                  Sign Up
                </button>
              </Link>
            </li>
          </div>
        </ul>
        {/* <div className="flex flex-col w-full h-screen inline-block p-4"></div> */}
      </div>
    </div>
  );
};

export default Navbar;

</code>```

I believe that the change that needs to be done is in the div below:

```<code><div
        className={
          nav
            ? "md:hidden fixed left-0 top-20 flex flex-col items-center justify-between w-full h-full bg-primary ease-in duration-300 z-10"
            : "fixed left-[-100%] top-20 h-[90%] flex flex-col items-center justify-between ease-in duration-300"
        }
</code>```

Body:
When I scroll down after I've opened the menu bar in mobile and then scroll up, the logo and "x" button disappears and other areas of the page are showing instead. I know that the solution to it is make it so there won't be anything to scrol down since it's a menu bar but I can't find a way to it. I know that one thing that causes a scroll bar to appear is when you have margin and I've checked and no margin.
I've taken a video of the screen but apparentley can't upload a video here...
I've tried using h-screen and h-full, changed fixed property to sticky
Anyway here's the code

const Navbar = () => {
  const [nav, setNav] = useState(false);
  const { user, logout } = UserAuth();
  const navigate = useNavigate();

  const handleNav = () => {
    setNav(!nav);
  };

  const handleSignOut = async () => {
    try {
      await logout();
      navigate("/");
    } catch (e) {
      console.log(e.message);
    }
  };

  return (

      <Link to="/">

Cryptoboss

      </Link>

        <ThemeToggle />

      {user?.email ? (

          <Link to="/account" className="hidden md:block p-4">
            Account
          </Link>

      ) : (

          <Link to="/signin" className="p-4 hover:text-accent">
            Sign In
          </Link>
          <Link
            to="/signup"
            className="bg-button text-btnText px-5 py-2 ml-2 rounded-2xl shadow-lg hover:shadow-2xl"
          >
            Sign Up
          </Link>

      )}

      {/* Menu Icon */}

        {nav ? <AiOutlineClose size={20} /> : <AiOutlineMenu size={20} />}

      {/* Mobile Menu */}

            <Link to="/">Home</Link>

            <Link to="/account">Account</Link>

            <ThemeToggle />

              <Link to="/signin">
                <button
                  onClick={handleNav}
                  className="flex my-2 py-3 px-10 mr-11 ml-5 bg-primary text-primary border border-secondary rounded-2xl shadow-xl"
                >
                  Sign In
                </button>
              </Link>

              <Link onClick={handleNav} to="/signup">
                <button className="flex my-2 py-3 px-10 bg-button text-btnText rounded-2xl shadow-xl">
                  Sign Up
                </button>
              </Link>

        {/*

 */}

  );
};

export default Navbar;

I believe that the change that needs to be done is in the div below:

<div
        className={
          nav
            ? "md:hidden fixed left-0 top-20 flex flex-col items-center justify-between w-full h-full bg-primary ease-in duration-300 z-10"
            : "fixed left-[-100%] top-20 h-[90%] flex flex-col items-center justify-between ease-in duration-300"
        }


问:
Poll API every 2 seconds and update state until result turns successful/failure - React
I have an array of ids and I need to loop through the array and call an API with the id. The response from the API will have a Status field which ranges from [0,1,2,-1]. I want to call the API and update the state with the responses. I have a working code which has a Promise which gets resolved only if the Status is Finished or Failed. How do I go over about updating the state even while the Status is in Started and Queued.

This is my code.

```<code>import React from 'react';
import './style.css';
import { get, includes, keys, forEach, map } from 'lodash';

const Status = {
  Queued: 0,
  Started: 1,
  Finished: 2,
  Failed: -1,
};

/**
 * Keeps getting data every 2.5 seconds
 * If path is Status, keep calling the API every 2.5 seconds until Status is Finished or Failed, and then resolve
 * @param url
 * @param path
 */

/**
 * The MAP where the list of timers are stored
 */
let dataFetchingTimerMap = {};

const clearDataFetchingTimer = (key) => {
  /**
   * Clear the timeout
   */
  clearTimeout(dataFetchingTimerMap[key]);
  /**
   * Delete the key
   */
  delete dataFetchingTimerMap[key];
};

const setDataFetchingTimer = (key, cb, delay) => {
  /**
   * Save the timeout with a key
   */
  dataFetchingTimerMap[key] = window.setTimeout(() => {
    /**
     * Delete key when it executes
     */
    clearDataFetchingTimer(key);
    /**
     * Execute the callback (loop function)
     */
    cb();
  }, delay);
};

export const getDataAtIntervals = (url, path) => {
  const timerKey = `${url}_${path}`;

  clearTimeout(+timerKey);
  return new Promise((resolve, reject) => {
    (async function loop() {
      try {
        const resultData = await fetch(url);
        const result = await resultData.json();
        if (
          get(result, path) &&
          includes(
            [Status.Finished, Status.Failed, Status.FailedWithReturnFile],
            get(result, path)
          )
        ) {
          /**
           * Resolve with the data
           */
          return resolve(result);
        }
        setDataFetchingTimer(timerKey, loop, 2500);
      } catch (e) {
        reject(e);
      }
    })();
  });
};

/**
 * Clear every timeout
 */
export const clearGetDataAtIntervals = () =>
  forEach(keys(dataFetchingTimerMap), clearDataFetchingTimer);

export default function App() {
  const [state, setState] = React.useState([]);
  const handleClick = async () => {
    const ids = [1, 2, 3];
    const responses = await Promise.all(
      map(
        ids,
        async (id) =>
          await getDataAtIntervals(
            `https://jsonplaceholder.typicode.com/todos/${id}`,
            'completed'
          )
      )
    );
    setState(responses);
  };
  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}
</code>```

Please advice. This is my Stackblitz link:

https://stackblitz.com/edit/react-dos3i3?file=src%2FApp.js,src%2Findex.js

Body:
I have an array of ids and I need to loop through the array and call an API with the id. The response from the API will have a Status field which ranges from [0,1,2,-1]. I want to call the API and update the state with the responses. I have a working code which has a Promise which gets resolved only if the Status is Finished or Failed. How do I go over about updating the state even while the Status is in Started and Queued.

This is my code.

import React from 'react';
import './style.css';
import { get, includes, keys, forEach, map } from 'lodash';

const Status = {
  Queued: 0,
  Started: 1,
  Finished: 2,
  Failed: -1,
};

/**
 * Keeps getting data every 2.5 seconds
 * If path is Status, keep calling the API every 2.5 seconds until Status is Finished or Failed, and then resolve
 * @param url
 * @param path
 */

/**
 * The MAP where the list of timers are stored
 */
let dataFetchingTimerMap = {};

const clearDataFetchingTimer = (key) => {
  /**
   * Clear the timeout
   */
  clearTimeout(dataFetchingTimerMap[key]);
  /**
   * Delete the key
   */
  delete dataFetchingTimerMap[key];
};

const setDataFetchingTimer = (key, cb, delay) => {
  /**
   * Save the timeout with a key
   */
  dataFetchingTimerMap[key] = window.setTimeout(() => {
    /**
     * Delete key when it executes
     */
    clearDataFetchingTimer(key);
    /**
     * Execute the callback (loop function)
     */
    cb();
  }, delay);
};

export const getDataAtIntervals = (url, path) => {
  const timerKey = `${url}_${path}`;

  clearTimeout(+timerKey);
  return new Promise((resolve, reject) => {
    (async function loop() {
      try {
        const resultData = await fetch(url);
        const result = await resultData.json();
        if (
          get(result, path) &&
          includes(
            [Status.Finished, Status.Failed, Status.FailedWithReturnFile],
            get(result, path)
          )
        ) {
          /**
           * Resolve with the data
           */
          return resolve(result);
        }
        setDataFetchingTimer(timerKey, loop, 2500);
      } catch (e) {
        reject(e);
      }
    })();
  });
};

/**
 * Clear every timeout
 */
export const clearGetDataAtIntervals = () =>
  forEach(keys(dataFetchingTimerMap), clearDataFetchingTimer);

export default function App() {
  const [state, setState] = React.useState([]);
  const handleClick = async () => {
    const ids = [1, 2, 3];
    const responses = await Promise.all(
      map(
        ids,
        async (id) =>
          await getDataAtIntervals(
            `https://jsonplaceholder.typicode.com/todos/${id}`,
            'completed'
          )
      )
    );
    setState(responses);
  };
  return (

Hello StackBlitz!

Start editing to see some magic happen :)

      <button onClick={handleClick}>Click me</button>

  );
}

Please advice. This is my Stackblitz link:

https://stackblitz.com/edit/react-dos3i3?file=src%2FApp.js,src%2Findex.js


问:
WebClient Flux to List not working with block
I am new to webclient. I have create a generic common library for inter microservice communication.

I am trying to post some data to get persist using webclient which works fine and able to get the data as well.

Now I need to some business logic on the return data by the web client. For that I am trying to convert the Flux to List of object, I am getting

```<code> java.lang.IllegalStateException: block()/blockFirst()/blockLast() are
     * blocking, which is not supported in thread reactor-http-nio-3
</code>```

Code:

```<code>    @Override
public Flux<EmployeeDTO> getAllEmployees() {
    WebClientRequest<EmployeeDTO> employeeWebClientRequest = new WebClientRequest<>();
    employeeWebClientRequest.setRequestTracker(UUID.randomUUID().toString());
    employeeWebClientRequest.setContentType("application/json");
    EmployeeDTO employeeDTO = new EmployeeDTO();
    employeeDTO.setEmployeeName("MTRS");
    employeeDTO.setFirstname("MT");
    employeeDTO.setLastName("RS");
    employeeWebClientRequest.setWebClientBody(employeeDTO);
    employeeWebClientRequest.setEndPoint("http://localhost:8080/api/employees");
    Flux<EmployeeDTO> postListAsynchronousWebClient = webClientEmployee
            .postListAsynchronousWebClient(employeeWebClientRequest, EmployeeDTO.class);
    List<EmployeeDTO> block = postListAsynchronousWebClient.collectList().block();// Failing Line
    /*
     *
     * java.lang.IllegalStateException: block()/blockFirst()/blockLast() are
     * blocking, which is not supported in thread reactor-http-nio-3 at
     * reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83)
     * ~[reactor-core-3.4.21.jar:3.4.21] Suppressed:
     * reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
     */
    return postListAsynchronousWebClient;
}

    public <T> Flux<K> postListAsynchronousWebClient(WebClientRequest<T> webClientRequest, Class<K> clazz) {
    if (null == webClientRequest.getRequestTracker()) {
        return Flux.error(new MtampWebClientException("", requestTrackerErrorCode, requestTrackerErrorMessage));
    }
    ResponseSpec retrieve = performPostWebRequest(webClientRequest);
    return retrieve.bodyToFlux(clazz).doOnNext(resp -> webClientResponse(webClientRequest, resp));
}

 private <T> ResponseSpec performPostWebRequest(WebClientRequest<T> webClientRequest) {
    WebClient client = webClientBuilder();
    client.get().headers(h-> System.out.println(h));
    LinkedMultiValueMap<String, String> map = setHeaders(webClientRequest);
    Consumer<HttpHeaders> consumer = it -> it.addAll(map);
    ResponseSpec retrieve;
    if (null != webClientRequest.getPathParam()) {
        retrieve = client.post().uri(webClientRequest.getEndPoint() + "/" + webClientRequest.getPathParam())
                .bodyValue(webClientRequest.getWebClientBody()).headers(consumer).retrieve();
    } else {

        retrieve = client.post().uri(webClientRequest.getEndPoint()).bodyValue(webClientRequest.getWebClientBody())
                .headers(consumer).retrieve();

    }
    return retrieve;
}

 private WebClient webClientBuilder() {
    HttpClient httpClient = HttpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, webClientTimeOut)
            .responseTimeout(Duration.ofMillis(webClientResponseTimeOut)).doOnConnected(
                    conn -> conn.addHandlerLast(new ReadTimeoutHandler(webClientReadTimeOut, TimeUnit.MILLISECONDS))
                            .addHandlerLast(new WriteTimeoutHandler(webClientWriteTimeOut, TimeUnit.MILLISECONDS)));
    return WebClient.builder().filter(new WebClientFilter()).filter(ExchangeFilterFunction.ofResponseProcessor(this::errorHandler))
            .clientConnector(new ReactorClientHttpConnector(httpClient)).build();

}
</code>```

The whole exception log below:

```<code>        java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3
        at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.4.21.jar:3.4.21]
        Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
    Error has been observed at the following site(s):
        *__checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
        *__checkpoint ⇢ HTTP GET "/api/employees" [ExceptionHandlingWebHandler]
    Original Stack Trace:
            at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Mono.block(Mono.java:1707) ~[reactor-core-3.4.21.jar:3.4.21]
            at com.mt.mtamp.webclient.service.impl.WebClientServiceImpl.getAllEmployees(WebClientServiceImpl.java:71) ~[classes/:na]
            at com.mt.mtamp.webclient.controller.WebClientController.getAllEmployees(WebClientController.java:50) ~[classes/:na]
            at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
            at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
            at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
            at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
            at org.springframework.web.reactive.result.method.InvocableHandlerMethod.lambda$invoke$0(InvocableHandlerMethod.java:144) ~[spring-webflux-5.3.22.jar:5.3.22]
            at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:152) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:240) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onComplete(MonoIgnoreThen.java:203) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoFlatMap$FlatMapMain.onComplete(MonoFlatMap.java:181) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Operators.complete(Operators.java:137) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoZip.subscribe(MonoZip.java:120) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Mono.subscribe(Mono.java:4397) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:263) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:157) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:74) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:82) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.innerNext(FluxConcatMap.java:282) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onNext(FluxConcatMap.java:863) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:129) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:180) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2398) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.request(MonoPeekTerminal.java:139) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request(FluxMapFuseable.java:171) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2194) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onSubscribe(Operators.java:2068) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe(FluxMapFuseable.java:96) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onSubscribe(MonoPeekTerminal.java:152) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:55) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Mono.subscribe(Mono.java:4397) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:451) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onSubscribe(FluxConcatMap.java:219) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Mono.subscribe(Mono.java:4397) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:263) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDeferContextual.subscribe(MonoDeferContextual.java:55) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.netty.http.server.HttpServer$HttpServerHandle.onStateChange(HttpServer.java:967) ~[reactor-netty-http-1.0.21.jar:1.0.21]
            at reactor.netty.ReactorNetty$CompositeConnectionObserver.onStateChange(ReactorNetty.java:677) ~[reactor-netty-core-1.0.21.jar:1.0.21]
            at reactor.netty.transport.ServerTransport$ChildObserver.onStateChange(ServerTransport.java:478) ~[reactor-netty-core-1.0.21.jar:1.0.21]
            at reactor.netty.http.server.HttpServerOperations.onInboundNext(HttpServerOperations.java:570) ~[reactor-netty-http-1.0.21.jar:1.0.21]
            at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:93) ~[reactor-netty-core-1.0.21.jar:1.0.21]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at reactor.netty.http.server.HttpTrafficHandler.channelRead(HttpTrafficHandler.java:222) ~[reactor-netty-http-1.0.21.jar:1.0.21]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:327) ~[netty-codec-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:299) ~[netty-codec-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[netty-common-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.79.Final.jar:4.1.79.Final]
            at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
</code>```

Body:
I am new to webclient. I have create a generic common library for inter microservice communication.

I am trying to post some data to get persist using webclient which works fine and able to get the data as well.

Now I need to some business logic on the return data by the web client. For that I am trying to convert the Flux to List of object, I am getting

 java.lang.IllegalStateException: block()/blockFirst()/blockLast() are
     * blocking, which is not supported in thread reactor-http-nio-3

Code:

    @Override
public Flux<EmployeeDTO> getAllEmployees() {
    WebClientRequest<EmployeeDTO> employeeWebClientRequest = new WebClientRequest<>();
    employeeWebClientRequest.setRequestTracker(UUID.randomUUID().toString());
    employeeWebClientRequest.setContentType("application/json");
    EmployeeDTO employeeDTO = new EmployeeDTO();
    employeeDTO.setEmployeeName("MTRS");
    employeeDTO.setFirstname("MT");
    employeeDTO.setLastName("RS");
    employeeWebClientRequest.setWebClientBody(employeeDTO);
    employeeWebClientRequest.setEndPoint("http://localhost:8080/api/employees");
    Flux<EmployeeDTO> postListAsynchronousWebClient = webClientEmployee
            .postListAsynchronousWebClient(employeeWebClientRequest, EmployeeDTO.class);
    List<EmployeeDTO> block = postListAsynchronousWebClient.collectList().block();// Failing Line
    /*
     *
     * java.lang.IllegalStateException: block()/blockFirst()/blockLast() are
     * blocking, which is not supported in thread reactor-http-nio-3 at
     * reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83)
     * ~[reactor-core-3.4.21.jar:3.4.21] Suppressed:
     * reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
     */
    return postListAsynchronousWebClient;
}

    public <T> Flux<K> postListAsynchronousWebClient(WebClientRequest<T> webClientRequest, Class<K> clazz) {
    if (null == webClientRequest.getRequestTracker()) {
        return Flux.error(new MtampWebClientException("", requestTrackerErrorCode, requestTrackerErrorMessage));
    }
    ResponseSpec retrieve = performPostWebRequest(webClientRequest);
    return retrieve.bodyToFlux(clazz).doOnNext(resp -> webClientResponse(webClientRequest, resp));
}

 private <T> ResponseSpec performPostWebRequest(WebClientRequest<T> webClientRequest) {
    WebClient client = webClientBuilder();
    client.get().headers(h-> System.out.println(h));
    LinkedMultiValueMap<String, String> map = setHeaders(webClientRequest);
    Consumer<HttpHeaders> consumer = it -> it.addAll(map);
    ResponseSpec retrieve;
    if (null != webClientRequest.getPathParam()) {
        retrieve = client.post().uri(webClientRequest.getEndPoint() + "/" + webClientRequest.getPathParam())
                .bodyValue(webClientRequest.getWebClientBody()).headers(consumer).retrieve();
    } else {

        retrieve = client.post().uri(webClientRequest.getEndPoint()).bodyValue(webClientRequest.getWebClientBody())
                .headers(consumer).retrieve();

    }
    return retrieve;
}

 private WebClient webClientBuilder() {
    HttpClient httpClient = HttpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, webClientTimeOut)
            .responseTimeout(Duration.ofMillis(webClientResponseTimeOut)).doOnConnected(
                    conn -> conn.addHandlerLast(new ReadTimeoutHandler(webClientReadTimeOut, TimeUnit.MILLISECONDS))
                            .addHandlerLast(new WriteTimeoutHandler(webClientWriteTimeOut, TimeUnit.MILLISECONDS)));
    return WebClient.builder().filter(new WebClientFilter()).filter(ExchangeFilterFunction.ofResponseProcessor(this::errorHandler))
            .clientConnector(new ReactorClientHttpConnector(httpClient)).build();

}

The whole exception log below:

        java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3
        at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.4.21.jar:3.4.21]
        Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
    Error has been observed at the following site(s):
        *__checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
        *__checkpoint ⇢ HTTP GET "/api/employees" [ExceptionHandlingWebHandler]
    Original Stack Trace:
            at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Mono.block(Mono.java:1707) ~[reactor-core-3.4.21.jar:3.4.21]
            at com.mt.mtamp.webclient.service.impl.WebClientServiceImpl.getAllEmployees(WebClientServiceImpl.java:71) ~[classes/:na]
            at com.mt.mtamp.webclient.controller.WebClientController.getAllEmployees(WebClientController.java:50) ~[classes/:na]
            at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
            at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
            at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
            at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
            at org.springframework.web.reactive.result.method.InvocableHandlerMethod.lambda$invoke$0(InvocableHandlerMethod.java:144) ~[spring-webflux-5.3.22.jar:5.3.22]
            at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:152) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:240) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onComplete(MonoIgnoreThen.java:203) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoFlatMap$FlatMapMain.onComplete(MonoFlatMap.java:181) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Operators.complete(Operators.java:137) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoZip.subscribe(MonoZip.java:120) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Mono.subscribe(Mono.java:4397) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:263) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:157) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:74) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:82) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.innerNext(FluxConcatMap.java:282) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onNext(FluxConcatMap.java:863) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:129) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:180) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2398) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.request(MonoPeekTerminal.java:139) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request(FluxMapFuseable.java:171) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2194) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onSubscribe(Operators.java:2068) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe(FluxMapFuseable.java:96) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onSubscribe(MonoPeekTerminal.java:152) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:55) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Mono.subscribe(Mono.java:4397) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:451) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onSubscribe(FluxConcatMap.java:219) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.Mono.subscribe(Mono.java:4397) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:263) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.core.publisher.MonoDeferContextual.subscribe(MonoDeferContextual.java:55) ~[reactor-core-3.4.21.jar:3.4.21]
            at reactor.netty.http.server.HttpServer$HttpServerHandle.onStateChange(HttpServer.java:967) ~[reactor-netty-http-1.0.21.jar:1.0.21]
            at reactor.netty.ReactorNetty$CompositeConnectionObserver.onStateChange(ReactorNetty.java:677) ~[reactor-netty-core-1.0.21.jar:1.0.21]
            at reactor.netty.transport.ServerTransport$ChildObserver.onStateChange(ServerTransport.java:478) ~[reactor-netty-core-1.0.21.jar:1.0.21]
            at reactor.netty.http.server.HttpServerOperations.onInboundNext(HttpServerOperations.java:570) ~[reactor-netty-http-1.0.21.jar:1.0.21]
            at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:93) ~[reactor-netty-core-1.0.21.jar:1.0.21]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at reactor.netty.http.server.HttpTrafficHandler.channelRead(HttpTrafficHandler.java:222) ~[reactor-netty-http-1.0.21.jar:1.0.21]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:327) ~[netty-codec-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:299) ~[netty-codec-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496) ~[netty-transport-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[netty-common-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.79.Final.jar:4.1.79.Final]
            at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.79.Final.jar:4.1.79.Final]
            at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]


问:
How to get indices of elements barring consecutive repeats except first and last element of the repeated sequence?
I have an array where each element is either a 0 or a 1 in any random order. I am trying to write a function that will output the indices of elements such that any consecutive 1s or 0s are excluded excepting the start and end of any consecutive sequence.

For example if the input is [0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1] then the output would be [0, 1, 2, 4, 5, 9, 10, 11, 12, 13, 14]

My attempt #1:

```<code>function findIndices(arr) {
  let result = [], previous = null;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== previous) {
      result.push(i);
    }
    previous = arr[i];
  }
  return result;
}
</code>```

Which incorrectly outputs:

```<code>[0, 1, 2, 5, 10, 12, 13, 14]
</code>```

Attempt #2:

```<code>function findIndices(arr) {
  let indices = [];
  let prev = null;
  for (let i = 0; i < arr.length; i++) {
    let current = arr[i];
    if (current !== prev || i === 0) {
      indices.push(i);
    }
    if (current === 1 && arr[i + 1] === 0) {
      indices.push(i + 1);
    }
    prev = current;
  }
  return indices;
}
</code>```

This outputs (also incorrectly):

```<code>[
   0,  1,  2,  2,  5,
  10, 10, 12, 13, 13,
  14
]
</code>```

How do I write this function?

Body:
I have an array where each element is either a 0 or a 1 in any random order. I am trying to write a function that will output the indices of elements such that any consecutive 1s or 0s are excluded excepting the start and end of any consecutive sequence.

For example if the input is [0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1] then the output would be [0, 1, 2, 4, 5, 9, 10, 11, 12, 13, 14]

My attempt #1:

function findIndices(arr) {
  let result = [], previous = null;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== previous) {
      result.push(i);
    }
    previous = arr[i];
  }
  return result;
}

Which incorrectly outputs:

[0, 1, 2, 5, 10, 12, 13, 14]

Attempt #2:

function findIndices(arr) {
  let indices = [];
  let prev = null;
  for (let i = 0; i < arr.length; i++) {
    let current = arr[i];
    if (current !== prev || i === 0) {
      indices.push(i);
    }
    if (current === 1 && arr[i + 1] === 0) {
      indices.push(i + 1);
    }
    prev = current;
  }
  return indices;
}

This outputs (also incorrectly):

[
   0,  1,  2,  2,  5,
  10, 10, 12, 13, 13,
  14
]

How do I write this function?


问:
react @types conflicts with typescript dom types
Is there a way to specifically import types from typescript dom and not from react? Types from react seem to not be correct.


问:
Why is the TERM variable overwritten after each ssh reconnection?
I am using ubuntu 22.10.

In order for this tmux theme to work, I need to assign the value xterm-256color to the TERM variable.

But after each reconnection, the variable is assigned the value xterm.

How to fix it?


问:
Fix Beginning of Time Series Plot - It Is Wildly Distorted
Regardless of the time frame I put on this chart (i.e. 10yrs, 20yrs, 25yrs), the data in the beginning is always distorted -- i.e. very high or very low -- on the chart.

I thought it was a min_periods issue, but that doesn't seem to be it.

Appreciate any insight!

Tried making sure that there were no N/As in the calculation columns.

Tried changing min_periods to be larger.

No change.

What's charted on the bottom subplot is sharpe_rf in the code below.

```<code>asset1          = 'XLY Equity'
asset2          = 'USGG10YR Index'

#-------------Dataframe 1: Price Data from Multiple Securities-------------#
sids            = mgr[asset1, asset2]
d               = sids.get_historical(prices,start=startD,end=endD)
df              = pd.DataFrame(d)
df              = df.dropna()

df.columns      = ['Asset', 'Risk Free Rate']

#------------Returns and Standard Deviation---------------#
log_return          = np.log(df['Asset']) - np.log(df['Asset'].shift(1))
ten_day_return      = log_return.rolling(min_periods=10, window=30, center=False).sum()
std_20d             = df['Asset'].rolling(min_periods=10, window=30, center=False).std()
max_std_today       = std_20d.max() - std_20d

#------------Moving Averages------------#
ma_50               = df['Asset'].rolling(min_periods=10, window=50, center=False).mean()
ma_100              = df['Asset'].rolling(min_periods=10, window=100, center=False).mean()
ma_200              = df['Asset'].rolling(min_periods=10, window=200, center=False).mean()

# #------------Rolling Sharpe Ratio------------#
lookback            = 252
daily_returns       = log_return[1:]
std_returns         = daily_returns.rolling(min_periods=10,window=lookback,center=False).std()
std_returns         = std_returns.dropna()

avg_daily_return    = daily_returns.rolling(min_periods=10,window=lookback,center=False).mean()
avg_daily_return    = avg_daily_return.dropna()

sharpe              = avg_daily_return/std_returns
sharpe_final        = np.sqrt(252)*sharpe
sharpe_final        =sharpe_final.dropna()

sharpe_rf           = sharpe_final / df['Risk Free Rate']
sharpe_rf           = sharpe_rf.dropna()`
</code>```

Body:
Regardless of the time frame I put on this chart (i.e. 10yrs, 20yrs, 25yrs), the data in the beginning is always distorted -- i.e. very high or very low -- on the chart.

I thought it was a min_periods issue, but that doesn't seem to be it.

Appreciate any insight!

Tried making sure that there were no N/As in the calculation columns.

Tried changing min_periods to be larger.

No change.

What's charted on the bottom subplot is sharpe_rf in the code below.

asset1          = 'XLY Equity'
asset2          = 'USGG10YR Index'

#-------------Dataframe 1: Price Data from Multiple Securities-------------#
sids            = mgr[asset1, asset2]
d               = sids.get_historical(prices,start=startD,end=endD)
df              = pd.DataFrame(d)
df              = df.dropna()

df.columns      = ['Asset', 'Risk Free Rate']

#------------Returns and Standard Deviation---------------#
log_return          = np.log(df['Asset']) - np.log(df['Asset'].shift(1))
ten_day_return      = log_return.rolling(min_periods=10, window=30, center=False).sum()
std_20d             = df['Asset'].rolling(min_periods=10, window=30, center=False).std()
max_std_today       = std_20d.max() - std_20d

#------------Moving Averages------------#
ma_50               = df['Asset'].rolling(min_periods=10, window=50, center=False).mean()
ma_100              = df['Asset'].rolling(min_periods=10, window=100, center=False).mean()
ma_200              = df['Asset'].rolling(min_periods=10, window=200, center=False).mean()

# #------------Rolling Sharpe Ratio------------#
lookback            = 252
daily_returns       = log_return[1:]
std_returns         = daily_returns.rolling(min_periods=10,window=lookback,center=False).std()
std_returns         = std_returns.dropna()

avg_daily_return    = daily_returns.rolling(min_periods=10,window=lookback,center=False).mean()
avg_daily_return    = avg_daily_return.dropna()

sharpe              = avg_daily_return/std_returns
sharpe_final        = np.sqrt(252)*sharpe
sharpe_final        =sharpe_final.dropna()

sharpe_rf           = sharpe_final / df['Risk Free Rate']
sharpe_rf           = sharpe_rf.dropna()`


问:
How to create SCD type 2 with no new output row when condition is met
I need to create SCD type 2 in order to store addresses. I need to track changes in columns City, ZipCode, Type and ValidTo. The column ValidTo says the date to which the address was valid (it takes the value from the database). I'm trying to get my head around how to create SCD type 2 so that it won't create a new row when value in column ValidTo doesn't equal to '2100-01-01'.

Here is what I get:
The address is inactive in the database but in my dimension address table it's still active since there's a row with null value in DateTo column.

I'm racking my brain how not to insert a new row when a condition is met.

AdressID
ad_id
City
ZipCode
Type
ValidTo
DateFrom
DateTo

1
100
Warsaw
02-414
registered
2100-01-01
2022-11-28
2022-12-05

2
100
Warsaw
02-414
registered
2022-12-05
2022-12-05
null


问:
I can't create app for API in facebook developer account
I need facebook login API for my app. But I can't create app on facebook developer console.
Everytime it says "Something went wrong. we are working to getting i fixed soon."

Is there any solution?
Screenshot: It says like this picture

I need help to solve the problem.