答:
Added event.preventDefault so the form does not actually submit and refresh the page removing the client side event. Added a click event to the button and ran conditionals that sets the style attributes to block for the numbers selected.

I assume you want to show each numbers corresponding amount of their divs, so if 3 is selected show balance_0, balance_1, balance_2 correct?

let e = document.querySelector('#dropdown_result');

let send = document.querySelector('#button');
let one = document.querySelector('.balance_0');
let two = document.querySelector('.balance_1');
let three = document.querySelector('.balance_2');
let four = document.querySelector('.balance_3');
let selected;
  send.addEventListener('click', event => {
    selected = Number(e.options[e.selectedIndex].value);
    if(selected === 1){
      one.style.display = "block";
      two.style.display = "none";
      three.style.display = "none";
      four.style.display = "none";
    }else if(selected === 2){
      one.style.display = "block";
      two.style.display = "block";
      three.style.display = "none";
      four.style.display = "none";
    }else if(selected === 3){
      one.style.display = "bloc";
      two.style.display = "block";
      three.style.display = "block";
      four.style.display = "none";
    }else if(selected === 4){
      one.style.display = "block";
      two.style.display = "block";
      three.style.display = "block";
      four.style.display = "block";
    }
    event.preventDefault();
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.balance_0,
    .balance_1,
    .balance_2,
    .balance_3
     {
      display: none;
    }</code>```

<form class="year-selector" method="post">

  <select class="dropdown_result" id="dropdown_result" name="selection">

    <option value="" selected="selected">Select amount of years to report...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>

  </select>

  <button type="submit" id="button" name="button">Send</button>

</form>

Balance-0

Balance-1

Balance-2

Balance-3
```

Title: Show divs based on dropdown-menu-option selected by user

Body:
Added event.preventDefault so the form does not actually submit and refresh the page removing the client side event. Added a click event to the button and ran conditionals that sets the style attributes to block for the numbers selected.

I assume you want to show each numbers corresponding amount of their divs, so if 3 is selected show balance_0, balance_1, balance_2 correct?

let e = document.querySelector('#dropdown_result');

let send = document.querySelector('#button');
let one = document.querySelector('.balance_0');
let two = document.querySelector('.balance_1');
let three = document.querySelector('.balance_2');
let four = document.querySelector('.balance_3');
let selected;
  send.addEventListener('click', event => {
    selected = Number(e.options[e.selectedIndex].value);
    if(selected === 1){
      one.style.display = "block";
      two.style.display = "none";
      three.style.display = "none";
      four.style.display = "none";
    }else if(selected === 2){
      one.style.display = "block";
      two.style.display = "block";
      three.style.display = "none";
      four.style.display = "none";
    }else if(selected === 3){
      one.style.display = "bloc";
      two.style.display = "block";
      three.style.display = "block";
      four.style.display = "none";
    }else if(selected === 4){
      one.style.display = "block";
      two.style.display = "block";
      three.style.display = "block";
      four.style.display = "block";
    }
    event.preventDefault();
  });

.balance_0,
    .balance_1,
    .balance_2,
    .balance_3
     {
      display: none;
    }

<form class="year-selector" method="post">

  <select class="dropdown_result" id="dropdown_result" name="selection">

    <option value="" selected="selected">Select amount of years to report...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>

  </select>

  <button type="submit" id="button" name="button">Send</button>

</form>

<!-- Divs -->

<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>


来源: stackexchange

问:
Is there a way of getting a number to increment by 1 each time when inside a while loop?
I have this function:

function newMessages() {
    global $connection;

    $userId = $_SESSION['userId'];
    $query = "SELECT * FROM messages WHERE toUserId = '$userId' && messageRead = 'No' ORDER BY date DESC, time DESC";
    $selectImageQuery = mysqli_query($connection, $query);
    confirmQuery($selectImageQuery);

    while ($row = mysqli_fetch_assoc($selectImageQuery)) {
        $messageId = escape($row['messageId']);
        $message =  escape($row['message']);
        $fromUsername = escape($row['fromUsername']);
        $username = escape($_SESSION['username']);
        $date = escape($row['date']);
        $time = escape($row['time']);

        $query = "SELECT messageCount FROM users WHERE userId = '$userId' ";
        $selectCountQuery = mysqli_query($connection, $query);
        confirmQuery($selectCountQuery);

        while ($row = mysqli_fetch_assoc($selectCountQuery)) {
            $messageCount = escape($row['messageCount']);

            for ($i = 1; $i<=$messageCount; $i++) {
                $messageCount = $i;
                echo $messageCount;

                echo "
          <button type='button' class='btn btn-success' data-toggle='collapse' data-target='#demo$messageCount'>$date / $time - 1 new message from $fromUsername</button>

            $message

";
            }
        }
    }
}
```

The first while loop checks for messages and echo's them out which it does. I then need to find a way where a user can click on each one and only see the info for that one. Currently when a user clicks on one they all open because the data-target (of course) is the same for each. So i am thinking if there is a way of having $messageCount change on each loop

Please help!!! I am going mad

If i change for($i = 1; $i<=$messageCount; $i++) for for($i = 1; $i<=10; $i++) then i get 10 of the 1st message, then 10 of the 2nd message and so on. However only all the 1's open so it's a start i guess.

It would be nice if the number (down the left) went from 1 - 4

答:
Here is my answer following all your recommendations

```<code>function newMessages() {

    global $connection;

    /* create a prepared statement */
    if ($stmt = $connection->prepare("SELECT messageId, fromUsername, message, date, time FROM messages WHERE toUserId = ? AND messageRead = ? ORDER BY date DESC, time DESC")) {

         /* set variables */
         $userId = $_SESSION['userId'];
         $messageRead = 'No';

         /* bind parameters for markers */
         $stmt->bind_param("is", $userId, $messageRead);

         /* execute query */
         $stmt->execute();

         /* bind result variables */
         $stmt->bind_result($messageId, $fromUsername, $message, $date, $time);

         /* fetch value */
         while ($row = $stmt->fetch()) {
        echo $messageId;
         echo "
          <button type='button' class='btn btn-success' data-toggle='collapse' data-target='#demo$messageId'>$date / $time - 1 new message from $fromUsername</button>
          <div id='demo$messageId' class='collapse'>
            $message
          </div><br><br>";

         }

         /* close statement */
         $stmt->close();
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this function:

function newMessages() {
    global $connection;

    $userId = $_SESSION['userId'];
    $query = "SELECT * FROM messages WHERE toUserId = '$userId' && messageRead = 'No' ORDER BY date DESC, time DESC";
    $selectImageQuery = mysqli_query($connection, $query);
    confirmQuery($selectImageQuery);

    while ($row = mysqli_fetch_assoc($selectImageQuery)) {
        $messageId = escape($row['messageId']);
        $message =  escape($row['message']);
        $fromUsername = escape($row['fromUsername']);
        $username = escape($_SESSION['username']);
        $date = escape($row['date']);
        $time = escape($row['time']);

        $query = "SELECT messageCount FROM users WHERE userId = '$userId' ";
        $selectCountQuery = mysqli_query($connection, $query);
        confirmQuery($selectCountQuery);

        while ($row = mysqli_fetch_assoc($selectCountQuery)) {
            $messageCount = escape($row['messageCount']);

            for ($i = 1; $i<=$messageCount; $i++) {
                $messageCount = $i;
                echo $messageCount;

                echo "
          <button type='button' class='btn btn-success' data-toggle='collapse' data-target='#demo$messageCount'>$date / $time - 1 new message from $fromUsername</button>

            $message

";
            }
        }
    }
}

The first while loop checks for messages and echo's them out which it does. I then need to find a way where a user can click on each one and only see the info for that one. Currently when a user clicks on one they all open because the data-target (of course) is the same for each. So i am thinking if there is a way of having $messageCount change on each loop

Please help!!! I am going mad

If i change for($i = 1; $i<=$messageCount; $i++) for for($i = 1; $i<=10; $i++) then i get 10 of the 1st message, then 10 of the 2nd message and so on. However only all the 1's open so it's a start i guess.

It would be nice if the number (down the left) went from 1 - 4

Body:
Here is my answer following all your recommendations

function newMessages() {

    global $connection;

    /* create a prepared statement */
    if ($stmt = $connection->prepare("SELECT messageId, fromUsername, message, date, time FROM messages WHERE toUserId = ? AND messageRead = ? ORDER BY date DESC, time DESC")) {

         /* set variables */
         $userId = $_SESSION['userId'];
         $messageRead = 'No';

         /* bind parameters for markers */
         $stmt->bind_param("is", $userId, $messageRead);

         /* execute query */
         $stmt->execute();

         /* bind result variables */
         $stmt->bind_result($messageId, $fromUsername, $message, $date, $time);

         /* fetch value */
         while ($row = $stmt->fetch()) {
        echo $messageId;
         echo "
          <button type='button' class='btn btn-success' data-toggle='collapse' data-target='#demo$messageId'>$date / $time - 1 new message from $fromUsername</button>
          <div id='demo$messageId' class='collapse'>
            $message
          </div><br><br>";

         }

         /* close statement */
         $stmt->close();
    }

}


问:
Copy entire directory contents to another directory?
Method to copy entire directory contents to another directory in java or groovy?</p>

答:
Use Apache's
FileUtils.copyDirectory

Write
your own e.g. this guy provides
example code.

Java 7: take a look at java.nio.file.Files.

ContentLicense: CC BY-SA 3.0


问:
linux g++ regular expressions not working
I'm trying to find sub string using regular expressions on linux g++.

For example :

```<code>    std::string logline = "Apr 19 00:55:32 localhost kernel: usb 2-2.1: SerialNumber: ABCDEFGHIJKLMNOP\n";

    std::string sn = "";
    std::regex re("SerialNumber\: (.*)\n");
    std::smatch match;
    if (std::regex_search(logline, match, re) && match.size() > 1) {
        sn = match.str(1);
    }
    else
    {
        sn = std::string("");
    }
</code>```

it works in windows c++ as well.
but linux g++ not work.
what's is the problem?

答:
you do not need '\' before ':'. so the correct line is:
std::regex re("SerialNumber: (.*)\n");
with this change your code works with gcc starting gcc 4.9.1. https://wandbox.org/permlink/uuVCxdtpHAjZTghP

Body:
I'm trying to find sub string using regular expressions on linux g++.

For example :

    std::string logline = "Apr 19 00:55:32 localhost kernel: usb 2-2.1: SerialNumber: ABCDEFGHIJKLMNOP\n";

    std::string sn = "";
    std::regex re("SerialNumber\: (.*)\n");
    std::smatch match;
    if (std::regex_search(logline, match, re) && match.size() > 1) {
        sn = match.str(1);
    }
    else
    {
        sn = std::string("");
    }

it works in windows c++ as well.
but linux g++ not work.
what's is the problem?


问:
How to read a .pgn.bz2 file with fread in R?
I am trying to read chess game files from https://database.lichess.org/ where the files are stored as a bzip of a pgn.
A sample format of a pgn file would look something like this:

```<code>[Event "4th Bayern-chI Bank Hofmann"]
[Site "?"]
[Date "2000.10.29"]
[Round "?"]
[White "Carlsen, Magnus"]
[Black "Cordts, Ingo"]
[ECO "A56"]
[WhiteElo "0"]
[BlackElo "2222"]
[Result "0-1"]

1. d4 Nf6 2. c4 c5 3. Nf3 cxd4 4. Nxd4 e5 5. Nb5 d5 6. cxd5 Bc5 7. N5c3 O-O 8. e3 e4 9. h3 Re8 10. g4 Re5 11. Bc4 Nbd7 12. Qb3 Ne8 13. Nd2 Nd6 14. Be2 Qh4 15. Nc4 Nxc4 16. Qxc4 b5 17. Qxb5 Rb8 18. Qa4 Nf6 19. Qc6 Nd7 20. d6 Re6 21. Nxe4 Bb7 22. Qxd7 Bxe4 23. Rh2 Bxd6 24. Bc4 Rd8 25. Qxa7 Bxh2 26. Bxe6 fxe6 27. Qa6 Bf3 28. Bd2 Qxh3 29. Qxe6+ Kh8 30. Qe7 Bc7
</code>```

I can read the files with read.csv directly from the bz2 file:

```<code>read.csv(file.pgn.bg2, nrows = 100000, stringsAsFactors = F, header = F)
</code>```

But the problem is that read.csv is quite slow and the files have millions of lines. So I thought I would use fread since now it can read .bz2 files.
The problem is that when I try the following

```<code>fread(file.pgn.bg2, nrows = 1000)
</code>```

The command just runs for ages without any results.
My sessioninfo():

```<code>R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)
</code>```

I tried with a normal .pgn file and fread reads albeit incorrectly. As in it splits the columns and discards the game notation, so for the example above it would result in something like this:

```<code>V1               V2
[Event     "4th Bayern-chI Bank Hofmann"]
[Site      "?"]
[Date      "2000.10.29"]
[Round     "?"]
[White     "Carlsen, Magnus"]
[Black     "Cordts, Ingo"]
[ECO       "A56"]
[WhiteElo  "0"]
[BlackElo  "2222"]
[Result    "0-1"]
</code>```

But at least it's reading it.
Would anyone have any advice as to how to go about it? How to use fread to correctly read from the .pgn.bz2 file?

答:
This is reading the file correctly....

how to process afterwards is a different problem ;-)

```<code>DT <- fread( "./temp/lichess_db_standard_rated_2013-01.pgn.bz2", sep = "", header = FALSE )
</code>```

Body:
I am trying to read chess game files from https://database.lichess.org/ where the files are stored as a bzip of a pgn.
A sample format of a pgn file would look something like this:

[Event "4th Bayern-chI Bank Hofmann"]
[Site "?"]
[Date "2000.10.29"]
[Round "?"]
[White "Carlsen, Magnus"]
[Black "Cordts, Ingo"]
[ECO "A56"]
[WhiteElo "0"]
[BlackElo "2222"]
[Result "0-1"]

1. d4 Nf6 2. c4 c5 3. Nf3 cxd4 4. Nxd4 e5 5. Nb5 d5 6. cxd5 Bc5 7. N5c3 O-O 8. e3 e4 9. h3 Re8 10. g4 Re5 11. Bc4 Nbd7 12. Qb3 Ne8 13. Nd2 Nd6 14. Be2 Qh4 15. Nc4 Nxc4 16. Qxc4 b5 17. Qxb5 Rb8 18. Qa4 Nf6 19. Qc6 Nd7 20. d6 Re6 21. Nxe4 Bb7 22. Qxd7 Bxe4 23. Rh2 Bxd6 24. Bc4 Rd8 25. Qxa7 Bxh2 26. Bxe6 fxe6 27. Qa6 Bf3 28. Bd2 Qxh3 29. Qxe6+ Kh8 30. Qe7 Bc7

I can read the files with read.csv directly from the bz2 file:

read.csv(file.pgn.bg2, nrows = 100000, stringsAsFactors = F, header = F)

But the problem is that read.csv is quite slow and the files have millions of lines. So I thought I would use fread since now it can read .bz2 files.
The problem is that when I try the following

fread(file.pgn.bg2, nrows = 1000)

The command just runs for ages without any results.
My sessioninfo():

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

I tried with a normal .pgn file and fread reads albeit incorrectly. As in it splits the columns and discards the game notation, so for the example above it would result in something like this:

V1               V2
[Event     "4th Bayern-chI Bank Hofmann"]
[Site      "?"]
[Date      "2000.10.29"]
[Round     "?"]
[White     "Carlsen, Magnus"]
[Black     "Cordts, Ingo"]
[ECO       "A56"]
[WhiteElo  "0"]
[BlackElo  "2222"]
[Result    "0-1"]

But at least it's reading it.
Would anyone have any advice as to how to go about it? How to use fread to correctly read from the .pgn.bz2 file?

Body:
This is reading the file correctly....

how to process afterwards is a different problem ;-)

DT <- fread( "./temp/lichess_db_standard_rated_2013-01.pgn.bz2", sep = "", header = FALSE )


问:
How to call method in ViewController from viewmodel in swift 5?
I am using MVVM design pattern in iOS project. I am trying to call method in viewcontroller from viewmodel.

```<code>import Foundation

class NotificationViewModel {

    var onCompletion: ((_ success: Bool) -> ())?

    func saveNotification(notification: Dictionary<String, Any>) {
        print("notification save")
        //other logic
        onCompletion?(true)
    }
   }
</code>```

"saveNotification" method getting called from appdelegate when notification received

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSMutableDictionary
            else {
                // handle any error here
                return
            }

        NotificationViewModel().saveNotification(notification: alert as! Dictionary<String, Any>)
        }
</code>```

trying to call method in viewcontroller when "saveNotification" trigger

```<code>     class AlertViewController: BaseViewController{

            var viewModel = NotificationViewModel()

            override func viewDidLoad() {
                super.viewDidLoad()

                self.viewModel.onCompletion = { success in
                    // this should be executed when `saveNotification()` will be called
// **** this is never getting called ******
                    print("calling from viewmodel")
                    methodToCall()
                }
            }

          func methodToCall(){
            //logic
          }
      }
</code>```

But the method in viewdidload is not getting called anytime.

Please suggest if its possible or any other way to achieve this?
Thanks for help

答: It's because you are calling the saveNotification method on a new instance of NotificationViewModel whose onCompletion is not set, and hence would not call the methodToCall method in the AlertViewController.

Body:
I am using MVVM design pattern in iOS project. I am trying to call method in viewcontroller from viewmodel.

import Foundation

class NotificationViewModel {

    var onCompletion: ((_ success: Bool) -> ())?

    func saveNotification(notification: Dictionary<String, Any>) {
        print("notification save")
        //other logic
        onCompletion?(true)
    }
   }

"saveNotification" method getting called from appdelegate when notification received

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSMutableDictionary
            else {
                // handle any error here
                return
            }

        NotificationViewModel().saveNotification(notification: alert as! Dictionary<String, Any>)
        }

trying to call method in viewcontroller when "saveNotification" trigger

     class AlertViewController: BaseViewController{

            var viewModel = NotificationViewModel()

            override func viewDidLoad() {
                super.viewDidLoad()

                self.viewModel.onCompletion = { success in
                    // this should be executed when `saveNotification()` will be called
// **** this is never getting called ******
                    print("calling from viewmodel")
                    methodToCall()
                }
            }

          func methodToCall(){
            //logic
          }
      }

But the method in viewdidload is not getting called anytime.

Please suggest if its possible or any other way to achieve this?
Thanks for help


问:
Negative r squared for linear regression but positive r squared with Random forest regressor
My R squared score for Linear regression is -1.56 but my R squared score for Random Forest regressor is around 0.48. Is it okay to get scores like this?</p>

答:
Is it okay to get scores like this?

Yes.

Explanation - Linear Regression and Random Forest are two very different models. It is highly possible that the data on which you are trying to fit the model is so complicated that linear regression does not fit it well.

Regarding the negative R squared score -  It simply means that the linear regression model fits worse than a horizontal line.


问:
Google Sheets Split remove characters and unwanted words
I have this data as a sample in a column:

```<code>3 PACK BAG 1500 ML CONTAIN 600 ML AMINO ACID, 600 ML GLUCOSE, 300 ML LIPID EMULSION
</code>```

I am using this formula to remove unwanted characters: =SPLIT(A2:A,"1234567890-=[]\;',./!@#$%^&*()")

So it returns me:

```<code> PACK BAG    ML C   NTAIN    ML AMIN     ACID        ML GLUC    SE       ML LIPID EMULSI    N
</code>```

Now i would like to add in my formula =SPLIT(A2:A,"1234567890-=[]\;',./!@#$%^&*()") a function to remove "MC" and "C" OR "SE".

How i can update my formula split to remove the specific chain of characters (words) ?

答:
```<code>=SPLIT(REGEXREPLACE(A2:A, "(MC|C|SE)", " "),"1234567890-=[]\;',./!@#$%^&*()")
</code>```

You could pre-process your string with REGEXREPLACE to substitute a specific character (eg. whitespace) for these specific words before applying the SPLIT function.

Body:
I have this data as a sample in a column:

3 PACK BAG 1500 ML CONTAIN 600 ML AMINO ACID, 600 ML GLUCOSE, 300 ML LIPID EMULSION

I am using this formula to remove unwanted characters: =SPLIT(A2:A,"1234567890-=[]\;',./!@#$%^&*()")

So it returns me:

 PACK BAG    ML C   NTAIN    ML AMIN     ACID        ML GLUC    SE       ML LIPID EMULSI    N

Now i would like to add in my formula =SPLIT(A2:A,"1234567890-=[]\;',./!@#$%^&*()") a function to remove "MC" and "C" OR "SE".

How i can update my formula split to remove the specific chain of characters (words) ?

Body:
=SPLIT(REGEXREPLACE(A2:A, "(MC|C|SE)", " "),"1234567890-=[]\;',./!@#$%^&*()")

You could pre-process your string with REGEXREPLACE to substitute a specific character (eg. whitespace) for these specific words before applying the SPLIT function.


问:
how to create RecyclerView drag and drop (swap 2 item positions version)
I have ItemTouchHelper class that uses swiping and drag and drop for performing actions. But i want to change drag and drop behavior. It should swap positions of 2 elements, the first one I dragged and the other one where it is dropped on. i want to exchange the items of the dragged & dropped positions. not to change positions of all items among both of them.

How to do it

this is my class for drag and drop

```<code>public class ItemTouchHelper extends
androidx.recyclerview.widget.ItemTouchHelper.Callback {

private Drawable icon;
private Context context;
private ColorDrawable background;
private final ItemTouchHelperListener dragDropListener;

public ItemTouchHelper(Context context, Drawable icon,
                       ItemTouchHelperListener dragDropListener) {
    this.icon = icon;
    this.dragDropListener = dragDropListener;
    this.context = context;
    this.background = new ColorDrawable(context.getResources().getColor(R.color.deleteItem));
}

@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
                        @NonNull RecyclerView.ViewHolder viewHolder,
                        float dX, float dY,
                        int actionState, boolean isCurrentlyActive) {
    super.onChildDraw(c, recyclerView, viewHolder, dX,
            dY, actionState, isCurrentlyActive);
    View itemView = viewHolder.itemView;

    int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
    int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
    int iconBottom = iconTop + icon.getIntrinsicHeight();

    if (dX > 0) {
        background = new ColorDrawable(context.getResources().getColor(R.color.deleteItem));

        iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        iconBottom = iconTop + icon.getIntrinsicHeight();

        int iconRight = itemView.getLeft() + iconMargin + icon.getIntrinsicWidth();
        int iconLeft = itemView.getLeft() + iconMargin;

        icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);

        background.setBounds(itemView.getLeft(), itemView.getTop(),
                itemView.getLeft() + ((int) dX),
                itemView.getBottom());
    } else if (dX < 0) {
        int iconRight = itemView.getRight() - iconMargin;
        int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
        icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);
        background.setBounds(itemView.getRight(), itemView.getTop(),
                itemView.getRight() + ((int) dX),
                itemView.getBottom());
    } else {
        background.setBounds(0, 0, 0, 0);
        icon.setBounds(0, 0, 0, 0);
    }

    background.draw(c);
    icon.draw(c);
}

@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder,
                     int direction) {
    dragDropListener.deleteElementDialog(viewHolder.getAdapterPosition());
}

@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
    int dragFlags = UP | DOWN;
    int swipeFlags = START | END;
    return makeMovementFlags(dragFlags, swipeFlags);
}

@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder,
                      @NonNull RecyclerView.ViewHolder target) {
    dragDropListener.onRowMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
    return true;
}

@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder,
                              int actionState) {
    if (actionState != ACTION_STATE_IDLE && actionState != ACTION_STATE_SWIPE) {
        dragDropListener.onRowSelected(viewHolder);
    }
    super.onSelectedChanged(viewHolder, actionState);
}

@Override
public void clearView(@NonNull RecyclerView recyclerView,
                      @NonNull RecyclerView.ViewHolder viewHolder) {
    super.clearView(recyclerView, Objects.requireNonNull(viewHolder));
    dragDropListener.onRowClear(Objects.requireNonNull(viewHolder));
}

@Override
public boolean isLongPressDragEnabled() {
    return true;
}

}
</code>```

and this is my ItemTouchHelperListener:

```<code>    public void setItemTouchHelperListener() {
    ItemTouchHelperListener itemTouchHelperListener = new
   ItemTouchHelperListener() {
        @Override
        public void onRowMoved(int fromPosition, int toPosition) {
            presenter.rowMoved(fromPosition, toPosition);
        }

        @Override
        public void onRowSelected(RecyclerView.ViewHolder myViewHolder) {
            if (myViewHolder instanceof ElementsAdapter.ElementsViewHolder) {
                elementsAdapter.rowSelected((ElementsAdapter.ElementsViewHolder) myViewHolder);
                presenter.rowSelected(myViewHolder.getAdapterPosition());
            }
        }

        @Override
        public void onRowClear(RecyclerView.ViewHolder myViewHolder) {
            if (myViewHolder instanceof ElementsAdapter.ElementsViewHolder) {
                elementsAdapter.rowClear((ElementsAdapter.ElementsViewHolder) myViewHolder);
                presenter.rowClear(myViewHolder.getAdapterPosition());
            }
        }

        @Override
        public void deleteElementDialog(int adapterPosition) {
            createDeleteDialog(adapterPosition);
        }
    };
</code>```

答:
I totally agree with @Zain answer but there is one problem i.e suppose you want to replace the 1st item with 3rd then you will click and hold the 3rd item and drag it over the 1st item. Once you dropped, you will notice the 3rd item will get again shifted to its original position and after that, both items will get updated properly. It doesn't look good.

I've just slightly modified the @Zain answer.

```<code>private int fromPos = -1;
private int toPos = -1;

ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new
ItemTouchHelper.SimpleCallback(
    ItemTouchHelper.UP | ItemTouchHelper.DOWN |
    ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT, 0) {

@Override
public boolean onMove(@NonNull RecyclerView recyclerView,
                      @NonNull RecyclerView.ViewHolder viewHolder,
                      @NonNull RecyclerView.ViewHolder target) {
    toPos = target.getAdapterPosition();
    return false;
}

@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder,
                     int direction) {}

@Override
public void onSelectedChange(@NonNull RecyclerView.ViewHolder
                           viewHolder, int actionState) {
    switch(actionState){
          case ItemTouchHelper.ACTION_STATE_DRAG:{
             fromPos = viewHolder.getAdapterPosition();
             break;
          }

          case ItemTouchHelper.ACTION_STATE_IDLE: {
              //Execute when the user dropped the item after dragging.
              if(fromPos != -1 && toPos != -1
                 && fromPos != toPos) {
               moveItem(fromPos, toPos);
               fromPos = -1;
               toPos = -1;
           }
           break;
        }
}

private void moveItem(int oldPos, int newPos) {
   Item temp = mItems.get(oldPos);
   mItems.set(oldPos, mItems.get(newPos));
   mItems.set(newPos, temp);
   mAdapter.notifyItemChanged(oldPos);
   mAdapter.notifyItemChanged(newPos);
}
</code>```

Body:
I have ItemTouchHelper class that uses swiping and drag and drop for performing actions. But i want to change drag and drop behavior. It should swap positions of 2 elements, the first one I dragged and the other one where it is dropped on. i want to exchange the items of the dragged & dropped positions. not to change positions of all items among both of them.

How to do it

this is my class for drag and drop

public class ItemTouchHelper extends
androidx.recyclerview.widget.ItemTouchHelper.Callback {

private Drawable icon;
private Context context;
private ColorDrawable background;
private final ItemTouchHelperListener dragDropListener;

public ItemTouchHelper(Context context, Drawable icon,
                       ItemTouchHelperListener dragDropListener) {
    this.icon = icon;
    this.dragDropListener = dragDropListener;
    this.context = context;
    this.background = new ColorDrawable(context.getResources().getColor(R.color.deleteItem));
}

@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
                        @NonNull RecyclerView.ViewHolder viewHolder,
                        float dX, float dY,
                        int actionState, boolean isCurrentlyActive) {
    super.onChildDraw(c, recyclerView, viewHolder, dX,
            dY, actionState, isCurrentlyActive);
    View itemView = viewHolder.itemView;

    int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
    int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
    int iconBottom = iconTop + icon.getIntrinsicHeight();

    if (dX > 0) {
        background = new ColorDrawable(context.getResources().getColor(R.color.deleteItem));

        iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        iconBottom = iconTop + icon.getIntrinsicHeight();

        int iconRight = itemView.getLeft() + iconMargin + icon.getIntrinsicWidth();
        int iconLeft = itemView.getLeft() + iconMargin;

        icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);

        background.setBounds(itemView.getLeft(), itemView.getTop(),
                itemView.getLeft() + ((int) dX),
                itemView.getBottom());
    } else if (dX < 0) {
        int iconRight = itemView.getRight() - iconMargin;
        int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
        icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);
        background.setBounds(itemView.getRight(), itemView.getTop(),
                itemView.getRight() + ((int) dX),
                itemView.getBottom());
    } else {
        background.setBounds(0, 0, 0, 0);
        icon.setBounds(0, 0, 0, 0);
    }

    background.draw(c);
    icon.draw(c);
}

@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder,
                     int direction) {
    dragDropListener.deleteElementDialog(viewHolder.getAdapterPosition());
}

@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
    int dragFlags = UP | DOWN;
    int swipeFlags = START | END;
    return makeMovementFlags(dragFlags, swipeFlags);
}

@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder,
                      @NonNull RecyclerView.ViewHolder target) {
    dragDropListener.onRowMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
    return true;
}

@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder,
                              int actionState) {
    if (actionState != ACTION_STATE_IDLE && actionState != ACTION_STATE_SWIPE) {
        dragDropListener.onRowSelected(viewHolder);
    }
    super.onSelectedChanged(viewHolder, actionState);
}

@Override
public void clearView(@NonNull RecyclerView recyclerView,
                      @NonNull RecyclerView.ViewHolder viewHolder) {
    super.clearView(recyclerView, Objects.requireNonNull(viewHolder));
    dragDropListener.onRowClear(Objects.requireNonNull(viewHolder));
}

@Override
public boolean isLongPressDragEnabled() {
    return true;
}

}

and this is my ItemTouchHelperListener:

    public void setItemTouchHelperListener() {
    ItemTouchHelperListener itemTouchHelperListener = new
   ItemTouchHelperListener() {
        @Override
        public void onRowMoved(int fromPosition, int toPosition) {
            presenter.rowMoved(fromPosition, toPosition);
        }

        @Override
        public void onRowSelected(RecyclerView.ViewHolder myViewHolder) {
            if (myViewHolder instanceof ElementsAdapter.ElementsViewHolder) {
                elementsAdapter.rowSelected((ElementsAdapter.ElementsViewHolder) myViewHolder);
                presenter.rowSelected(myViewHolder.getAdapterPosition());
            }
        }

        @Override
        public void onRowClear(RecyclerView.ViewHolder myViewHolder) {
            if (myViewHolder instanceof ElementsAdapter.ElementsViewHolder) {
                elementsAdapter.rowClear((ElementsAdapter.ElementsViewHolder) myViewHolder);
                presenter.rowClear(myViewHolder.getAdapterPosition());
            }
        }

        @Override
        public void deleteElementDialog(int adapterPosition) {
            createDeleteDialog(adapterPosition);
        }
    };

Body:
I totally agree with @Zain answer but there is one problem i.e suppose you want to replace the 1st item with 3rd then you will click and hold the 3rd item and drag it over the 1st item. Once you dropped, you will notice the 3rd item will get again shifted to its original position and after that, both items will get updated properly. It doesn't look good.

I've just slightly modified the @Zain answer.

private int fromPos = -1;
private int toPos = -1;

ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new
ItemTouchHelper.SimpleCallback(
    ItemTouchHelper.UP | ItemTouchHelper.DOWN |
    ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT, 0) {

@Override
public boolean onMove(@NonNull RecyclerView recyclerView,
                      @NonNull RecyclerView.ViewHolder viewHolder,
                      @NonNull RecyclerView.ViewHolder target) {
    toPos = target.getAdapterPosition();
    return false;
}

@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder,
                     int direction) {}

@Override
public void onSelectedChange(@NonNull RecyclerView.ViewHolder
                           viewHolder, int actionState) {
    switch(actionState){
          case ItemTouchHelper.ACTION_STATE_DRAG:{
             fromPos = viewHolder.getAdapterPosition();
             break;
          }

          case ItemTouchHelper.ACTION_STATE_IDLE: {
              //Execute when the user dropped the item after dragging.
              if(fromPos != -1 && toPos != -1
                 && fromPos != toPos) {
               moveItem(fromPos, toPos);
               fromPos = -1;
               toPos = -1;
           }
           break;
        }
}

private void moveItem(int oldPos, int newPos) {
   Item temp = mItems.get(oldPos);
   mItems.set(oldPos, mItems.get(newPos));
   mItems.set(newPos, temp);
   mAdapter.notifyItemChanged(oldPos);
   mAdapter.notifyItemChanged(newPos);
}


问:
scala json4s, can't convert LocalDate
I'm having an issue with org.json4s (scala), joda.time.LocalDate and org.json4s.ext.JodaTimeSerializers.  Given that JodaTimeSerializers.all has a LocalDate conversion in it, i was hoping that i could do the following, but I get the exception shown after

```<code>scala> import org.json4s.JString
import org.json4s.JString

scala> import org.joda.time.LocalDate
import org.joda.time.LocalDate

scala> import org.json4s.ext.JodaTimeSerializers
import org.json4s.ext.JodaTimeSerializers

scala> import org.json4s._
import org.json4s._

scala> implicit val formats: Formats = DefaultFormats ++ JodaTimeSerializers.all
formats: org.json4s.Formats = org.json4s.Formats$$anon$3@693d3d7f

scala> val jDate = JString("2016-01-26")
jDate: org.json4s.JsonAST.JString = JString(2016-01-26)

scala> jDate.extract[LocalDate]
org.json4s.package$MappingException: Can't convert JString(2016-01-26) to class org.joda.time.LocalDate
</code>```

Other the other hand, this works (not surprisingly)

```<code>scala> val jodaDate = LocalDate.parse(jDate.values)
</code>```

I've tried to create a custom Serializer, which never gets called b/c it falls into the JodaSerializer realm it seems.  I have also created a custom Deserializer that will work with Java.time.LocalDate (int and bytes from strings), but java.time.LocalDate messes with some other code which is likely a different question...this one is:  I'm looking for clues by JodaTimeSerializers.all can not parse JString(2016-01-26), or any date string.

The top of the exception is: org.json4s.package$MappingException:

```<code>Can't convert JString(2016-01-01) to class org.joda.time.LocalDate (JodaTimeSerializers.scala:126)
</code>```

Edit
This is still biting me, so dug a bit further and its reproducible with the following.

```<code>import org.joda.time.LocalDate
import org.json4s.ext.JodaTimeSerializers
import org.json4s._
implicit val formats: Formats = DefaultFormats ++ JodaTimeSerializers.all
import org.joda.time.LocalDate
case class MyDate(myDate: LocalDate)
val stringyDate =
"""
{
  "myDate" : "2016-01-01"
}
"""
import org.json4s.jackson.JsonMethods.parse
parse(stringyDate).extract[MyDate]

org.json4s.package$MappingException: No usable value for myDate
Can't convert JString(2016-01-01) to class org.joda.time.LocalDate
</code>```

This seems to happen b/c on line 125 of JodaTimeSerializers.scala, its not a JObject, it is a JString, so it falls into the value case on line 126, which throws the error.

Adding this here in case it bites someone else and hopefully get some assistance fixing it...but now i'm late.  I have moved the code locally hopefully to come up with a fix tomorrow.

答:
The new serializers are included in the library, but not in the default formats:</p>

```<code>implicit val formats: Formats = DefaultFormats ++ JavaTimeSerializers.all
</code>```

Title: scala json4s, can't convert LocalDate

Body:
I'm having an issue with org.json4s (scala), joda.time.LocalDate and org.json4s.ext.JodaTimeSerializers.  Given that JodaTimeSerializers.all has a LocalDate conversion in it, i was hoping that i could do the following, but I get the exception shown after

scala> import org.json4s.JString
import org.json4s.JString

scala> import org.joda.time.LocalDate
import org.joda.time.LocalDate

scala> import org.json4s.ext.JodaTimeSerializers
import org.json4s.ext.JodaTimeSerializers

scala> import org.json4s._
import org.json4s._

scala> implicit val formats: Formats = DefaultFormats ++ JodaTimeSerializers.all
formats: org.json4s.Formats = org.json4s.Formats$$anon$3@693d3d7f

scala> val jDate = JString("2016-01-26")
jDate: org.json4s.JsonAST.JString = JString(2016-01-26)

scala> jDate.extract[LocalDate]
org.json4s.package$MappingException: Can't convert JString(2016-01-26) to class org.joda.time.LocalDate

Other the other hand, this works (not surprisingly)

scala> val jodaDate = LocalDate.parse(jDate.values)

I've tried to create a custom Serializer, which never gets called b/c it falls into the JodaSerializer realm it seems.  I have also created a custom Deserializer that will work with Java.time.LocalDate (int and bytes from strings), but java.time.LocalDate messes with some other code which is likely a different question...this one is:  I'm looking for clues by JodaTimeSerializers.all can not parse JString(2016-01-26), or any date string.

The top of the exception is: org.json4s.package$MappingException:

Can't convert JString(2016-01-01) to class org.joda.time.LocalDate (JodaTimeSerializers.scala:126)

Edit
This is still biting me, so dug a bit further and its reproducible with the following.

import org.joda.time.LocalDate
import org.json4s.ext.JodaTimeSerializers
import org.json4s._
implicit val formats: Formats = DefaultFormats ++ JodaTimeSerializers.all
import org.joda.time.LocalDate
case class MyDate(myDate: LocalDate)
val stringyDate =
"""
{
  "myDate" : "2016-01-01"
}
"""
import org.json4s.jackson.JsonMethods.parse
parse(stringyDate).extract[MyDate]

org.json4s.package$MappingException: No usable value for myDate
Can't convert JString(2016-01-01) to class org.joda.time.LocalDate

This seems to happen b/c on line 125 of JodaTimeSerializers.scala, its not a JObject, it is a JString, so it falls into the value case on line 126, which throws the error.

Adding this here in case it bites someone else and hopefully get some assistance fixing it...but now i'm late.  I have moved the code locally hopefully to come up with a fix tomorrow.

Body:
The new serializers are included in the library, but not in the default formats:

implicit val formats: Formats = DefaultFormats ++ JavaTimeSerializers.all


问:
Is there a query tool for Cassandra (or other noSQL DBs) similar to QTADO or navicat?
There are many query tools for SQL databases, e.g. QTADO, navicat, etc. Are there similar tools for Cassandra and other noSQL databases? I need it mostly for testing during development of Cassandra apps.</p>

答: I use Visual Studio Code and https://marketplace.visualstudio.com/items?itemName=mtxr.sqltools extension. It supports various db-s, including cassandra.</p>


问:
C++ Cypher issue
I am new to the world of coding and been experimenting on making a cypher with c++ but it is throwing an error and I don't know how to fix it. Help would be appreciated, Here is the code

```<code>#include <iostream>
#include <string>

using namespace std;

int main(){

/* Variables Declaration! */

string alphabets{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};

string key{"XWZYLMNOPQRSTUVABCDEFGHIJKuvwxyzabcdefghijklmnopqrst"};

string input{};

string encrypted_message{};

string decrypted_message{};

/*----------------------------------------------------------------------------------------------*/

cout << "Welcome To the Cypher!" << endl;
cout << "-------------------------------------------------------------" << endl;

cout << "Enter the code: " << endl;
getline(cin,input);

/*Encryption Part Code*/

cout << "Encrypting!"<< endl;
cout << endl ;

for (char c:input) {

    size_t postition = alphabets.find(c);
    if (postition != string::npos){
        encrypted_message += key.at(postition);
    }
    else
        encrypted_message += c;
}
cout << endl ;
cout << encrypted_message << endl;

/* Decryption Part Code */

cout << "Decrypting!" << endl;
cout << endl ;

for (char c : encrypted_message) {

    size_t position = key.find(c);

    if (position != string::npos){
        decrypted_message += alphabets.at(c);
    }

    else
        decrypted_message += c;

}
/* --------------------------------------------------------------------------------------*/

cout << endl;
cout << "-----------------------------------------------------------------------------" ;
cout << endl ;

return 0;
}
</code>```

The error I'm getting -

terminate called after throwing an instance of 'std::out_of_range'

  what():  basic_string::at: __n (which is 88) >= this->size() (which is
  52)

答:
The error you see is caused by the line

```<code>decrypted_message += alphabets.at(c);
</code>```

You index with a character, and so if the first character in the encrypted_message is X (equal to 88 in ascii), it tries to access element at index 88 which is off bounds. The .at() then throws an exception.

Your intention was to use the position

```<code>if (position != string::npos){
    // decrypted_message += alphabets.at(c);
    decrypted_message += alphabets.at(position);
}
</code>```

Stepping over the code with a debugger makes it easier to find these bugs.

Title: C++ Cypher issue

Body:
I am new to the world of coding and been experimenting on making a cypher with c++ but it is throwing an error and I don't know how to fix it. Help would be appreciated, Here is the code

#include <iostream>
#include <string>

using namespace std;

int main(){

/* Variables Declaration! */

string alphabets{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};

string key{"XWZYLMNOPQRSTUVABCDEFGHIJKuvwxyzabcdefghijklmnopqrst"};

string input{};

string encrypted_message{};

string decrypted_message{};

/*----------------------------------------------------------------------------------------------*/

cout << "Welcome To the Cypher!" << endl;
cout << "-------------------------------------------------------------" << endl;

cout << "Enter the code: " << endl;
getline(cin,input);

/*Encryption Part Code*/

cout << "Encrypting!"<< endl;
cout << endl ;

for (char c:input) {

    size_t postition = alphabets.find(c);
    if (postition != string::npos){
        encrypted_message += key.at(postition);
    }
    else
        encrypted_message += c;
}
cout << endl ;
cout << encrypted_message << endl;

/* Decryption Part Code */

cout << "Decrypting!" << endl;
cout << endl ;

for (char c : encrypted_message) {

    size_t position = key.find(c);

    if (position != string::npos){
        decrypted_message += alphabets.at(c);
    }

    else
        decrypted_message += c;

}
/* --------------------------------------------------------------------------------------*/

cout << endl;
cout << "-----------------------------------------------------------------------------" ;
cout << endl ;

return 0;
}

The error I'm getting -

terminate called after throwing an instance of 'std::out_of_range'

  what():  basic_string::at: __n (which is 88) >= this->size() (which is
  52)

Body:
The error you see is caused by the line

decrypted_message += alphabets.at(c);

You index with a character, and so if the first character in the encrypted_message is X (equal to 88 in ascii), it tries to access element at index 88 which is off bounds. The .at() then throws an exception.

Your intention was to use the position

if (position != string::npos){
    // decrypted_message += alphabets.at(c);
    decrypted_message += alphabets.at(position);
}

Stepping over the code with a debugger makes it easier to find these bugs.


问:
How can i create and run Jar file from spring batch
I have a spring batch application which contains two job, the application in eclipse work correctly but when i create jar and run it, not working i need execute it using CommandLineJobRunner.

I try create a jar using severeal ways:

I using the maven comand mvn clean install and mvn clean package, in this case if I run the jar using ->

java -jar  org.springframework.batch.core.launch.support.CommandLineJobRunner    the jar always execute all jobs.

in other case if i try it using java -cp i get:

Error: Could not find or load main class org.springframework.batch.core.launch.support.CommandLineJobRunner
Caused by: java.lang.ClassNotFoundException: org.springframework.batch.core.launch.support.CommandLineJobRunner

Using ecilpse to export jar file

In eclipse export -> jar -> runneableJar, in this case:

if i use java -cp i get FileNotFoundException application.properties, but this file is in resources.

if i use java -jar i get no main manifest attribute.

In eclipse export -> jar -> Jar file, in this case:

if i use java -cp i get -> Error: Could not find or load main class org.springframework.batch.core.launch.support.CommandLineJobRunner
Caused by: java.lang.ClassNotFoundException: org.springframework.batch.core.launch.support.CommandLineJobRunner

if i use java -jar i get no main manifest attribute.

I don't know what to try.
thancks and sorry for my english, is not my native languaje

答:
You have at least three options:

Add spring batch and all other dependencies in your classpath

Use the maven shade plugin to shade all your dependencies in the same jar

Use Spring Boot and it will do it for you automatically, see example in the getting started guide.


问:
Convert float dtype dataframe to string dtype dataframe (NaN becomes '0')
Here is my code:

```<code>    dfFact = pd.read_sql_query("select * from MusicFact;", conn)
    dfFact['artist'].fillna(0)
    dfFact['artist'].astype('Int64')
    dfFact['artist'] = dfFact['artist'].astype(str)
</code>```

I am trying to convert the following dataframe into a string dataframe

But my desired output needs to be for example in this case '3','3','3','3','2','1','0','0'

I am stuck so I thought I'd come to stack - thank you in advance!

答:
Series.fillna if used without inplace=True returns a new series with missing values filled with the replacement value. Similarly Series.astype returns a copy of casted series. In your case you are not assigning the results of these operations back the the series hence the changes are not propogating in the output.

Simply, use:

```<code>dfFact['artist'] = dfFact['artist'].fillna(0).astype(int).astype(str)
</code>```

Body:
Here is my code:

    dfFact = pd.read_sql_query("select * from MusicFact;", conn)
    dfFact['artist'].fillna(0)
    dfFact['artist'].astype('Int64')
    dfFact['artist'] = dfFact['artist'].astype(str)

I am trying to convert the following dataframe into a string dataframe

But my desired output needs to be for example in this case '3','3','3','3','2','1','0','0'

I am stuck so I thought I'd come to stack - thank you in advance!

Body:
Series.fillna if used without inplace=True returns a new series with missing values filled with the replacement value. Similarly Series.astype returns a copy of casted series. In your case you are not assigning the results of these operations back the the series hence the changes are not propogating in the output.

Simply, use:

dfFact['artist'] = dfFact['artist'].fillna(0).astype(int).astype(str)


问:
Rails Trying to submit a form onchange of dropdown
I have my Ajax working, builtin Rails javascript, with the submit button.  However, I would like it to submit when I change the value of the dropdown box and eliminate the button.  In my research I found what looks like the correct solution but I get no request to the server.  Here is my dropdown form code, note it still has the submit button that worked before I added :onchange:

```<code><% form_tag('switch_car', :method => :put, :remote => true) do %>
  <div class="field">
    <label>Car Name:</label>
    <%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"),
       :onchange => ("$('switch_car').submit()"))%><%= submit_tag "Switch Car" %>
  </div>
<% end %>
</code>```

Here is the HTML generated:

```<code><form accept-charset="UTF-8" action="switch_car" data-remote="true" method="post">
  <div style="margin:0;padding:0;display:inline">
    <input name="utf8" type="hidden" value="✓" />
    <input name="_method" type="hidden" value="put" />
    <input name="authenticity_token" type="hidden" value="PEbdqAoiik37lcoP4+v+dakpYxdpMkSm7Ub8eZpdF9I=" />
  </div>
  <div class="field">
    <label>Car Name:</label>
    <select id="id" name="id" onchange="$('switch_car').submit()">
      <option value="9">Truck</option>
      <option value="10">Car</option>
    </select>
    <input name="commit" type="submit" value="Switch Car" />
</div>
</code>```

Thanks in advance for any help.

答:
This is an old question, but none of the above answers work for me. They all result in a text/html request.

The following works, e.g. (the hide class sets css display: none):

```<code><%= form.radio_button :tier_id, tier.id, onchange: "$('#submit-button-id').click();" %>
</code>```

together with:

```<code><%= form.submit "Save changes", id: 'submit-button-id', class: 'hide' %>
</code>```

Body:
I have my Ajax working, builtin Rails javascript, with the submit button.  However, I would like it to submit when I change the value of the dropdown box and eliminate the button.  In my research I found what looks like the correct solution but I get no request to the server.  Here is my dropdown form code, note it still has the submit button that worked before I added :onchange:

<% form_tag('switch_car', :method => :put, :remote => true) do %>

    Car Name:
    <%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"),
       :onchange => ("$('switch_car').submit()"))%><%= submit_tag "Switch Car" %>

<% end %>

Here is the HTML generated:

<form accept-charset="UTF-8" action="switch_car" data-remote="true" method="post">

    <input name="utf8" type="hidden" value="✓" />
    <input name="_method" type="hidden" value="put" />
    <input name="authenticity_token" type="hidden" value="PEbdqAoiik37lcoP4+v+dakpYxdpMkSm7Ub8eZpdF9I=" />

    Car Name:
    <select id="id" name="id" onchange="$('switch_car').submit()">
      <option value="9">Truck</option>
      <option value="10">Car</option>
    </select>
    <input name="commit" type="submit" value="Switch Car" />

Thanks in advance for any help.

Body:
This is an old question, but none of the above answers work for me. They all result in a text/html request.

The following works, e.g. (the hide class sets css display: none):

<%= form.radio_button :tier_id, tier.id, onchange: "$('#submit-button-id').click();" %>

together with:

<%= form.submit "Save changes", id: 'submit-button-id', class: 'hide' %>


问:
How OR logical assignment works in Javascript
```<code>function maxChecker(str) {
  let final = {};
  for (let char of str) {
    final[char] = final[char] + 1 || 1;
  }

  return final;
}
</code>```

If in this code I don't use the expression || 1 then my values in object is NAN kindly explain this

```<code>final[char]= final[char]+1 || 1;
</code>```

答:
What you get is NaN, because of adding to undefined a value.

console.log(undefined + 1);```
</div>
</div>
</p>

<p>But what is more a problem of this pattern, you move a error to a second step without using a falsy value, like <code>undefined</code> of <code>final[char]</code>.</p>

<p>A better approach is to check if you get a falsy value and if so take zero as number, instead of <code>undefined</code> and add a value like <code>1</code> in the second step.</p>

```final[char] = (final[char] || 0) + 1;
```

Body:
function maxChecker(str) {
  let final = {};
  for (let char of str) {
    final[char] = final[char] + 1 || 1;
  }

  return final;
}

If in this code I don't use the expression || 1 then my values in object is NAN kindly explain this

final[char]= final[char]+1 || 1;

Body:
What you get is NaN, because of adding to undefined a value.

console.log(undefined + 1);

But what is more a problem of this pattern, you move a error to a second step without using a falsy value, like undefined of final[char].

A better approach is to check if you get a falsy value and if so take zero as number, instead of undefined and add a value like 1 in the second step.

final[char] = (final[char] || 0) + 1;


问:
how to merge or join two dataset without column name by pandas, I use right_on and left_on but shows key error
There are two dataset,after I using

the first one:data_df like that:

```<code>          0      1      2      3      4      5
0  sample_0  0.592  0.000  7.215  6.620  0.000
1  sample_1  0.000  0.000  9.950  1.175  0.000
2  sample_2  1.683  3.660  6.097  7.681  0.000
3  sample_3  1.267  0.000  3.914  6.469  0.000
</code>```

the second one:labels_df like that:

```<code>   sampleid Class
0  sample_0  PRAD
1  sample_1  LUAD
2  sample_2  PRAD
3  sample_3  PRAD
4  sample_4  BRCA
5  sample_5  PRAD
</code>```

I want merge two dataset by same sample name and delete sample_4 and sample_5 row in label dataset, so I tried this:

```<code>merge_df = pd.merge(labels_df, data_df, left_on='sampleid', right_on='0', how='inner')
</code>```

but it shows the error:

```<code>Exception has occurred: KeyError
'0'
</code>```

So how to solve it?

答:
Use 0 for select numeric column 0, '0' is used for string column, how='inner' is by default, so should be omited, also for remove duplicates is used DataFrame.drop_duplicates:

```<code>data_df = data_df.drop_duplicates(0)
labels_df = labels_df.drop_duplicates('sampleid')

merge_df = pd.merge(labels_df, data_df, left_on='sampleid', right_on=0)
</code>```

Body:
There are two dataset,after I using

the first one:data_df like that:

          0      1      2      3      4      5
0  sample_0  0.592  0.000  7.215  6.620  0.000
1  sample_1  0.000  0.000  9.950  1.175  0.000
2  sample_2  1.683  3.660  6.097  7.681  0.000
3  sample_3  1.267  0.000  3.914  6.469  0.000

the second one:labels_df like that:

   sampleid Class
0  sample_0  PRAD
1  sample_1  LUAD
2  sample_2  PRAD
3  sample_3  PRAD
4  sample_4  BRCA
5  sample_5  PRAD

I want merge two dataset by same sample name and delete sample_4 and sample_5 row in label dataset, so I tried this:

merge_df = pd.merge(labels_df, data_df, left_on='sampleid', right_on='0', how='inner')

but it shows the error:

Exception has occurred: KeyError
'0'

So how to solve it?

Body:
Use 0 for select numeric column 0, '0' is used for string column, how='inner' is by default, so should be omited, also for remove duplicates is used DataFrame.drop_duplicates:

data_df = data_df.drop_duplicates(0)
labels_df = labels_df.drop_duplicates('sampleid')

merge_df = pd.merge(labels_df, data_df, left_on='sampleid', right_on=0)


问:
Why is UTF-8 output to C console working with Cygwin but not with MinGW?
I want my code to output unicode characters.

This is my code:

```<code>printf("\u2660"); //Spade character
</code>```

When compiling and executing with Cygwin, it works just fine and the spade character (♠) is displayed.

However, it doesn't work with MinGW, as the UTF-8 encoding is displayed as three characters (ÔÖá).

In the executable, the character is stored as UTF-8 in both cases, so the issue doesn't come from compiling.

So, why is the console behaving differently between Cygwin and MinGW?

Is there a fix to display UTF-8 with MinGW too?

答:
How are you running your MinGW application in a console?
There are different ways:

Command Prompt

MinTTY (typically how MSYS2 shell is started)

some other tool like Conzole2 or ConsoleZ

Either way you should go to Properties or Options (for the first 2 by clicking on the icon on the top left of the console window) and change the font to a font that supports Unicode.

Also, in your application use wide character output like this: wprintf(L"\u2660");

Body:
I want my code to output unicode characters.

This is my code:

printf("\u2660"); //Spade character

When compiling and executing with Cygwin, it works just fine and the spade character (♠) is displayed.

However, it doesn't work with MinGW, as the UTF-8 encoding is displayed as three characters (ÔÖá).

In the executable, the character is stored as UTF-8 in both cases, so the issue doesn't come from compiling.

So, why is the console behaving differently between Cygwin and MinGW?

Is there a fix to display UTF-8 with MinGW too?


问:
How to serve Allure Report without automatically starting the browser
When i start the allure, the server always attempts to start the browser:

```<code>$ /home/allure/allure-2.3.4/bin/allure serve target/allure-results -p 5012
    Generating report to temp directory...
    Report successfully generated to /tmp/779851636804605067/allure-report
    Starting web server...
    2017-08-21 17:51:00.271:INFO::main: Logging initialized @3082ms
    Xlib:  extension "RANDR" missing on display ":99".
    Exception in thread "main" java.lang.UnsupportedOperationException: The BROWSE action is not supported on the current platform!
            at java.awt.Desktop.checkActionSupport(Desktop.java:225)
            at java.awt.Desktop.browse(Desktop.java:381)
            at io.qameta.allure.Commands.openBrowser(Commands.java:207)
            at io.qameta.allure.Commands.open(Commands.java:135)
            at io.qameta.allure.Commands.serve(Commands.java:119)
            at io.qameta.allure.CommandLine.run(CommandLine.java:136)
            at java.util.Optional.orElseGet(Optional.java:267)
            at io.qameta.allure.CommandLine.main(CommandLine.java:72)
    2017-08-21 17:51:06.387:WARN:oejsh.ResourceHandler:qtp1928301845-20: org.eclipse.jetty.io.EofException
    2017-08-21 17:51:06.388:WARN:oejsh.ResourceHandler:qtp1928301845-15: org.eclipse.jetty.io.EofException
</code>```

The problem is not in the error, but in the launch, I don't need to start it on this host.
How do I start the allure server without starting the browser?

答:
You can use the docker container Allure Docker Service, recognize the results automatically and update the reports without doing anything:
https://github.com/fescobar/allure-docker-service</p>

Body:
When i start the allure, the server always attempts to start the browser:

$ /home/allure/allure-2.3.4/bin/allure serve target/allure-results -p 5012
    Generating report to temp directory...
    Report successfully generated to /tmp/779851636804605067/allure-report
    Starting web server...
    2017-08-21 17:51:00.271:INFO::main: Logging initialized @3082ms
    Xlib:  extension "RANDR" missing on display ":99".
    Exception in thread "main" java.lang.UnsupportedOperationException: The BROWSE action is not supported on the current platform!
            at java.awt.Desktop.checkActionSupport(Desktop.java:225)
            at java.awt.Desktop.browse(Desktop.java:381)
            at io.qameta.allure.Commands.openBrowser(Commands.java:207)
            at io.qameta.allure.Commands.open(Commands.java:135)
            at io.qameta.allure.Commands.serve(Commands.java:119)
            at io.qameta.allure.CommandLine.run(CommandLine.java:136)
            at java.util.Optional.orElseGet(Optional.java:267)
            at io.qameta.allure.CommandLine.main(CommandLine.java:72)
    2017-08-21 17:51:06.387:WARN:oejsh.ResourceHandler:qtp1928301845-20: org.eclipse.jetty.io.EofException
    2017-08-21 17:51:06.388:WARN:oejsh.ResourceHandler:qtp1928301845-15: org.eclipse.jetty.io.EofException

The problem is not in the error, but in the launch, I don't need to start it on this host.
How do I start the allure server without starting the browser?


问:
using @ symbol with ftp stream in DirectoryIterator
I'm using DirectoryIterator class to list ftp content:
$a = new DirectoryIterator('ftp://user:password@host');

If there is an at "@" character in login, i get an error:
failed to open dir: operation failed

How i can escape @ symbol in login?

I try:
%40,
+
\@

答:
RFC1738 mandates the special characters like @ should be urlencoded in the ftp:// scheme. So using %40 in place of the @ in a password fragement would be correct.

But you just wanted the user:password@ prefix before the hostname. Those don't need escaping. And it's already natively supported by the ftp fopen url wrapper:

```<code>$d = opendir("ftp://anonymous:nopwd@ftp.kernel.org/pub/");
print readdir($d);
</code>```

Above ftp:// url works for me with DirectoryIterator too, but gives some obscure warning and different results. So I would test with the native functions first.

Body:
RFC1738 mandates the special characters like @ should be urlencoded in the ftp:// scheme. So using %40 in place of the @ in a password fragement would be correct.

But you just wanted the user:password@ prefix before the hostname. Those don't need escaping. And it's already natively supported by the ftp fopen url wrapper:

$d = opendir("ftp://anonymous:nopwd@ftp.kernel.org/pub/");
print readdir($d);

Above ftp:// url works for me with DirectoryIterator too, but gives some obscure warning and different results. So I would test with the native functions first.


问:
Is there any way to change the value of fields whose type is 'table' in runtime (with ajax or etc.) on Laravel Backpack CRUD?
In Laravel Backpack CRUD I want to change the current value of a field whose type is 'table' (I save its content as JSON) after changing an onther field. So is there any way to do this?

For example:
after changing some radio buttons I want to change the content of the 'table' field based on the radio's value.

答:
Yes it's possible. The easiest way to do this, in my opinion, would be to:

create a new field type starting from the radio or checkbox or whatever field type you would like to be the toggle;

use that field type instead of the original field type, in your form;

inside the custom field type, inside the JavaScript, include the logic you want that would customize the table field;


问:
Unable to get IntelliJ to recognize proto compiled Java class files
We have a build.xml in our project, but IntelliJ is unable to import from it. I get a:

```<code>Cannot import anything from <path_to>/build.xml file.
</code>```

On Eclipse I can do a:

```<code>File -> Import -> General -> Existing Projects into workspace.
</code>```

and chose top-level folder. I did the same in IJ. The project imported and indexed fine, I can do a search for any class. However, it does not recognize protobuf compiled class files. I installed the proto plugin, so it syntax highlights my .proto files, but still doesn't realize that there's a compiled class output that it needs to refer to. Do I need to do something special to get it to recognize those files?

答:
An extension to Michele's answer,

There is no bin folder in Mac.

In macOS, when Intellij is unable to recognize proto compiled Java class files,

From the Help menu ---> select Edit Custom Properties. It might ask you to create idea.properties file under

```<code>$HOME//Library/Application\ Support/JetBrains/IdeaIC2020.1/
</code>```

create property idea.max.intellisense.filesize=2500 and set the value to accommodate your big fat proto compiled file for IntelliJ to recognize.

Body:
We have a build.xml in our project, but IntelliJ is unable to import from it. I get a:

Cannot import anything from <path_to>/build.xml file.

On Eclipse I can do a:

File -> Import -> General -> Existing Projects into workspace.

and chose top-level folder. I did the same in IJ. The project imported and indexed fine, I can do a search for any class. However, it does not recognize protobuf compiled class files. I installed the proto plugin, so it syntax highlights my .proto files, but still doesn't realize that there's a compiled class output that it needs to refer to. Do I need to do something special to get it to recognize those files?

Body:
An extension to Michele's answer,

There is no bin folder in Mac.

In macOS, when Intellij is unable to recognize proto compiled Java class files,

From the Help menu ---> select Edit Custom Properties. It might ask you to create idea.properties file under

$HOME//Library/Application\ Support/JetBrains/IdeaIC2020.1/

create property idea.max.intellisense.filesize=2500 and set the value to accommodate your big fat proto compiled file for IntelliJ to recognize.


问:
Invoking a method which uses CompletableFuture's thenAccept()
I have a rest API function which returns an object of type DeferredResult.

```<code>import org.springframework.web.context.request.async.DeferredResult;

public DeferredResult<Object> apiMethod{
CompletableFuture<Object> future = someMethod();
final DeferredResult<Object> response = new DeferredResult<>();

future.thenAccept(){
    //logic to populate response
}

return response;
}
</code>```

I am writing a function which will invoke apiMethod() and use its response. I always end up getting a null response because response is populated in future.thenAccept (). Is there a way to handle this ?

答:
The problem is that the method continues the execution while thenAccept runs async. After you call thenAccept, the method just returns response afterwards, independent of if it's already populated.

Imagine the following simple code:

    public static void main(String[] args) {
        AtomicReference<String> result = new AtomicReference<>(null);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            for (int i = 0; i < 100_000_000; i++) {}
            return "Hello World!";
        });
        future.thenAccept(s -> {
            result.compareAndSet(null, s);
        });
        System.out.println(result.get());
    }
```

<p>You may expect that <code>"Hello World!"</code> is printed, which is not the case; it prints out <code>null</code>. Here's the same problem: the main-thread prints the value, which will be updated async somewhen. You can fix this by joining the future:</p>

<pre class="lang-java prettyprint-override"><code>    public static void main(String[] args) {
        AtomicReference<String> result = new AtomicReference<>(null);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            for (int i = 0; i < 100_000_000; i++) {}
            return "Hello World!";
        });
        CompletableFuture<Void> end = future.thenAccept(s -> {
            result.compareAndSet(null, s);
        });
        end.join();
        System.out.println(result.get());
    }
</code>```

Now when we join the async future chain, or rather the one future that sets the value, we will see the main-thread printing out "Hello World!" because it will wait for the future to finish.

Now you just have to apply this fix in your code.

Body:
I have a rest API function which returns an object of type DeferredResult.

import org.springframework.web.context.request.async.DeferredResult;

public DeferredResult<Object> apiMethod{
CompletableFuture<Object> future = someMethod();
final DeferredResult<Object> response = new DeferredResult<>();

future.thenAccept(){
    //logic to populate response
}

return response;
}

I am writing a function which will invoke apiMethod() and use its response. I always end up getting a null response because response is populated in future.thenAccept (). Is there a way to handle this ?

Body:
The problem is that the method continues the execution while thenAccept runs async. After you call thenAccept, the method just returns response afterwards, independent of if it's already populated.

Imagine the following simple code:

    public static void main(String[] args) {
        AtomicReference<String> result = new AtomicReference<>(null);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            for (int i = 0; i < 100_000_000; i++) {}
            return "Hello World!";
        });
        future.thenAccept(s -> {
            result.compareAndSet(null, s);
        });
        System.out.println(result.get());
    }

You may expect that "Hello World!" is printed, which is not the case; it prints out null. Here's the same problem: the main-thread prints the value, which will be updated async somewhen. You can fix this by joining the future:

    public static void main(String[] args) {
        AtomicReference<String> result = new AtomicReference<>(null);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            for (int i = 0; i < 100_000_000; i++) {}
            return "Hello World!";
        });
        CompletableFuture<Void> end = future.thenAccept(s -> {
            result.compareAndSet(null, s);
        });
        end.join();
        System.out.println(result.get());
    }

Now when we join the async future chain, or rather the one future that sets the value, we will see the main-thread printing out "Hello World!" because it will wait for the future to finish.

Now you just have to apply this fix in your code.


问:
External font does not load when link is loaded from inside the shadowDOM
At the begining I want to say that I'm aware that the question is similar to:

How to let imported css font / icons have effects on elements in the shadow dom?

It's not the case and it does not help.

Issue:
I've recently decided to use the ShadowDOM to encapsulate the styles in my project. At the very begining it I thought it worked as expected but I've noticed that some of the icons coming from the external CSS files were gone.
It's important to notice that those styles are external and possibilities of making changes are limited.

I've prepared the code to demonstrate the issue (look at the snippet below).

Everything seems to be working fine except the @font-face

As You can see, HTML containing the external CSS file with icons works as expected outside the ShadowDOM. I'd like to use it inside the shadowDOM as well.

How can I achieve that ?

NOTE: If you check the dev tools, there is a problem with the CSS path in network tab but it's the SO snippet issue. If You run the snippet locally, everything is ok in network.

const body = document.getElementsByTagName('body')[0];
const wrapper = document.querySelector('.wrapper')

const handleAddToShadowClick = (param) => {
  const host = document.querySelector('#shadowHost');
  if(param === 'insideShadow') {
    const shadowRoot = host.attachShadow({mode: 'open'});
     shadowRoot.innerHTML = firstComponent
  } else {
    const shadowRoot = host;
    wrapper !== null ? body.removeChild(wrapper): ''
    shadowRoot.innerHTML = firstComponent
  }
}

const firstComponent = `

Bla bla

Sample String od text

  <link rel="stylesheet" href="./style.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous">

````
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    font-family: agGridBalham;
    background-color: aquamarine;
    color: black;
}

.balham:before {
    content: "\F11F";
}

.login::before {
    font-family: "Font Awesome 5 Free";
    font-weight: 900;
    content: "\f007";
  }</code>```

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

      Refresh the page after each button click

    <button onclick="handleAddToShadowClick('outside')">Add outside shadow</button>
    <button onclick="handleAddToShadowClick('insideShadow')">Add inside shadow</button>

```

答:
The behavior mentioned in the question is a bug which has been there in chromium(It was also there in Gecko too not sure if it has been fixed or not).

Here is the link for the bug reported at chromium related
  to this issue, which still not resolved by them. At, present i feel
  this is the only workaround which will work.

The issue is mainly related to scoping of @font-face. Currently you cannot use the fonts awesome fonts when they are only included inside the shadow DOM. So inorder to use the fonts the fonts css must be present inside both light DOM and shadow DOM. So you need to import the font css both inside the shadow dom and the light dom.

Here is a Working Plunker which solves your problem.

```<code><html>
  <head>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous">
  </head>

  <body>
      Refresh the page after each button click
    </p>
    <button onclick="handleAddToShadowClick('outside')">Add outside shadow</button>
    <button onclick="handleAddToShadowClick('insideShadow')">Add inside shadow</button>
    <div>
      <div id="shadowHost"> </div>
    </div>
    <script src="lib/script.js"></script>
  </body>
</html>
</code>```

As you can see the plunker above, we have included the font-awesome css both in light DOM and Shadow Dom. And it is working fine as intended.

Body:
At the begining I want to say that I'm aware that the question is similar to:

How to let imported css font / icons have effects on elements in the shadow dom?

It's not the case and it does not help.

Issue:
I've recently decided to use the ShadowDOM to encapsulate the styles in my project. At the very begining it I thought it worked as expected but I've noticed that some of the icons coming from the external CSS files were gone.
It's important to notice that those styles are external and possibilities of making changes are limited.

I've prepared the code to demonstrate the issue (look at the snippet below).

Everything seems to be working fine except the @font-face

As You can see, HTML containing the external CSS file with icons works as expected outside the ShadowDOM. I'd like to use it inside the shadowDOM as well.

How can I achieve that ?

NOTE: If you check the dev tools, there is a problem with the CSS path in network tab but it's the SO snippet issue. If You run the snippet locally, everything is ok in network.

const body = document.getElementsByTagName('body')[0];
const wrapper = document.querySelector('.wrapper')

const handleAddToShadowClick = (param) => {
  const host = document.querySelector('#shadowHost');
  if(param === 'insideShadow') {
    const shadowRoot = host.attachShadow({mode: 'open'});
     shadowRoot.innerHTML = firstComponent
  } else {
    const shadowRoot = host;
    wrapper !== null ? body.removeChild(wrapper): ''
    shadowRoot.innerHTML = firstComponent
  }
}

const firstComponent = `

Bla bla

Sample String od text

  <link rel="stylesheet" href="./style.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous">

`

.wrapper {
    font-family: agGridBalham;
    background-color: aquamarine;
    color: black;
}

.balham:before {
    content: "\F11F";
}

.login::before {
    font-family: "Font Awesome 5 Free";
    font-weight: 900;
    content: "\f007";
  }

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

      Refresh the page after each button click

    <button onclick="handleAddToShadowClick('outside')">Add outside shadow</button>
    <button onclick="handleAddToShadowClick('insideShadow')">Add inside shadow</button>

Body:
The behavior mentioned in the question is a bug which has been there in chromium(It was also there in Gecko too not sure if it has been fixed or not).

Here is the link for the bug reported at chromium related
  to this issue, which still not resolved by them. At, present i feel
  this is the only workaround which will work.

The issue is mainly related to scoping of @font-face. Currently you cannot use the fonts awesome fonts when they are only included inside the shadow DOM. So inorder to use the fonts the fonts css must be present inside both light DOM and shadow DOM. So you need to import the font css both inside the shadow dom and the light dom.

Here is a Working Plunker which solves your problem.

<html>
  <head>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous">
  </head>

  <body>
      Refresh the page after each button click
    </p>
    <button onclick="handleAddToShadowClick('outside')">Add outside shadow</button>
    <button onclick="handleAddToShadowClick('insideShadow')">Add inside shadow</button>
    <div>
      <div id="shadowHost"> </div>
    </div>
    <script src="lib/script.js"></script>
  </body>
</html>

As you can see the plunker above, we have included the font-awesome css both in light DOM and Shadow Dom. And it is working fine as intended.


问:
Read first column's value of selected row in Listbox
I thought it could be useful for users doubleclicking on any entry in the ListBox (Name: Offene_PZ)
and getting information on another Userform. I want to achieve this by taking the value of the first column in the Listbox and paste it in a Textbox of another Form (Name: Packzettelinfo)

I got the Idea from here

```<code>  With Me.Offene_PZ
    For i = 0 To .ListCount - 1 'check for selected row
      If .Selected(i) Then
        With Packzettelinfo
        .show
        .PZ_ID.Value=      'paste the value to there
        End With
        Exit For
      End If
    Next
  End With

But now I

End Sub
</code>```

Since I am still a noob in VBA (but still learning! Will start with VB / Java soon, eager to learn it) I would like to know if it is possible. (Sure it is?)

答:
Okay I figured it out, wasn't so hard if you know how: This was it.

```<code>Private Sub Offene_PZ_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Dim i As Integer

  With Me.Offene_PZ
    For i = 0 To .ListCount - 1
      If .Selected(i) Then

        With Packzettelinfo
        .PZ_ID.Value = Offene_PZ.List(i, 1)
        .show

        End With
        Exit For
      End If
    Next
  End With
  Me.Hide

End Sub
</code>```

So if I may explain: You loop through the Listbox entries, until the .selected row appears, then I take that row with Offene_PZ.List(i, 1) to return the value i need!

Body:
I thought it could be useful for users doubleclicking on any entry in the ListBox (Name: Offene_PZ)
and getting information on another Userform. I want to achieve this by taking the value of the first column in the Listbox and paste it in a Textbox of another Form (Name: Packzettelinfo)

I got the Idea from here

  With Me.Offene_PZ
    For i = 0 To .ListCount - 1 'check for selected row
      If .Selected(i) Then
        With Packzettelinfo
        .show
        .PZ_ID.Value=      'paste the value to there
        End With
        Exit For
      End If
    Next
  End With

But now I

End Sub

Since I am still a noob in VBA (but still learning! Will start with VB / Java soon, eager to learn it) I would like to know if it is possible. (Sure it is?)

Body:
Okay I figured it out, wasn't so hard if you know how: This was it.

Private Sub Offene_PZ_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Dim i As Integer

  With Me.Offene_PZ
    For i = 0 To .ListCount - 1
      If .Selected(i) Then

        With Packzettelinfo
        .PZ_ID.Value = Offene_PZ.List(i, 1)
        .show

        End With
        Exit For
      End If
    Next
  End With
  Me.Hide

End Sub

So if I may explain: You loop through the Listbox entries, until the .selected row appears, then I take that row with Offene_PZ.List(i, 1) to return the value i need!


问:
How to generate this R function for random effect model?
I'm trying to create a code such that Y = 5g1(X1) + 3g2(X2) + 4g3(X3) + 6g4(X4) + sqrt(1.74)*eps (the functions g, are defined in the code).

X = (X1,...,Xp) should be an nxp dimensional design matrix, however I'm not sure about how to generate that based on this information where Xj = W+U is simulated according to a random effects model. I tried using X = do.call(cbind, replicate(p, X, simplify=FALSE)) but this just replicates each Xj, i'm not sure that's what should be done, they should be different.

Any advice on what i have missed would be appreciated and any improvements on the code too to make it more concise.

```<code>n<- 400
p<- 1000
W = runif(n)
U = runif(n)
eps = rnorm(n)

for (j in 1:p){
   X = W+U
   X = as.matrix(X)
return(X)} #This is a nx1 matrix...
#alternatively write: X = do.call(cbind, replicate(p, X, simplify=FALSE))

g1 = X
g2 = (2*X-1)^2
g3 = sin(2*pi*X)/(2-sin(2*pi*X))
g4 = 0.1*sin(2*pi*X) + 0.2*cos(2*pi*X) + 0.3*sin(2*pi*X)^2 + 0.4*cos(2*pi*X)^3 + 0.5*sin(2*pi*X)^3

Y = 5*g1 + 3*g2 + 4*g3 + 6*g4 + sqrt(1.74)*eps
return(Y)
}
</code>```

答:
I am not sure to capture the logic of your calculation, eventually it is something like this:

```<code>n <- 40 # 400
p <- 100 # 1000

X <- replicate(p, runif(n) + runif(n))  ## W+U

y <- function(X) {
  g1 <- X
  g2 <- (2*X-1)^2
  g3 <- sin(2*pi*X)/(2-sin(2*pi*X))
  g4 <- 0.1*sin(2*pi*X) + 0.2*cos(2*pi*X) + 0.3*sin(2*pi*X)^2 + 0.4*cos(2*pi*X)^3 + 0.5*sin(2*pi*X)^3
  eps <- rnorm(length(X))
  Y <- 5*g1 + 3*g2 + 4*g3 + 6*g4 + sqrt(1.74)*eps
  return(Y)
}

Y <- apply(X, 2, FUN=y)
</code>```

Also the variant without apply() works:

```<code>Y <- y(X)
</code>```

To compare both variants:

```<code>set.seed(42)
Y1 <- apply(X, 2, FUN=y)

set.seed(42)
Y2 <- y(X)

identical(Y1, Y2)
</code>```

Body:
I'm trying to create a code such that Y = 5g1(X1) + 3g2(X2) + 4g3(X3) + 6g4(X4) + sqrt(1.74)*eps (the functions g, are defined in the code).

X = (X1,...,Xp) should be an nxp dimensional design matrix, however I'm not sure about how to generate that based on this information where Xj = W+U is simulated according to a random effects model. I tried using X = do.call(cbind, replicate(p, X, simplify=FALSE)) but this just replicates each Xj, i'm not sure that's what should be done, they should be different.

Any advice on what i have missed would be appreciated and any improvements on the code too to make it more concise.

n<- 400
p<- 1000
W = runif(n)
U = runif(n)
eps = rnorm(n)

for (j in 1:p){
   X = W+U
   X = as.matrix(X)
return(X)} #This is a nx1 matrix...
#alternatively write: X = do.call(cbind, replicate(p, X, simplify=FALSE))

g1 = X
g2 = (2*X-1)^2
g3 = sin(2*pi*X)/(2-sin(2*pi*X))
g4 = 0.1*sin(2*pi*X) + 0.2*cos(2*pi*X) + 0.3*sin(2*pi*X)^2 + 0.4*cos(2*pi*X)^3 + 0.5*sin(2*pi*X)^3

Y = 5*g1 + 3*g2 + 4*g3 + 6*g4 + sqrt(1.74)*eps
return(Y)
}

Body:
I am not sure to capture the logic of your calculation, eventually it is something like this:

n <- 40 # 400
p <- 100 # 1000

X <- replicate(p, runif(n) + runif(n))  ## W+U

y <- function(X) {
  g1 <- X
  g2 <- (2*X-1)^2
  g3 <- sin(2*pi*X)/(2-sin(2*pi*X))
  g4 <- 0.1*sin(2*pi*X) + 0.2*cos(2*pi*X) + 0.3*sin(2*pi*X)^2 + 0.4*cos(2*pi*X)^3 + 0.5*sin(2*pi*X)^3
  eps <- rnorm(length(X))
  Y <- 5*g1 + 3*g2 + 4*g3 + 6*g4 + sqrt(1.74)*eps
  return(Y)
}

Y <- apply(X, 2, FUN=y)

Also the variant without apply() works:

Y <- y(X)

To compare both variants:

set.seed(42)
Y1 <- apply(X, 2, FUN=y)

set.seed(42)
Y2 <- y(X)

identical(Y1, Y2)


问:
Send data between servers Kafka Apache on Python
```<code>producer = KafkaProducer(bootstrap_servers='kf-p1l-node3:9092,xxxxx,xxxxx',
                                 value_serializer=lambda x: dumps(x).encode('utf-8'))  # utf-8
</code>```

```<code>consumer = KafkaConsumer(  bootstrap_servers='rdwh-node1:49092,xxxxx,xxxxx',
                                 # bootstrap_servers='kf-p1l-node3:9092,xxxxx,xxxxx',
                                 auto_offset_reset=param["AUTO_OFFSET_RESET"],
                                 consumer_timeout_ms=param["CONSUMER_TIMEOUT_MS"],
                                 enable_auto_commit=False,
                                 auto_commit_interval_ms=60000,
                                 group_id=param["GROUP_ID"],
                                 client_id=param["CLIENT_ID"]
                                 )
consumer.subscribe([param["TOPIC_IN"]])
</code>```

This code work if, KafkaProducer and KafkaConsumer's bootstrap_server are the same. But if change  KafkaConsumer to another server it doesn't work

答:
Bootstrap servers must contain all servers for establishing the initial connection to the Kafka cluster. The client will make use of all servers irrespective of which servers are specified here for bootstrapping. You can check the documentation here: http://kafka.apache.org/090/documentation.html

consumer = KafkaConsumer('my-topic',
                         group_id='my-group',
                         bootstrap_servers=['node1:port1', 'node1:port2', 'node2:port3'])
```

Body:
producer = KafkaProducer(bootstrap_servers='kf-p1l-node3:9092,xxxxx,xxxxx',
                                 value_serializer=lambda x: dumps(x).encode('utf-8'))  # utf-8

consumer = KafkaConsumer(  bootstrap_servers='rdwh-node1:49092,xxxxx,xxxxx',
                                 # bootstrap_servers='kf-p1l-node3:9092,xxxxx,xxxxx',
                                 auto_offset_reset=param["AUTO_OFFSET_RESET"],
                                 consumer_timeout_ms=param["CONSUMER_TIMEOUT_MS"],
                                 enable_auto_commit=False,
                                 auto_commit_interval_ms=60000,
                                 group_id=param["GROUP_ID"],
                                 client_id=param["CLIENT_ID"]
                                 )
consumer.subscribe([param["TOPIC_IN"]])

This code work if, KafkaProducer and KafkaConsumer's bootstrap_server are the same. But if change  KafkaConsumer to another server it doesn't work


问:
Issue with EditText's On TextChange Listener
In my Recyclerview's Adapter class, I have done something as below:

```<code>holder.mEdtDescription.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(p0: Editable?) {
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        listener.onDeleteOrDescribe(position, "" + holder.mEdtDescription.text.toString(), "describe")
    }
})

holder.mIvDelete.setOnClickListener {
    listener.onDeleteOrDescribe(position, "", "delete")
}
</code>```

mEdtDescription is EditText.

On deleting some value from the recycler my adapter calls method onDeleteOrDescribe.
Unfortunately, At the same time onTextChanged is also calling.

How can I avoid calling onTextChanged when I am deleting soemthing?

Hope you got the point.

As per the solution, I have tried disabling textWatcher as below :

```<code>val textWatcher: TextWatcher = object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            ToastUtil.displayShortDurationToast(mContext,"called")
            listener.onDeleteOrDescribe(
                position,
                "" + holder.mEdtDescription.text.toString(),
                "describe"
            )
        }
    }
    holder.mEdtDescription.addTextChangedListener(textWatcher)

    holder.mIvDelete.setOnClickListener {
        //listener.onDeleteStep(position)
        holder.mEdtDescription.removeTextChangedListener(textWatcher)
        listener.onDeleteOrDescribe(position, "", "delete")
        holder.mEdtDescription.addTextChangedListener(textWatcher)
    }
</code>```

But, still is calling onTextChange()   :(

答:
You could try disabling the TextWatcher temporarily:</p>

```<code>val textWatcher :  TextWatcher = object : TextWatcher {
    override fun afterTextChanged(p0: Editable?) {
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        listener.onDeleteOrDescribe(position, holder.mEdtDescription.text.toString(), "describe")
    }
}

holder.mEdtDescription.addTextChangedListener(textWatcher)

holder.mIvDelete.setOnClickListener {
    holder.mEdtDescription.removeTextChangedListener(textWatcher)
    listener.onDeleteOrDescribe(position, "", "delete")
    holder.mEdtDescription.addTextChangedListener(textWatcher)
}
</code>```

Body:
In my Recyclerview's Adapter class, I have done something as below:

holder.mEdtDescription.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(p0: Editable?) {
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        listener.onDeleteOrDescribe(position, "" + holder.mEdtDescription.text.toString(), "describe")
    }
})

holder.mIvDelete.setOnClickListener {
    listener.onDeleteOrDescribe(position, "", "delete")
}

mEdtDescription is EditText.

On deleting some value from the recycler my adapter calls method onDeleteOrDescribe.
Unfortunately, At the same time onTextChanged is also calling.

How can I avoid calling onTextChanged when I am deleting soemthing?

Hope you got the point.

As per the solution, I have tried disabling textWatcher as below :

val textWatcher: TextWatcher = object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            ToastUtil.displayShortDurationToast(mContext,"called")
            listener.onDeleteOrDescribe(
                position,
                "" + holder.mEdtDescription.text.toString(),
                "describe"
            )
        }
    }
    holder.mEdtDescription.addTextChangedListener(textWatcher)

    holder.mIvDelete.setOnClickListener {
        //listener.onDeleteStep(position)
        holder.mEdtDescription.removeTextChangedListener(textWatcher)
        listener.onDeleteOrDescribe(position, "", "delete")
        holder.mEdtDescription.addTextChangedListener(textWatcher)
    }

But, still is calling onTextChange()   :(

Body:
You could try disabling the TextWatcher temporarily:

val textWatcher :  TextWatcher = object : TextWatcher {
    override fun afterTextChanged(p0: Editable?) {
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        listener.onDeleteOrDescribe(position, holder.mEdtDescription.text.toString(), "describe")
    }
}

holder.mEdtDescription.addTextChangedListener(textWatcher)

holder.mIvDelete.setOnClickListener {
    holder.mEdtDescription.removeTextChangedListener(textWatcher)
    listener.onDeleteOrDescribe(position, "", "delete")
    holder.mEdtDescription.addTextChangedListener(textWatcher)
}


问:
Print json value without quotes for python
I have the following json:

```<code>{
  "email": "lalalalal@gmail.com"
}
</code>```

and little test script:

```<code>file = open('/Users/user/PycharmProjects/Test/newfile.json')
x = json.load(file)
y = repr(x['email'])
print('My test email is ' + y)
</code>```

I receive next output:

```<code>My test email is 'lalalalal@gmail.com'
</code>```

My question is:

How to receive JSON value data (print also) without ordinary quotes in output?

To receive:

My test email is lalalalal@gmail.com

答:
You should not use repr. You can get the value without repr</p>

```<code>x['email']
</code>```

Body:
I have the following json:

{
  "email": "lalalalal@gmail.com"
}

and little test script:

file = open('/Users/user/PycharmProjects/Test/newfile.json')
x = json.load(file)
y = repr(x['email'])
print('My test email is ' + y)

I receive next output:

My test email is 'lalalalal@gmail.com'

My question is:

How to receive JSON value data (print also) without ordinary quotes in output?

To receive:

My test email is lalalalal@gmail.com

Body:
You should not use repr. You can get the value without repr

x['email']