问:
summarize count with a condition
I have a data frame of counts in quadrats for a bunch of species in a bunch of years, but sometimes instead of counts, they are marked as "p" for "present." I want to average them while counting those p's as NA in the averaging, but also keep track of the number of p's there are in each species/year, so my question is, is there a way to use summarize(count) to count occurrences of P?

minimal example:

```<code>df <- data.frame(
  # years
  year = rep(1990:1992, each=3),
  # character vector of counts and p's
  count = c("p","p","2","1","5","4","7","p","4")
) %>%
  # numeric column of counts and NAs where P's should be
  mutate(count_numeric = as.numeric(count))

# summarize dataset
df %>%
  group_by(year) %>%
  summarize(number_quadrats = n(), # find total number of rows
            average_count = mean(count_numeric, na.rm=T)) # find average value

</code>```

but I want to add another line to the summarize that will just count the number of P's in each group. Something like this:

```<code>df %>%
  group_by(year) %>%
  summarize(number_quadrats = n(), # find total number of rows
            average_count = mean(count_numeric, na.rm=T),# find average value
            number_p = n(count == "p"))
</code>```

but that doesn't work.

Any advice appreciated.

Thanks!

答:
Just change the last line:

```<code>df %>%
group_by(year) %>%
summarize(number_quadrats = n(), # find total number of rows
          average_count = mean(count_numeric, na.rm=T),# find average value
          number_p = sum(count == "p"))
</code>```

By summing a boolean vector, you are essentially counting the number of times the condition is met.

Title: summarize count with a condition

Body:
I have a data frame of counts in quadrats for a bunch of species in a bunch of years, but sometimes instead of counts, they are marked as "p" for "present." I want to average them while counting those p's as NA in the averaging, but also keep track of the number of p's there are in each species/year, so my question is, is there a way to use summarize(count) to count occurrences of P?

minimal example:

df <- data.frame(
  # years
  year = rep(1990:1992, each=3),
  # character vector of counts and p's
  count = c("p","p","2","1","5","4","7","p","4")
) %>%
  # numeric column of counts and NAs where P's should be
  mutate(count_numeric = as.numeric(count))

# summarize dataset
df %>%
  group_by(year) %>%
  summarize(number_quadrats = n(), # find total number of rows
            average_count = mean(count_numeric, na.rm=T)) # find average value

but I want to add another line to the summarize that will just count the number of P's in each group. Something like this:

df %>%
  group_by(year) %>%
  summarize(number_quadrats = n(), # find total number of rows
            average_count = mean(count_numeric, na.rm=T),# find average value
            number_p = n(count == "p"))

but that doesn't work.

Any advice appreciated.

Thanks!

Body:
Just change the last line:

df %>%
group_by(year) %>%
summarize(number_quadrats = n(), # find total number of rows
          average_count = mean(count_numeric, na.rm=T),# find average value
          number_p = sum(count == "p"))

By summing a boolean vector, you are essentially counting the number of times the condition is met.


来源: stackexchange

问:
Relations between slowly changing dimensions in a data warehouse
I’m designing a data warehouse and am struggling to work out how I should be modelling this scenario. I’ve got Users stored in a Slowly Changing Dimension Type 2 table along these lines:

UserKey
UserID
Language
EffectiveDate
ExpiryDate
IsCurrent

1
1001
EN
2021-01-01
9999-12-3
Y

2
1002
EN
2021-07-31
2022-01-06
N

3
1002
FR
2022-01-06
9999-12-31
Y

And a Login fact table like:

LoginKey
UserKey
LoginTime

12345
2
2021-12-25 15:00

12399
3
2022-01-31 18:00

Thereby allowing us to report on logins by date by user language setting at the time, etc.

Now I have to consider that each user may have one, none, or many concurrent subscriptions, which I was thinking of modelling in a Type 1 SCD thus:

SubsKey
SubsID
SubsType
UserKey
StartDate
EndDate

55501
SBP501
Premium
2
2021-08-01
2022-08-01

55502
SBB123
Bonus
3
2022-01-31
2023-01-31

Is it right for one dimension table to reference the surrogate row key of another like this, or should it rather contain the UserID natural key? It seems unwieldy for the Subs table to have different UserKeys for the two concurrent Subscriptions for the same user like this. Or perhaps, when the third row was added to the Type 2 User table, should all the existing rows in Subs with UserKey=2 have been updated to UserKey=3?

The whole thing doesn't seem to fit comfortably into the classic snowflake pattern, which usually has the one-to-many relationship pointing the other way, as might be the case were Language to be a separate dimension table say, with a one-to-many relation on User.

Edit

I'm wrestling with not only in the one-to-many example described (one user has many subscriptions) but also many-to-one relations between SCDT2 tables e.g. If the user's language was stored in a SCDT2 table, should the User dimension use reference the Language ID or the LanguageKey for Language table's current row?

答:
A subscription is a fact and so should be stored in a fact table - though you might also have a subscription dimension that holds attributes of a subscription such as its name.
You relate dimensions through fact tables, so your subscription fact would have FKs to Subscription, User, Date etc dimensions.

Relating dimensions directly to each other is called snowflaking and is, generally a bad design.

BTW for an SCD2 table, having the expiry date of one row the same as the effective date of the next row is not a good design. In your example, you would need business logic to define which row was active on 2022-01-06, whereas if a row expires on 2022-01-06 and the next row starts on 2022-01-07 there can be no confusion.

ContentLicense: CC BY-SA 4.0


问:
Javascript alert function not displaying message after clicking button
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.</p>
```<code>    <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <style type="text/css">

      body {
        margin: 40px;
        font-family: 'Open Sans';
      }
      #fieldSize, #fieldCrust {
        width: 150px;
        float: left;
        border: none;
      }
       #fieldToppings {
         width: 350px;
         border: none;

       }
       fieldset {
         margin-top: 20px;
       }
      #toppings1 {
        float: left;
      }
      label {
        display: inline-block;
        width: 150px;
        margin: 7px;
        text-align: left;
      }
      input[type="text"] {
        width: 250px;
      }
      div {
        padding: 10px;
      }
      #btnOrder {
        width: auto;
        border-radius: 10px;
      }

    </style>
    <script type="text/javascript">

      function orderSubmit() {
        var name = document.getElementById("txtName").value;
        var phone = document.getElementById("txtPhone").value;
        phone = '(' + phone.substring(0,3) + ')' + phone.substring(3,6) + '-' + phone.substring(6);
        var address = document.getElementById("txtAddress").value;

        var msg = name + ", your order is being prepared. \n";
        msg+= "Your order will be delivered at " + address;
        msg+= "Your contact infromation is: " + phone "\n";
        msg+= "Order details: \n \n";

        for(var i = 0; i < document.frm1.rdoSize.length; i++) {
           if(document.frm1.rdoSize[i].checked) {
             var radioStateSize = document.frm1.rdoSize[i].value;
           }
        }
        for(var j = 0; j < document.frm1.rdoCrust.length; j++) {
           if(document.frm1.rdoCrust[j].checked) {
             var radioStateCrust = document.frm1.rdoCrust[j].value;
           }
        }
        msg+= radioStateSize + ' ' + radioStateCrust + " pizza with the following toppings: \n";

        var chkToppings = document.frm1.chkToppings;

        for(k=0; k < document.frm1.chkToppings; k++) {
           if(document.frm1.chkToppings[k].checked) {
           msg += document.frm1.chkToppings[k].value + ' ';
           }
        }
        alert(msg);
      }

    </script>

  </head>

  <body>
    <fieldset id="main">
      <legend><h2>Pizza Order!</h2></legend>

      <form name="frm1">
        <div>
          <label for="lblName">Name:</label>
          <input type="text" id="txtName">
        </div>

        <div>
          <label for="lblPhone">Phone Number:</label>
          <input type="text" id="txtPhone">
        </div>

        <div>
          <label for="lblAddress">Address:</label>
          <input type="text" id="txtAddress">
        </div>

      <fieldset id="fieldSize">
        <legend><strong>Size</strong></legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small <br>
          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium <br>
          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large <br>
      </fieldset>

      <fieldset id="fieldCrust">
        <legend><strong>Crust</strong></legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small <br>
          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed <br>
          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free <br>
      </fieldset>

      <fieldset id="fieldToppings">
        <legend><strong>Toppings</strong></legend>
          <div id="toppings1">
            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage <br>
            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken <br>
            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies <br>
          </div>
          <div id="toppings2">
            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms <br>
            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers <br>
            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta <br>
            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives <br>
            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions <br>
          </div>
      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>
  </body>
</html>
</code>```

答:
You had a type here msg+= "Your contact infromation is: " + phone "\n"; you must add + between phone + "\n";.

You can run the snippet below, it works.

function orderSubmit() {
  var name = document.getElementById("txtName").value;
  var phone = document.getElementById("txtPhone").value;
  phone = "(" + phone.substring(0,3) + ")" + phone.substring(3,6) + "-" + phone.substring(6);
  var address = document.getElementById("txtAddress").value;

  var msg = name + ", your order is being prepared. \n";
  msg+= "Your order will be delivered at " + address;
  msg+= "Your contact infromation is: " + phone + "\n"; // <- Problem is that you forgot "+"
  msg+= "Order details: \n \n";

  for(var i = 0; i < document.frm1.rdoSize.length; i++) {
     if(document.frm1.rdoSize[i].checked) {
       var radioStateSize = document.frm1.rdoSize[i].value;
     }
  }
  for(var j = 0; j < document.frm1.rdoCrust.length; j++) {
     if(document.frm1.rdoCrust[j].checked) {
       var radioStateCrust = document.frm1.rdoCrust[j].value;
     }
  }
  msg+= radioStateSize + " " + radioStateCrust + " pizza with the following toppings: \n";

  var chkToppings = document.frm1.chkToppings;
  for(var k=0; k < document.frm1.chkToppings; k++) { // add var k
     if(document.frm1.chkToppings[k].checked)
     msg += document.frm1.chkToppings[k].value + ' ';
  }
  alert(msg);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
        margin: 40px;
        font-family: 'Open Sans';
      }
      #fieldSize, #fieldCrust {
        width: 150px;
        float: left;
        border: none;
      }
       #fieldToppings {
         width: 350px;
         border: none;

       }
       fieldset {
         margin-top: 20px;
       }
      #toppings1 {
        float: left;
      }
      label {
        display: inline-block;
        width: 150px;
        margin: 7px;
        text-align: left;
      }
      input[type="text"] {
        width: 250px;
      }
      div {
        padding: 10px;
      }
      #btnOrder {
        width: auto;
        border-radius: 10px;
      }</code>```

<!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Gianni's Pizzeria</title>

    <fieldset id="main">
      <legend>
Pizza Order!
</legend>

      <form name="frm1">

          Name:
          <input type="text" id="txtName">

          Phone Number:
          <input type="text" id="txtPhone">

          Address:
          <input type="text" id="txtAddress">

      <fieldset id="fieldSize">
        <legend>Size</legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small

          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium

          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large

      </fieldset>

      <fieldset id="fieldCrust">
        <legend>Crust</legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small

          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed

          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free

      </fieldset>

      <fieldset id="fieldToppings">
        <legend>Toppings</legend>

            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage

            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken

            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies

            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms

            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers

            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta

            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives

            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions

      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>

```

Body:
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.

    <!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <fieldset id="main">
      <legend>
Pizza Order!
</legend>

      <form name="frm1">

          Name:
          <input type="text" id="txtName">

          Phone Number:
          <input type="text" id="txtPhone">

          Address:
          <input type="text" id="txtAddress">

      <fieldset id="fieldSize">
        <legend>Size</legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small

          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium

          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large

      </fieldset>

      <fieldset id="fieldCrust">
        <legend>Crust</legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small

          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed

          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free

      </fieldset>

      <fieldset id="fieldToppings">
        <legend>Toppings</legend>

            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage

            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken

            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies

            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms

            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers

            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta

            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives

            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions

      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>

Body:
You had a type here msg+= "Your contact infromation is: " + phone "\n"; you must add + between phone + "\n";.

You can run the snippet below, it works.

function orderSubmit() {
  var name = document.getElementById("txtName").value;
  var phone = document.getElementById("txtPhone").value;
  phone = "(" + phone.substring(0,3) + ")" + phone.substring(3,6) + "-" + phone.substring(6);
  var address = document.getElementById("txtAddress").value;

  var msg = name + ", your order is being prepared. \n";
  msg+= "Your order will be delivered at " + address;
  msg+= "Your contact infromation is: " + phone + "\n"; // <- Problem is that you forgot "+"
  msg+= "Order details: \n \n";

  for(var i = 0; i < document.frm1.rdoSize.length; i++) {
     if(document.frm1.rdoSize[i].checked) {
       var radioStateSize = document.frm1.rdoSize[i].value;
     }
  }
  for(var j = 0; j < document.frm1.rdoCrust.length; j++) {
     if(document.frm1.rdoCrust[j].checked) {
       var radioStateCrust = document.frm1.rdoCrust[j].value;
     }
  }
  msg+= radioStateSize + " " + radioStateCrust + " pizza with the following toppings: \n";

  var chkToppings = document.frm1.chkToppings;
  for(var k=0; k < document.frm1.chkToppings; k++) { // add var k
     if(document.frm1.chkToppings[k].checked)
     msg += document.frm1.chkToppings[k].value + ' ';
  }
  alert(msg);
}

body {
        margin: 40px;
        font-family: 'Open Sans';
      }
      #fieldSize, #fieldCrust {
        width: 150px;
        float: left;
        border: none;
      }
       #fieldToppings {
         width: 350px;
         border: none;

       }
       fieldset {
         margin-top: 20px;
       }
      #toppings1 {
        float: left;
      }
      label {
        display: inline-block;
        width: 150px;
        margin: 7px;
        text-align: left;
      }
      input[type="text"] {
        width: 250px;
      }
      div {
        padding: 10px;
      }
      #btnOrder {
        width: auto;
        border-radius: 10px;
      }

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Gianni's Pizzeria</title>
  </head>

  <body>
    <fieldset id="main">
      <legend><h2>Pizza Order!</h2></legend>

      <form name="frm1">
        <div>
          <label for="lblName">Name:</label>
          <input type="text" id="txtName">
        </div>

        <div>
          <label for="lblPhone">Phone Number:</label>
          <input type="text" id="txtPhone">
        </div>

        <div>
          <label for="lblAddress">Address:</label>
          <input type="text" id="txtAddress">
        </div>

      <fieldset id="fieldSize">
        <legend><strong>Size</strong></legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small <br>
          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium <br>
          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large <br>
      </fieldset>

      <fieldset id="fieldCrust">
        <legend><strong>Crust</strong></legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small <br>
          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed <br>
          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free <br>
      </fieldset>

      <fieldset id="fieldToppings">
        <legend><strong>Toppings</strong></legend>
          <div id="toppings1">
            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage <br>
            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken <br>
            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies <br>
          </div>
          <div id="toppings2">
            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms <br>
            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers <br>
            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta <br>
            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives <br>
            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions <br>
          </div>
      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>
  </body>
</html>


问:
TypeError: Cannot read properties of undefined (reading 'fetch') Discord.js v13
Trying to get 10 messages from every channel in a guild and read the contents then see if they contain a certain string but getting the error below

```<code>TypeError: Cannot read properties of undefined (reading 'fetch')
</code>```

This is my code

```<code>interaction.guild.channels.cache.forEach(c => {
   c.messages.fetch({limit: 10}).then(msgs => {
      msgs.forEach(m => {
         if (m.content.includes(interaction.options.getString('text',true))) {
            // will do stuff here
         }
      }).catch(err => console.error(err))
   })
})
</code>```

答:
interaction.guild.channels.cache is a collection of GuildChannel.

GuildChannels combines all theses categories of channels.

Unfortunately, only Text Channels and News Channels have a messages property.

Maybe you need to check this condition before fetch the messages.

interaction.guild.channels.cache.forEach(c => {
   if(c.type == 'GUILD_TEXT'){
      c.messages.fetch({limit: 10}).then(msgs => {
         msgs.forEach(m => {
            if (m.content.includes(interaction.options.getString('text',true))) {
               // will do stuff here
            }
         }).catch(err => console.error(err))
      })
   }
})
```
<p>You can also filter the channels</p>
<pre class="lang-js prettyprint-override"><code>interaction.guild.channels.cache.filter((c) => c.type == 'GUILD_TEXT').forEach(c => {
   c.messages.fetch({limit: 10}).then(msgs => {
      msgs.forEach(m => {
         if (m.content.includes(interaction.options.getString('text',true))) {
            // will do stuff here
         }
      }).catch(err => console.error(err))
   })
})
</code>```

Body:
Trying to get 10 messages from every channel in a guild and read the contents then see if they contain a certain string but getting the error below

TypeError: Cannot read properties of undefined (reading 'fetch')

This is my code

interaction.guild.channels.cache.forEach(c => {
   c.messages.fetch({limit: 10}).then(msgs => {
      msgs.forEach(m => {
         if (m.content.includes(interaction.options.getString('text',true))) {
            // will do stuff here
         }
      }).catch(err => console.error(err))
   })
})

Body:
interaction.guild.channels.cache is a collection of GuildChannel.

GuildChannels combines all theses categories of channels.

Unfortunately, only Text Channels and News Channels have a messages property.

Maybe you need to check this condition before fetch the messages.

interaction.guild.channels.cache.forEach(c => {
   if(c.type == 'GUILD_TEXT'){
      c.messages.fetch({limit: 10}).then(msgs => {
         msgs.forEach(m => {
            if (m.content.includes(interaction.options.getString('text',true))) {
               // will do stuff here
            }
         }).catch(err => console.error(err))
      })
   }
})

You can also filter the channels

interaction.guild.channels.cache.filter((c) => c.type == 'GUILD_TEXT').forEach(c => {
   c.messages.fetch({limit: 10}).then(msgs => {
      msgs.forEach(m => {
         if (m.content.includes(interaction.options.getString('text',true))) {
            // will do stuff here
         }
      }).catch(err => console.error(err))
   })
})


问:
Reorder Function in R Issues
I am trying to add reorder to get the data set to arrange from largest to smallest but having issues.

```<code>ggplot(Manager_Graph_Data, aes(x = reorder(Manager_Graph_Data$`Completion Rate`), y = Manager_Graph_Data$Manager)) +
  geom_bar(stat="identity",
           position="identity",
           fill="#0077b5")

structure(list(Manager = c("Bob Beno", "Dylan Tracy", "Ignacia Lemley",
"Jaimee Cogdill", "Jeneva Engman", "Julianne Holdren", "Lakia Farrington",
"Lester Braden", "Soon Mooneyham"), Complete = c(5, 5, 1, 4,
0, 0, 3, 2, 5), Incomplete = c(6, 6, 7, 2, 3, 4, 5, 2, 3), Total = c(11,
11, 8, 6, 3, 4, 8, 4, 8), `Completion Rate` = c(0.454545454545455,
0.454545454545455, 0.125, 0.666666666666667, 0, 0, 0.375, 0.5,
0.625)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-9L))
</code>```

Any help will be much appreciated

答:
It looks like you're trying to order by the completion rate. When you have a bar or column chart, ggplot will order by the factor (or character) field. So to change the order, set the factor levels. There are a variety of ways to do this. Here is one way:

```<code>library(tidyverse)

# order by rate decreasing
MgrRate <- Manager_Graph_Data %>%
  arrange(`Completion Rate`, decreasing = T) %>%
  mutate(Manager = ordered(Manager, levels = .$Manager))

ggplot(MgrRate,
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_bar(stat="identity",
           position="identity",
           fill="#0077b5")
</code>```

In case you were not aware, if you want to set an x and y, try using geom_col() to simplify things.

```<code># alternatively (creating the same plot)
ggplot(MgrRate,
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_col(fill="#0077b5")
</code>```

If you actually wanted to order by the manager, here's an example of how to do that. (This is by the first name of the manager.)

```<code># order by manager's first name
Mgr <- Manager_Graph_Data %>%
  arrange(desc(Manager)) %>%
  mutate(Manager = ordered(Manager, levels = .$Manager))

ggplot(Mgr,
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_col(fill="#0077b5")
</code>```

Just so you are aware, when you flip the axes (but the factor on y, instead of x) you have to reverse the order.

Title: Reorder Function in R Issues

Body:
I am trying to add reorder to get the data set to arrange from largest to smallest but having issues.

ggplot(Manager_Graph_Data, aes(x = reorder(Manager_Graph_Data$`Completion Rate`), y = Manager_Graph_Data$Manager)) +
  geom_bar(stat="identity",
           position="identity",
           fill="#0077b5")

structure(list(Manager = c("Bob Beno", "Dylan Tracy", "Ignacia Lemley",
"Jaimee Cogdill", "Jeneva Engman", "Julianne Holdren", "Lakia Farrington",
"Lester Braden", "Soon Mooneyham"), Complete = c(5, 5, 1, 4,
0, 0, 3, 2, 5), Incomplete = c(6, 6, 7, 2, 3, 4, 5, 2, 3), Total = c(11,
11, 8, 6, 3, 4, 8, 4, 8), `Completion Rate` = c(0.454545454545455,
0.454545454545455, 0.125, 0.666666666666667, 0, 0, 0.375, 0.5,
0.625)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-9L))

Any help will be much appreciated

Body:
It looks like you're trying to order by the completion rate. When you have a bar or column chart, ggplot will order by the factor (or character) field. So to change the order, set the factor levels. There are a variety of ways to do this. Here is one way:

library(tidyverse)

# order by rate decreasing
MgrRate <- Manager_Graph_Data %>%
  arrange(`Completion Rate`, decreasing = T) %>%
  mutate(Manager = ordered(Manager, levels = .$Manager))

ggplot(MgrRate,
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_bar(stat="identity",
           position="identity",
           fill="#0077b5")

In case you were not aware, if you want to set an x and y, try using geom_col() to simplify things.

# alternatively (creating the same plot)
ggplot(MgrRate,
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_col(fill="#0077b5")

If you actually wanted to order by the manager, here's an example of how to do that. (This is by the first name of the manager.)

# order by manager's first name
Mgr <- Manager_Graph_Data %>%
  arrange(desc(Manager)) %>%
  mutate(Manager = ordered(Manager, levels = .$Manager))

ggplot(Mgr,
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_col(fill="#0077b5")

Just so you are aware, when you flip the axes (but the factor on y, instead of x) you have to reverse the order.


问:
How can I shift the rows of a 2d array down by 1 in java?
What would be the most basic way to shift the rows of a 2d array in java down by 1. The first row turns into the second row, the second row turns into the third row and the last row turns into the first one.

I tried this but it only lets me change two rows.

```<code>public static void switchRows(int[][] matrix, int K, int L){
   for (int i = 0; i < matrix[0].length; i++) {
   // Swap two numbers
     int temp = matrix[K - 1][i];
     matrix[K - 1][i] = matrix[L - 1][i];
     matrix[L - 1][i] = temp;
   }
   // Print matrix
   for(int g = 0; g < matrix.length; g++){
      for(int b = 0; b < matrix[g].length; b++){
         System.out.print(matrix[g][b] + " ");
      }
      System.out.println();
   }
}
</code>```

答:
For this problem first, you need to create a copy of the array that represents the last row (lastRow).

After that, all values for each row (except the first row matrix[0]) have to be overwritten with values from the previous row.

Finally, assign the reference to the defensive copy of last row to the first row of the matrix.

```<code>public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };
        switchRows(matrix);
        printMatrix(matrix);
    }
</code>```
```<code>    public static void switchRows(int[][] matrix){
        int[] lastRow = Arrays.copyOf(matrix[matrix.length - 1], matrix[matrix.length - 1].length);
        for (int row = matrix.length - 1; row > 0; row--) {
            // assign values of the previous row to current row
            for (int col = 0; col < matrix[row].length; col++) {
                matrix[row][col] = matrix[row - 1][col];
            }
        }
        matrix[0] = lastRow;
    }
</code>```
```<code>    public static void printMatrix(int[][] matrix) {
        for (int row = 0; row < matrix.length; row++){
            for(int col = 0; col < matrix[row].length; col++){
                System.out.print(matrix[row][col] + " ");
            }
            System.out.println();
        }
    }
</code>```

output

```<code>7 8 9
1 2 3
4 5 6
</code>```

Body:
What would be the most basic way to shift the rows of a 2d array in java down by 1. The first row turns into the second row, the second row turns into the third row and the last row turns into the first one.

I tried this but it only lets me change two rows.

public static void switchRows(int[][] matrix, int K, int L){
   for (int i = 0; i < matrix[0].length; i++) {
   // Swap two numbers
     int temp = matrix[K - 1][i];
     matrix[K - 1][i] = matrix[L - 1][i];
     matrix[L - 1][i] = temp;
   }
   // Print matrix
   for(int g = 0; g < matrix.length; g++){
      for(int b = 0; b < matrix[g].length; b++){
         System.out.print(matrix[g][b] + " ");
      }
      System.out.println();
   }
}

Body:
For this problem first, you need to create a copy of the array that represents the last row (lastRow).

After that, all values for each row (except the first row matrix[0]) have to be overwritten with values from the previous row.

Finally, assign the reference to the defensive copy of last row to the first row of the matrix.

public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };
        switchRows(matrix);
        printMatrix(matrix);
    }

    public static void switchRows(int[][] matrix){
        int[] lastRow = Arrays.copyOf(matrix[matrix.length - 1], matrix[matrix.length - 1].length);
        for (int row = matrix.length - 1; row > 0; row--) {
            // assign values of the previous row to current row
            for (int col = 0; col < matrix[row].length; col++) {
                matrix[row][col] = matrix[row - 1][col];
            }
        }
        matrix[0] = lastRow;
    }

    public static void printMatrix(int[][] matrix) {
        for (int row = 0; row < matrix.length; row++){
            for(int col = 0; col < matrix[row].length; col++){
                System.out.print(matrix[row][col] + " ");
            }
            System.out.println();
        }
    }

output

7 8 9
1 2 3
4 5 6


问:
Using a function to print an input one letter at a time
I am making a game/quiz in Python, but ran into a small issue. I made a function to print one letter at a time, but when I use that function for an input, it does not work and prints all at once. I've tried making a string for the input and multiple other things. To fix this temporarily, I have just been printing my question, and then using an input function to make an input, but I'm wondering if there is a better way. Here is my code:</p>
```<code>import time
import sys

def input1():
    input("")

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()
</code>```

答:
I figured out the answer. If anyone else is having this issue you should just do:</p>
```<code>input(oneprint(Blah Blah Blah Your Question Here))
</code>```

Body:
I am making a game/quiz in Python, but ran into a small issue. I made a function to print one letter at a time, but when I use that function for an input, it does not work and prints all at once. I've tried making a string for the input and multiple other things. To fix this temporarily, I have just been printing my question, and then using an input function to make an input, but I'm wondering if there is a better way. Here is my code:

import time
import sys

def input1():
    input("")

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()

Body:
I figured out the answer. If anyone else is having this issue you should just do:

input(oneprint(Blah Blah Blah Your Question Here))


问:
In PowerShell, how can I get the XML inner child to populate its parents and format it in a table?
So, I have the following XML file example:

    <root>
    <row>
        <row>
            <PName>Charles</PName>
            <Company>Contoso</Company>
            <ORDERDATE>2022-01-25</ORDERDATE>
            <STREET1>FakeStreet 123</STREET1>
            <City>San Francisco</City>
            <row>
                <ORDERID>0010286731129</ORDERID>
                <row>
                    <ProjectName>Sacramento Expansion</ProjectName>
                    <Name>ProductA</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Lemon</Color>
                </row>
            </row>
            <Other>OtherData</Other>
        </row>
        <row>
            <PName>Harvey</PName>
            <Company>Specter</Company>
            <ORDERDATE>2022-01-25</ORDERDATE>
            <STREET1>NotAFake 123</STREET1>
            <City>San Diego</City>
            <row>
                <ORDERID>0010286730526</ORDERID>
                <row>
                    <ProjectName>North Dakota Expansion</ProjectName>
                    <Name>ProductA</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Red</Color>
                </row>
                <row>
                    <ProjectName>North Dakota Expansion</ProjectName>
                    <Name>ProductB</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Blue</Color>
                </row>
            </row>
            <Other>OtherData</Other>
        </row>
    </row>
    </root>
```
<p>And I would like that Powershell outputs this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>PName</th>
<th>Company</th>
<th>ORDERDATE</th>
<th>STREET1</th>
<th>City</th>
<th>ProjectName</th>
<th>Name</th>
<th>Color</th>
<th>OtherData</th>
</tr>
</thead>
<tbody>
<tr>
<td>Charles</td>
<td>Contoso</td>
<td>2022-01-25</td>
<td>FakeStreet 123</td>
<td>San Francisco</td>
<td>Sacramento Expansion</td>
<td>ProductA</td>
<td>Lemon</td>
<td>OtherData</td>
</tr>
<tr>
<td>Harvey</td>
<td>Specter</td>
<td>2022-01-25</td>
<td>NotAFake 123</td>
<td>San Diego</td>
<td>North Dakota Expansion</td>
<td>ProductA</td>
<td>Red</td>
<td>OtherData</td>
</tr>
<tr>
<td>Harvey</td>
<td>Specter</td>
<td>2022-01-25</td>
<td>NotAFake 123</td>
<td>San Diego</td>
<td>North Dakota Expansion</td>
<td>ProductB</td>
<td>Blue</td>
<td>OtherData</td>
</tr>
</tbody>
</table>
</div>
<p>I've managed to do it with a horrible approach:</p>
```[xml]$data = Get-Content ./path/to/xml.xml
$RowsIwant = $data.root.row.row <#note the pipes for select object.#>
| Select-Object -ExpandProperty row -Property PName,Company,Orderdate,Street1,City,Other
| Select-Object -ExpandProperty row -Property PName,Company,Orderdate,Street1,City,Other
| Select-Object -Property PName,Company,OrderDate,Street1,City,ProjectName,Name,Color,OtherData

$RowsIwant | format-table
```

Is there a way to do this in a more elegant way? I feel like it's being super inefficient.
I tried with a "ForEach-Object" loop but I couldn't get it to access the "innermost" items.

Anyways, I do have a solution but I'd like to improve and get a better understanding on how to deal with the inner items, if you want to throw me a "read about this algorithm!" would be also welcome.

Thanks!

答:
For completion, here's Santiago's approach, but with an PSCustomObject that allows me to rename the columns to whatever I need (I do need it to export to a CSV file), and I think it's also more readable:

```<code>[xml]$xml = get-content ./file.xml
$result = foreach($line in $xml.root.row.row)
{
    foreach($object in $line.row.row)
    {
        [PSCustomObject]@{
            'Name'          = $line.PName
            'Company'       = $line.Company
            'Date'          = $line.OrderDate
            'Street'        = $line.STREET1
            'City'          = $line.City
            'Product Name'  = $object.Name
            'Product Color' = $object.Color
            'Other'         = $line.OtherData
        }
    }
}
</code>```

Although I liked the select object expanded properties, I didn't understand what it was reading the documentation, I had it right there!

Body:
So, I have the following XML file example:

    <root>
    <row>
        <row>
            <PName>Charles</PName>
            <Company>Contoso</Company>
            <ORDERDATE>2022-01-25</ORDERDATE>
            <STREET1>FakeStreet 123</STREET1>
            <City>San Francisco</City>
            <row>
                <ORDERID>0010286731129</ORDERID>
                <row>
                    <ProjectName>Sacramento Expansion</ProjectName>
                    <Name>ProductA</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Lemon</Color>
                </row>
            </row>
            <Other>OtherData</Other>
        </row>
        <row>
            <PName>Harvey</PName>
            <Company>Specter</Company>
            <ORDERDATE>2022-01-25</ORDERDATE>
            <STREET1>NotAFake 123</STREET1>
            <City>San Diego</City>
            <row>
                <ORDERID>0010286730526</ORDERID>
                <row>
                    <ProjectName>North Dakota Expansion</ProjectName>
                    <Name>ProductA</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Red</Color>
                </row>
                <row>
                    <ProjectName>North Dakota Expansion</ProjectName>
                    <Name>ProductB</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Blue</Color>
                </row>
            </row>
            <Other>OtherData</Other>
        </row>
    </row>
    </root>

And I would like that Powershell outputs this:

PName
Company
ORDERDATE
STREET1
City
ProjectName
Name
Color
OtherData

Charles
Contoso
2022-01-25
FakeStreet 123
San Francisco
Sacramento Expansion
ProductA
Lemon
OtherData

Harvey
Specter
2022-01-25
NotAFake 123
San Diego
North Dakota Expansion
ProductA
Red
OtherData

Harvey
Specter
2022-01-25
NotAFake 123
San Diego
North Dakota Expansion
ProductB
Blue
OtherData

I've managed to do it with a horrible approach:

[xml]$data = Get-Content ./path/to/xml.xml
$RowsIwant = $data.root.row.row <#note the pipes for select object.#>
| Select-Object -ExpandProperty row -Property PName,Company,Orderdate,Street1,City,Other
| Select-Object -ExpandProperty row -Property PName,Company,Orderdate,Street1,City,Other
| Select-Object -Property PName,Company,OrderDate,Street1,City,ProjectName,Name,Color,OtherData

$RowsIwant | format-table

Is there a way to do this in a more elegant way? I feel like it's being super inefficient.
I tried with a "ForEach-Object" loop but I couldn't get it to access the "innermost" items.

Anyways, I do have a solution but I'd like to improve and get a better understanding on how to deal with the inner items, if you want to throw me a "read about this algorithm!" would be also welcome.

Thanks!

Body:
For completion, here's Santiago's approach, but with an PSCustomObject that allows me to rename the columns to whatever I need (I do need it to export to a CSV file), and I think it's also more readable:

[xml]$xml = get-content ./file.xml
$result = foreach($line in $xml.root.row.row)
{
    foreach($object in $line.row.row)
    {
        [PSCustomObject]@{
            'Name'          = $line.PName
            'Company'       = $line.Company
            'Date'          = $line.OrderDate
            'Street'        = $line.STREET1
            'City'          = $line.City
            'Product Name'  = $object.Name
            'Product Color' = $object.Color
            'Other'         = $line.OtherData
        }
    }
}

Although I liked the select object expanded properties, I didn't understand what it was reading the documentation, I had it right there!


问:
Alert is taking wrong values inside LazyVGrid SwiftUI
Alert should remove objects from a model, but when Alert is apearing, values are not the same as a value inside tap and longPress Gesture. Any idea why?</p>
```<code>LazyVGrid(columns: columns, spacing: 5) {
            ForEach(model.robotsRepository.robots) { robot in
                RobotView(model: RobotView.Model(robotsRepository: model.robotsRepository, robot: robot)).environmentObject(team)
                    .contentShape(Rectangle())
                    .alert(isPresented: $showAlert) {
                        //When Alert is apearing, "robot" value are not the same as a value inside tap and longPress Gesture
                        Alert(
                            title: Text("Remove Card"),
                            message: Text("Are you sure you want to remove this card?"),
                            primaryButton: .destructive(Text("Remove")) {
                                withAnimation {
                                    model.remove(robot: robot)
                                }
                            },
                            secondaryButton: .cancel() {
                                withAnimation {
                                    deleting = false
                                }
                            }
                        )
                    }
                    .onTapGesture {
                        addRobot(robot: robot, at: selectedIndex)
                    }
                    .onLongPressGesture {
                        withAnimation {
                            showAlert = true
                            deleting = true
                        }
                    }
            }
        }
</code>```

答:
you could try moving the .alert(isPresented: $showAlert) {...} out of the ForEach, and probably out of
the LazyVGrid as well. Something like this, for example (untested):

```<code>@State var selectedRobot = Robot.default  // <--- here adjust accordingly

LazyVGrid(columns: columns, spacing: 5) {
            ForEach(model.robotsRepository.robots) { robot in
                RobotView(model: RobotView.Model(robotsRepository: model.robotsRepository, robot: robot)).environmentObject(team)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        addRobot(robot: robot, at: selectedIndex)
                    }
                    .onLongPressGesture {
                        withAnimation {
                            selectedRobot = robot  // <-- here
                            showAlert = true
                            deleting = true
                        }
                    }
            }
        }
        .alert(isPresented: $showAlert) {
            Alert(
                title: Text("Remove Card"),
                message: Text("Are you sure you want to remove this card?"),
                primaryButton: .destructive(Text("Remove")) {
                    withAnimation {
                        model.remove(robot: selectedRobot) // <-- here
                    }
                },
                secondaryButton: .cancel() {
                    withAnimation {
                        deleting = false
                    }
                }
            )
        }

</code>```

EDIT-1:  Note that alert(isPresented:content:)  and alert(item:content:) are deprecated (iOS 13.0–15.4 ).

If you are using (ios15+) you can use the following approach
(as per the Apple example: https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:)-8584l)

```<code>// for demonstration
struct Robot: Identifiable {
    let id = UUID()
    let name: String = "no name"
}

.....

@State var selectedRobot: Robot?  // <--- here

 .....

        LazyVGrid(columns: columns, spacing: 5) {
            ForEach(model.robotsRepository.robots) { robot in
                RobotView(model: RobotView.Model(robotsRepository: model.robotsRepository, robot: robot)).environmentObject(team)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        addRobot(robot: robot, at: selectedIndex)
                    }
                    .onLongPressGesture {
                        withAnimation {
                            selectedRobot = robot  // <-- here
                            showAlert = true
                            deleting = true
                        }
                    }
            }
        }
        .alert("Remove Card", isPresented: $showAlert, presenting: selectedRobot) { robot in
            Button(role: .destructive) {
                withAnimation {
                    model.remove(robot: robot)
                }
            } label: { Text("Remove") }

            Button(role: .cancel) {
                withAnimation {
                    deleting = false
                }
            } label: { Text("Cancel") }

        } message: { _ in
            Text("Are you sure you want to remove this card?")
        }

</code>```

Body:
Alert should remove objects from a model, but when Alert is apearing, values are not the same as a value inside tap and longPress Gesture. Any idea why?

LazyVGrid(columns: columns, spacing: 5) {
            ForEach(model.robotsRepository.robots) { robot in
                RobotView(model: RobotView.Model(robotsRepository: model.robotsRepository, robot: robot)).environmentObject(team)
                    .contentShape(Rectangle())
                    .alert(isPresented: $showAlert) {
                        //When Alert is apearing, "robot" value are not the same as a value inside tap and longPress Gesture
                        Alert(
                            title: Text("Remove Card"),
                            message: Text("Are you sure you want to remove this card?"),
                            primaryButton: .destructive(Text("Remove")) {
                                withAnimation {
                                    model.remove(robot: robot)
                                }
                            },
                            secondaryButton: .cancel() {
                                withAnimation {
                                    deleting = false
                                }
                            }
                        )
                    }
                    .onTapGesture {
                        addRobot(robot: robot, at: selectedIndex)
                    }
                    .onLongPressGesture {
                        withAnimation {
                            showAlert = true
                            deleting = true
                        }
                    }
            }
        }

Body:
you could try moving the .alert(isPresented: $showAlert) {...} out of the ForEach, and probably out of
the LazyVGrid as well. Something like this, for example (untested):

@State var selectedRobot = Robot.default  // <--- here adjust accordingly

LazyVGrid(columns: columns, spacing: 5) {
            ForEach(model.robotsRepository.robots) { robot in
                RobotView(model: RobotView.Model(robotsRepository: model.robotsRepository, robot: robot)).environmentObject(team)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        addRobot(robot: robot, at: selectedIndex)
                    }
                    .onLongPressGesture {
                        withAnimation {
                            selectedRobot = robot  // <-- here
                            showAlert = true
                            deleting = true
                        }
                    }
            }
        }
        .alert(isPresented: $showAlert) {
            Alert(
                title: Text("Remove Card"),
                message: Text("Are you sure you want to remove this card?"),
                primaryButton: .destructive(Text("Remove")) {
                    withAnimation {
                        model.remove(robot: selectedRobot) // <-- here
                    }
                },
                secondaryButton: .cancel() {
                    withAnimation {
                        deleting = false
                    }
                }
            )
        }

EDIT-1:  Note that alert(isPresented:content:)  and alert(item:content:) are deprecated (iOS 13.0–15.4 ).

If you are using (ios15+) you can use the following approach
(as per the Apple example: https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:)-8584l)

// for demonstration
struct Robot: Identifiable {
    let id = UUID()
    let name: String = "no name"
}

.....

@State var selectedRobot: Robot?  // <--- here

 .....

        LazyVGrid(columns: columns, spacing: 5) {
            ForEach(model.robotsRepository.robots) { robot in
                RobotView(model: RobotView.Model(robotsRepository: model.robotsRepository, robot: robot)).environmentObject(team)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        addRobot(robot: robot, at: selectedIndex)
                    }
                    .onLongPressGesture {
                        withAnimation {
                            selectedRobot = robot  // <-- here
                            showAlert = true
                            deleting = true
                        }
                    }
            }
        }
        .alert("Remove Card", isPresented: $showAlert, presenting: selectedRobot) { robot in
            Button(role: .destructive) {
                withAnimation {
                    model.remove(robot: robot)
                }
            } label: { Text("Remove") }

            Button(role: .cancel) {
                withAnimation {
                    deleting = false
                }
            } label: { Text("Cancel") }

        } message: { _ in
            Text("Are you sure you want to remove this card?")
        }


问:
What is meant by including "-p" as a "non-option argument" in the git stash push documentation?
The git stash push documentation states:

For quickly making a snapshot, you can omit "push". In this mode, non-option arguments are not allowed to prevent a misspelled subcommand from making an unwanted stash entry. The two exceptions to this are stash -p which acts as alias for stash push -p and pathspec elements, which are allowed after a double hyphen -- for disambiguation.

However, I'm confused by the stash -p example being listed as an exception to the non-option arguments.  Isn't -p an option argument?

For instance, the following also appears to be a valid use of omitting "push", and it creates a stash with the given message:

git stash -m "some commit message"
```

Am I misunderstanding something here?  Is this an issue with the documentation?

What is meant by including stash -p as an exception to disallowing the non-option arguments, when it appears to be an option argument.?

答:
A nonoption argument is, say, a filename.

Suppose you have an edited file called clea. Then it is forbidden to say

```<code>git stash clea
</code>```

because, as the documentation says, we can't tell if clea is a misspelling for some subcommand such as clear. It would have been legal to say

```<code>git stash push clea
</code>```

but Git is not about to assume you mean that.

But if you say

```<code>git stash -p -- clea
</code>```

that's fine; you have disambiguated sufficiently, so it is just as if you had said

```<code>git stash push -p clea
</code>```

and the success of the command depends merely on whether you do in fact have a file called clea.

Body:
The git stash push documentation states:

For quickly making a snapshot, you can omit "push". In this mode, non-option arguments are not allowed to prevent a misspelled subcommand from making an unwanted stash entry. The two exceptions to this are stash -p which acts as alias for stash push -p and pathspec elements, which are allowed after a double hyphen -- for disambiguation.

However, I'm confused by the stash -p example being listed as an exception to the non-option arguments.  Isn't -p an option argument?

For instance, the following also appears to be a valid use of omitting "push", and it creates a stash with the given message:

git stash -m "some commit message"

Am I misunderstanding something here?  Is this an issue with the documentation?

What is meant by including stash -p as an exception to disallowing the non-option arguments, when it appears to be an option argument.?

Body:
A nonoption argument is, say, a filename.

Suppose you have an edited file called clea. Then it is forbidden to say

git stash clea

because, as the documentation says, we can't tell if clea is a misspelling for some subcommand such as clear. It would have been legal to say

git stash push clea

but Git is not about to assume you mean that.

But if you say

git stash -p -- clea

that's fine; you have disambiguated sufficiently, so it is just as if you had said

git stash push -p clea

and the success of the command depends merely on whether you do in fact have a file called clea.


问:
rabbitmq docker wss not working even though https works
Update
I initially started the docker container using this command:

sudo docker run -d -it --hostname some-rabbitmq --name rabbitmq -p 5672:5672 -p 15672:15672 -p 15674:15674 --restart=unless-stopped -v /opt/rabbitmq-test:/etc/rabbitmq/ rabbitmq:3.9-management
```
<p>However I needed to add tls without losing the info that was already saved on it, so I added more ports by stopping the docker container and service, updating the <code>config.v2.json</code> and <code>hostconfig.json</code> files to add the ports I wanted to expose, including <code>15673</code>.</p>
<hr />
<p>I'm using the official rabbitmq docker image as my rabbitmq server. I've configured tls but for some reason the <code>wss://</code> connection fails completely. This is my rabbitmq.conf file</p>
```loopback_users.guest = false
management.cors.allow_origins.1 = *
management.tcp.port = 80

# ===========================================================================
# ====================== TLS for webstomp plugin ============================
# ===========================================================================

# source of tls settings for webstomp plugin: https://www.rabbitmq.com/web-stomp.html#tls-versions
web_stomp.ssl.port       = 15673
web_stomp.ssl.backlog    = 1024
web_stomp.ssl.cacertfile = /etc/letsencrypt/live/{example.com}/chain.pem
web_stomp.ssl.certfile   = /etc/letsencrypt/live/{example.com}/cert.pem
web_stomp.ssl.keyfile    = /etc/letsencrypt/live/{example.com}/privkey.pem
# web_stomp.ssl.password   = changeme

web_stomp.ssl.honor_cipher_order   = true
web_stomp.ssl.honor_ecc_order      = true
web_stomp.ssl.client_renegotiation = false
web_stomp.ssl.secure_renegotiate   = true

web_stomp.ssl.versions.1 = tlsv1.2
web_stomp.ssl.versions.2 = tlsv1.1
web_stomp.ssl.ciphers.1 = ECDHE-ECDSA-AES256-GCM-SHA384
web_stomp.ssl.ciphers.2 = ECDHE-RSA-AES256-GCM-SHA384
web_stomp.ssl.ciphers.3 = ECDHE-ECDSA-AES256-SHA384
web_stomp.ssl.ciphers.4 = ECDHE-RSA-AES256-SHA384
web_stomp.ssl.ciphers.5 = ECDH-ECDSA-AES256-GCM-SHA384
web_stomp.ssl.ciphers.6 = ECDH-RSA-AES256-GCM-SHA384
web_stomp.ssl.ciphers.7 = ECDH-ECDSA-AES256-SHA384
web_stomp.ssl.ciphers.8 = ECDH-RSA-AES256-SHA384
web_stomp.ssl.ciphers.9 = DHE-RSA-AES256-GCM-SHA384

# ==========================================================================
# ====================== TLS for manangement ui ============================
# ==========================================================================

# source of tls settings for management ui: https://www.rabbitmq.com/management.html#single-listener-https
management.ssl.port = 443
# management.ssl.cacertfile = /opt/rabbitmq-test/tls-ca/letsencrypt.pem
management.ssl.cacertfile = /etc/letsencrypt/live/{example.com}/chain.pem
management.ssl.certfile   = /etc/letsencrypt/live/{example.com}/cert.pem
management.ssl.keyfile    = /etc/letsencrypt/live/{example.com}/privkey.pem
## This key must only be used if private key is password protected
# management.ssl.password   = bunnies

# For RabbitMQ 3.7.10 and later versions
management.ssl.honor_cipher_order   = true
management.ssl.honor_ecc_order      = true
management.ssl.client_renegotiation = false
management.ssl.secure_renegotiate   = true

management.ssl.versions.1 = tlsv1.2
management.ssl.versions.2 = tlsv1.1

management.ssl.ciphers.1 = ECDHE-ECDSA-AES256-GCM-SHA384
management.ssl.ciphers.2 = ECDHE-RSA-AES256-GCM-SHA384
management.ssl.ciphers.3 = ECDHE-ECDSA-AES256-SHA384
management.ssl.ciphers.4 = ECDHE-RSA-AES256-SHA384
management.ssl.ciphers.5 = ECDH-ECDSA-AES256-GCM-SHA384
management.ssl.ciphers.6 = ECDH-RSA-AES256-GCM-SHA384
management.ssl.ciphers.7 = ECDH-ECDSA-AES256-SHA384
management.ssl.ciphers.8 = ECDH-RSA-AES256-SHA384
management.ssl.ciphers.9 = DHE-RSA-AES256-GCM-SHA384
## Usually RabbitMQ nodes do not perform peer verification of HTTP API clients
## but it can be enabled if needed. Clients then will have to be configured with
## a certificate and private key pair.
##
## See https://www.rabbitmq.com/ssl.html#peer-verification for details.
# management.ssl.verify = verify_peer
# management.ssl.fail_if_no_peer_cert = true

# ==========================================================================
# ========================= TLS for core server ============================
# ==========================================================================

# source of tls settings: https://www.rabbitmq.com/ssl.html#testssl-sh
listeners.ssl.default  = 5671
# ssl_options.cacertfile = /opt/rabbitmq-test/tls-ca/letsencrypt.pem
ssl_options.cacertfile = /etc/letsencrypt/live/{example.com}/chain.pem
ssl_options.certfile   = /etc/letsencrypt/live/{example.com}/cert.pem
ssl_options.keyfile    = /etc/letsencrypt/live/{example.com}/privkey.pem
ssl_options.versions.1 = tlsv1.2
ssl_options.verify               = verify_peer
ssl_options.fail_if_no_peer_cert = false

ssl_options.honor_cipher_order   = true
ssl_options.honor_ecc_order      = true

# These are highly recommended for TLSv1.2 but cannot be used
# with TLSv1.3. If TLSv1.3 is enabled, these lines MUST be removed.
ssl_options.client_renegotiation = false
ssl_options.secure_renegotiate   = true

ssl_options.ciphers.1  = ECDHE-ECDSA-AES256-GCM-SHA384
ssl_options.ciphers.2  = ECDHE-RSA-AES256-GCM-SHA384
ssl_options.ciphers.3  = ECDH-ECDSA-AES256-GCM-SHA384
ssl_options.ciphers.4  = ECDH-RSA-AES256-GCM-SHA384
ssl_options.ciphers.5  = DHE-RSA-AES256-GCM-SHA384
ssl_options.ciphers.6  = DHE-DSS-AES256-GCM-SHA384
ssl_options.ciphers.7  = ECDHE-ECDSA-AES128-GCM-SHA256
ssl_options.ciphers.8  = ECDHE-RSA-AES128-GCM-SHA256
ssl_options.ciphers.9  = ECDH-ECDSA-AES128-GCM-SHA256
ssl_options.ciphers.10 = ECDH-RSA-AES128-GCM-SHA256
ssl_options.ciphers.11 = DHE-RSA-AES128-GCM-SHA256
ssl_options.ciphers.12 = DHE-DSS-AES128-GCM-SHA256
```
<p>If you didn't read all that, the web_stomp plugin is configured to accept <code>wss://</code> connections on port <code>15673</code>, and regular <code>ws://</code> on <code>15674</code>. Note that I'm not using <code>amqp</code> and therefore <code>amqps</code> is not configured.</p>
<p>With this configuration I'm able to connect to <code>ws://example.com:15674/ws</code> using a webstomp javascript library using this code:</p>
<pre class="lang-js prettyprint-override"><code>    const stompClient = new StompJs.Client({
        brokerURL: url,
        connectHeaders: {
            login: userId,
            passcode: password,
        },
        reconnectDelay: 20000,
        heartbeatIncoming: 10000,
        heartbeatOutgoing: 10000,
      });
    // ... set my onConnect and onError listeners
     stompClient.activate();
</code>```

I'm also able to access both http://example.com and https://example.com from the browser. But strangely I
cannot access wss://example.com:15673/ws using the same javascript code above.

When I run sudo docker logs rabbitmq (rabbitmq is the name of the running container), I see entries like this:

```<code>2022-02-08 16:06:45.314017+00:00 [info] <0.11704.33> accepting AMQP connection <0.11704.33> (162.142.125.221:54938 -> 172.17.0.2:5672)
2022-02-08 16:06:45.314245+00:00 [erro] <0.11704.33> closing AMQP connection <0.11704.33> (162.142.125.221:54938 -> 172.17.0.2:5672):
2022-02-08 16:06:45.314245+00:00 [erro] <0.11704.33> amqp1_0_plugin_not_enabled
2022-02-08 16:40:01.274168+00:00 [noti] <0.12580.33> TLS server: In state hello at tls_handshake.erl:346 generated SERVER ALERT: Fatal - Insufficient Security
2022-02-08 16:40:01.274168+00:00 [noti] <0.12580.33>  - no_suitable_ciphers
2022-02-08 16:40:02.790021+00:00 [noti] <0.12597.33> TLS server: In state hello at tls_handshake.erl:346 generated SERVER ALERT: Fatal - Insufficient Security
2022-02-08 16:40:02.790021+00:00 [noti] <0.12597.33>  - no_suitable_ciphers
2022-02-08 16:40:03.423216+00:00 [noti] <0.12604.33> TLS server: In state hello at tls_handshake.erl:346 generated SERVER ALERT: Fatal - Insufficient Security
2022-02-08 16:40:03.423216+00:00 [noti] <0.12604.33>  - no_suitable_ciphers
2022-02-08 16:40:06.467195+00:00 [noti] <0.12610.33> TLS server: In state hello at tls_handshake.erl:346 generated SERVER ALERT: Fatal - Insufficient Security
2022-02-08 16:40:06.467195+00:00 [noti] <0.12610.33>  - no_suitable_ciphers
2022-02-08 18:12:36.615274+00:00 [noti] <0.16116.33> TLS server: In state hello at tls_record.erl:564 generated SERVER ALERT: Fatal - Unexpected Message
2022-02-08 18:12:36.615274+00:00 [noti] <0.16116.33>  - {unsupported_record_type,65}
2022-02-08 18:28:00.774093+00:00 [noti] <0.16535.33> TLS server: In state hello at tls_record.erl:564 generated SERVER ALERT: Fatal - Unexpected Message
2022-02-08 18:28:00.774093+00:00 [noti] <0.16535.33>  - {unsupported_record_type,71}
</code>```

None of these entries correspond to my actual attempts to connect. I don't know which connections are triggering these logs because my actual connection attempts do not show up in the logs.

RabbitMQ's website has a page for troubleshooting ssl, but when I go into the docker container (using docker exec -it rabbitmq bash) and try to use the rabbit-diagnostics command, I get:

```<code>Error: unable to perform an operation on node 'rabbit@name-rabbitmq-test.localdomain'. Please see diagnostics information and suggestions below.
</code>```

I've also tried using the openssl s_client command mentioned in the troubleshooting page, but what I get is Error: verify error:num=2:unable to get issuer certificate. I've tried using both chain.pem and fullchain.pem (the CA files provided by letsencrypt) without any luck, it's the same error.

I'm not a rabbitmq expert so I'm not really sure how to proceed. I tried to include additional info about what I've tried, but please remember that the main problem is that I cannot connect using wss:// even though I can connect with ws:// and https://. Any ideas as to why this happening or what can help me resolve the problem? Thanks.

答: Many thanks to @jhmckimm for the idea. The problem was that port 15673 from the docker container was not exposed by the host. To fix this I had to add that port to the ExposedPorts in the /var/lib/docker/containers/[hash_of_the_container]/config.v2.json file of the docker system. See here for more information.

Body:
Update
I initially started the docker container using this command:

sudo docker run -d -it --hostname some-rabbitmq --name rabbitmq -p 5672:5672 -p 15672:15672 -p 15674:15674 --restart=unless-stopped -v /opt/rabbitmq-test:/etc/rabbitmq/ rabbitmq:3.9-management

However I needed to add tls without losing the info that was already saved on it, so I added more ports by stopping the docker container and service, updating the config.v2.json and hostconfig.json files to add the ports I wanted to expose, including 15673.

I'm using the official rabbitmq docker image as my rabbitmq server. I've configured tls but for some reason the wss:// connection fails completely. This is my rabbitmq.conf file

loopback_users.guest = false
management.cors.allow_origins.1 = *
management.tcp.port = 80

# ===========================================================================
# ====================== TLS for webstomp plugin ============================
# ===========================================================================

# source of tls settings for webstomp plugin: https://www.rabbitmq.com/web-stomp.html#tls-versions
web_stomp.ssl.port       = 15673
web_stomp.ssl.backlog    = 1024
web_stomp.ssl.cacertfile = /etc/letsencrypt/live/{example.com}/chain.pem
web_stomp.ssl.certfile   = /etc/letsencrypt/live/{example.com}/cert.pem
web_stomp.ssl.keyfile    = /etc/letsencrypt/live/{example.com}/privkey.pem
# web_stomp.ssl.password   = changeme

web_stomp.ssl.honor_cipher_order   = true
web_stomp.ssl.honor_ecc_order      = true
web_stomp.ssl.client_renegotiation = false
web_stomp.ssl.secure_renegotiate   = true

web_stomp.ssl.versions.1 = tlsv1.2
web_stomp.ssl.versions.2 = tlsv1.1
web_stomp.ssl.ciphers.1 = ECDHE-ECDSA-AES256-GCM-SHA384
web_stomp.ssl.ciphers.2 = ECDHE-RSA-AES256-GCM-SHA384
web_stomp.ssl.ciphers.3 = ECDHE-ECDSA-AES256-SHA384
web_stomp.ssl.ciphers.4 = ECDHE-RSA-AES256-SHA384
web_stomp.ssl.ciphers.5 = ECDH-ECDSA-AES256-GCM-SHA384
web_stomp.ssl.ciphers.6 = ECDH-RSA-AES256-GCM-SHA384
web_stomp.ssl.ciphers.7 = ECDH-ECDSA-AES256-SHA384
web_stomp.ssl.ciphers.8 = ECDH-RSA-AES256-SHA384
web_stomp.ssl.ciphers.9 = DHE-RSA-AES256-GCM-SHA384

# ==========================================================================
# ====================== TLS for manangement ui ============================
# ==========================================================================

# source of tls settings for management ui: https://www.rabbitmq.com/management.html#single-listener-https
management.ssl.port = 443
# management.ssl.cacertfile = /opt/rabbitmq-test/tls-ca/letsencrypt.pem
management.ssl.cacertfile = /etc/letsencrypt/live/{example.com}/chain.pem
management.ssl.certfile   = /etc/letsencrypt/live/{example.com}/cert.pem
management.ssl.keyfile    = /etc/letsencrypt/live/{example.com}/privkey.pem
## This key must only be used if private key is password protected
# management.ssl.password   = bunnies

# For RabbitMQ 3.7.10 and later versions
management.ssl.honor_cipher_order   = true
management.ssl.honor_ecc_order      = true
management.ssl.client_renegotiation = false
management.ssl.secure_renegotiate   = true

management.ssl.versions.1 = tlsv1.2
management.ssl.versions.2 = tlsv1.1

management.ssl.ciphers.1 = ECDHE-ECDSA-AES256-GCM-SHA384
management.ssl.ciphers.2 = ECDHE-RSA-AES256-GCM-SHA384
management.ssl.ciphers.3 = ECDHE-ECDSA-AES256-SHA384
management.ssl.ciphers.4 = ECDHE-RSA-AES256-SHA384
management.ssl.ciphers.5 = ECDH-ECDSA-AES256-GCM-SHA384
management.ssl.ciphers.6 = ECDH-RSA-AES256-GCM-SHA384
management.ssl.ciphers.7 = ECDH-ECDSA-AES256-SHA384
management.ssl.ciphers.8 = ECDH-RSA-AES256-SHA384
management.ssl.ciphers.9 = DHE-RSA-AES256-GCM-SHA384
## Usually RabbitMQ nodes do not perform peer verification of HTTP API clients
## but it can be enabled if needed. Clients then will have to be configured with
## a certificate and private key pair.
##
## See https://www.rabbitmq.com/ssl.html#peer-verification for details.
# management.ssl.verify = verify_peer
# management.ssl.fail_if_no_peer_cert = true

# ==========================================================================
# ========================= TLS for core server ============================
# ==========================================================================

# source of tls settings: https://www.rabbitmq.com/ssl.html#testssl-sh
listeners.ssl.default  = 5671
# ssl_options.cacertfile = /opt/rabbitmq-test/tls-ca/letsencrypt.pem
ssl_options.cacertfile = /etc/letsencrypt/live/{example.com}/chain.pem
ssl_options.certfile   = /etc/letsencrypt/live/{example.com}/cert.pem
ssl_options.keyfile    = /etc/letsencrypt/live/{example.com}/privkey.pem
ssl_options.versions.1 = tlsv1.2
ssl_options.verify               = verify_peer
ssl_options.fail_if_no_peer_cert = false

ssl_options.honor_cipher_order   = true
ssl_options.honor_ecc_order      = true

# These are highly recommended for TLSv1.2 but cannot be used
# with TLSv1.3. If TLSv1.3 is enabled, these lines MUST be removed.
ssl_options.client_renegotiation = false
ssl_options.secure_renegotiate   = true

ssl_options.ciphers.1  = ECDHE-ECDSA-AES256-GCM-SHA384
ssl_options.ciphers.2  = ECDHE-RSA-AES256-GCM-SHA384
ssl_options.ciphers.3  = ECDH-ECDSA-AES256-GCM-SHA384
ssl_options.ciphers.4  = ECDH-RSA-AES256-GCM-SHA384
ssl_options.ciphers.5  = DHE-RSA-AES256-GCM-SHA384
ssl_options.ciphers.6  = DHE-DSS-AES256-GCM-SHA384
ssl_options.ciphers.7  = ECDHE-ECDSA-AES128-GCM-SHA256
ssl_options.ciphers.8  = ECDHE-RSA-AES128-GCM-SHA256
ssl_options.ciphers.9  = ECDH-ECDSA-AES128-GCM-SHA256
ssl_options.ciphers.10 = ECDH-RSA-AES128-GCM-SHA256
ssl_options.ciphers.11 = DHE-RSA-AES128-GCM-SHA256
ssl_options.ciphers.12 = DHE-DSS-AES128-GCM-SHA256

If you didn't read all that, the web_stomp plugin is configured to accept wss:// connections on port 15673, and regular ws:// on 15674. Note that I'm not using amqp and therefore amqps is not configured.

With this configuration I'm able to connect to ws://example.com:15674/ws using a webstomp javascript library using this code:

    const stompClient = new StompJs.Client({
        brokerURL: url,
        connectHeaders: {
            login: userId,
            passcode: password,
        },
        reconnectDelay: 20000,
        heartbeatIncoming: 10000,
        heartbeatOutgoing: 10000,
      });
    // ... set my onConnect and onError listeners
     stompClient.activate();

I'm also able to access both http://example.com and https://example.com from the browser. But strangely I
cannot access wss://example.com:15673/ws using the same javascript code above.

When I run sudo docker logs rabbitmq (rabbitmq is the name of the running container), I see entries like this:

2022-02-08 16:06:45.314017+00:00 [info] <0.11704.33> accepting AMQP connection <0.11704.33> (162.142.125.221:54938 -> 172.17.0.2:5672)
2022-02-08 16:06:45.314245+00:00 [erro] <0.11704.33> closing AMQP connection <0.11704.33> (162.142.125.221:54938 -> 172.17.0.2:5672):
2022-02-08 16:06:45.314245+00:00 [erro] <0.11704.33> amqp1_0_plugin_not_enabled
2022-02-08 16:40:01.274168+00:00 [noti] <0.12580.33> TLS server: In state hello at tls_handshake.erl:346 generated SERVER ALERT: Fatal - Insufficient Security
2022-02-08 16:40:01.274168+00:00 [noti] <0.12580.33>  - no_suitable_ciphers
2022-02-08 16:40:02.790021+00:00 [noti] <0.12597.33> TLS server: In state hello at tls_handshake.erl:346 generated SERVER ALERT: Fatal - Insufficient Security
2022-02-08 16:40:02.790021+00:00 [noti] <0.12597.33>  - no_suitable_ciphers
2022-02-08 16:40:03.423216+00:00 [noti] <0.12604.33> TLS server: In state hello at tls_handshake.erl:346 generated SERVER ALERT: Fatal - Insufficient Security
2022-02-08 16:40:03.423216+00:00 [noti] <0.12604.33>  - no_suitable_ciphers
2022-02-08 16:40:06.467195+00:00 [noti] <0.12610.33> TLS server: In state hello at tls_handshake.erl:346 generated SERVER ALERT: Fatal - Insufficient Security
2022-02-08 16:40:06.467195+00:00 [noti] <0.12610.33>  - no_suitable_ciphers
2022-02-08 18:12:36.615274+00:00 [noti] <0.16116.33> TLS server: In state hello at tls_record.erl:564 generated SERVER ALERT: Fatal - Unexpected Message
2022-02-08 18:12:36.615274+00:00 [noti] <0.16116.33>  - {unsupported_record_type,65}
2022-02-08 18:28:00.774093+00:00 [noti] <0.16535.33> TLS server: In state hello at tls_record.erl:564 generated SERVER ALERT: Fatal - Unexpected Message
2022-02-08 18:28:00.774093+00:00 [noti] <0.16535.33>  - {unsupported_record_type,71}

None of these entries correspond to my actual attempts to connect. I don't know which connections are triggering these logs because my actual connection attempts do not show up in the logs.

RabbitMQ's website has a page for troubleshooting ssl, but when I go into the docker container (using docker exec -it rabbitmq bash) and try to use the rabbit-diagnostics command, I get:

Error: unable to perform an operation on node 'rabbit@name-rabbitmq-test.localdomain'. Please see diagnostics information and suggestions below.

I've also tried using the openssl s_client command mentioned in the troubleshooting page, but what I get is Error: verify error:num=2:unable to get issuer certificate. I've tried using both chain.pem and fullchain.pem (the CA files provided by letsencrypt) without any luck, it's the same error.

I'm not a rabbitmq expert so I'm not really sure how to proceed. I tried to include additional info about what I've tried, but please remember that the main problem is that I cannot connect using wss:// even though I can connect with ws:// and https://. Any ideas as to why this happening or what can help me resolve the problem? Thanks.


问:
Using floor division and modulo together
How can I find the positive remainder of a floor division. I know I can carry out floor division with the // operator and I know I can find the remainder with % but how do I do this together
For example, the positive remainder of 12//5</p>

答:
The divmod() function returns (a//b, a%b) pair for input divmod(a, b)
So:

```<code>divmod(12, 5)
</code>```

Would output:

```<code>(2, 2)
</code>```

And this is right because 12 // 5 is 2 and 12 % 5 is also 2.

Body:
The divmod() function returns (a//b, a%b) pair for input divmod(a, b)
So:

divmod(12, 5)

Would output:

(2, 2)

And this is right because 12 // 5 is 2 and 12 % 5 is also 2.


问:
JQUERY Sorting an Array of Objects
I have an array that is holding a number of  objects.

Array:

```<code> var activeMembers=[];
</code>```

The DIV objects in the above array look like as follows - each was added one at a time:

```<code> <div id="mary" class="chatmember 1011"></div>
 <div id="steven" class="chatmember 1051"></div>
 <div id="adam" class="chatmember 1701"></div>
 <div id="bob" class="chatmember 1099"></div>
 <div id="peter" class="chatmember 1123"></div>
</code>```

Is there a quick way to sort theses DIV objects in the array by the ID from A-Z?

thx

答:
Since there are so many silly implementations being proposed that are using jQuery when it is only a waste of resources, I'll propose my own.  This is just a straight javascript sort of an array by a property of the object in the array.  To do that you just use the array sort method with a custom comparison function that does an alpha comparison of the id value.  There is no reason or advantage to involve jQuery in this at all.

```<code>activeMembers.sort(function(a, b) {
   var aID = a.id;
   var bID = b.id;
   return (aID == bID) ? 0 : (aID > bID) ? 1 : -1;
});
</code>```

Note, as requested in the question, this sorts a list of div references in the array.  It does not sort the objects in the layout of the page.  To do that, you'd have to sort the references list, then rearrange the divs in the page according to the new array order.

If you can rely on the fact that no two IDs are ever the same in your own HTML (since you are never supposed to have two objects with the same ID), you can shorten and speed up the custom sort function to just be this:

```<code>activeMembers.sort(function(a, b) {
   return (a.id > b.id) ? 1 : -1;
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: JQUERY Sorting an Array of Objects

Body:
I have an array that is holding a number of  objects.

Array:

 var activeMembers=[];

The DIV objects in the above array look like as follows - each was added one at a time:

Is there a quick way to sort theses DIV objects in the array by the ID from A-Z?

thx

Body:
Since there are so many silly implementations being proposed that are using jQuery when it is only a waste of resources, I'll propose my own.  This is just a straight javascript sort of an array by a property of the object in the array.  To do that you just use the array sort method with a custom comparison function that does an alpha comparison of the id value.  There is no reason or advantage to involve jQuery in this at all.

activeMembers.sort(function(a, b) {
   var aID = a.id;
   var bID = b.id;
   return (aID == bID) ? 0 : (aID > bID) ? 1 : -1;
});

Note, as requested in the question, this sorts a list of div references in the array.  It does not sort the objects in the layout of the page.  To do that, you'd have to sort the references list, then rearrange the divs in the page according to the new array order.

If you can rely on the fact that no two IDs are ever the same in your own HTML (since you are never supposed to have two objects with the same ID), you can shorten and speed up the custom sort function to just be this:

activeMembers.sort(function(a, b) {
   return (a.id > b.id) ? 1 : -1;
});


问:
localhost not working docker windows 10
I am using VS2017 docker support. VS created DockerFile for me and when I build docker-compose file, it creates the container and runs the app on 172.x.x.x IP address. But I want to run my application on localhost.

I did many things but nothing worked. Followed the docker docs as a starter and building microsoft sample app . The second link is working perfectly but I get HTTP Error 404 when tried the first link approach.

Any help is appreciated.

答: For those who encountering this issue in 2022, changing localhost to 127.0.0.1 solved an issue for me.

Title: localhost not working docker windows 10


问:
how can i get mobile status indicator in discord.py
So yea I code in python and I was wondering is it was posible to get mobile status indicator can someone help me please, thank you !</p>

答:
Edit function in \discord\gateway.py "identify"

'$browser': 'Discord Android'


问:
How to access the new variables value in same Ansible playbook
I'm learning the loop feature to set a dictionary variable from another variable in the same playbook like below:

vars:
- name: original var users contain multiple user's elements
  users:
    - name: alice
      authorized:
        - /tmp/alice/onekey.pub
        - /tmp/alice/twokey.pub
      mysql:
        password: "mysql-Alice's password"
        hosts:
          - "%"
          - "127.0.0.1"
          - "::1"
          - "localhost"
```
<p>Then in a task, I get the needed key/value from the variable above to set a new dictionary variable <code>mysql_user</code> like below:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: combine all elements data into one variable - MySQL users
  mysql_user: "name={{ item.0.user }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}"
  loop: "{{users|subelements('mysql.hosts')}}"
  #with_subelements:
  #  - users
  #  - mysql.hosts
</code>```

And you can see I tried the old with_subelements and new the loop construct, but both begets same error when the below task runs:

- name: display varible's value - combined varibles
  debug:
    msg: |
      "{{ mysql_user }}"
```

Error:

fatal: [s1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: name={{ item.0.user }} password={{ item.0.mysql.password }}

It obviously complains that the new varible mysql_user does not exist, so, my question actually is how to get the new variable or say it as a internal dictionary key/value in same playbook?

答:
I do not see you are setting the variable mysql_user. Maybe your code should have looked more like

```<code>- name: combine all elements data into one variable - MySQL users
  set_fact:
      mysql_user: "name={{ item.0.user }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}"
  loop: "{{users|subelements('mysql.hosts')}}"
</code>```

At least the last value should be retained.

But if you register the command output all the loop iterations' output is collected in a list - the registered variable will be a list with one entry for each loop invocation. Just make sure the necessary data is printed by the loop content.

```<code>- name: combine all elements data into one variable - MySQL users
  debug:
      msg: "name={{ item.0.user }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}"
  loop: "{{users|subelements('mysql.hosts')}}"
  register: mysql_user

- name: print the obtained values
  debug:
    var: mysql_user
</code>```

Body:
I'm learning the loop feature to set a dictionary variable from another variable in the same playbook like below:

vars:
- name: original var users contain multiple user's elements
  users:
    - name: alice
      authorized:
        - /tmp/alice/onekey.pub
        - /tmp/alice/twokey.pub
      mysql:
        password: "mysql-Alice's password"
        hosts:
          - "%"
          - "127.0.0.1"
          - "::1"
          - "localhost"

Then in a task, I get the needed key/value from the variable above to set a new dictionary variable mysql_user like below:

- name: combine all elements data into one variable - MySQL users
  mysql_user: "name={{ item.0.user }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}"
  loop: "{{users|subelements('mysql.hosts')}}"
  #with_subelements:
  #  - users
  #  - mysql.hosts

And you can see I tried the old with_subelements and new the loop construct, but both begets same error when the below task runs:

- name: display varible's value - combined varibles
  debug:
    msg: |
      "{{ mysql_user }}"

Error:

fatal: [s1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: name={{ item.0.user }} password={{ item.0.mysql.password }}

It obviously complains that the new varible mysql_user does not exist, so, my question actually is how to get the new variable or say it as a internal dictionary key/value in same playbook?

Body:
I do not see you are setting the variable mysql_user. Maybe your code should have looked more like

- name: combine all elements data into one variable - MySQL users
  set_fact:
      mysql_user: "name={{ item.0.user }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}"
  loop: "{{users|subelements('mysql.hosts')}}"

At least the last value should be retained.

But if you register the command output all the loop iterations' output is collected in a list - the registered variable will be a list with one entry for each loop invocation. Just make sure the necessary data is printed by the loop content.

- name: combine all elements data into one variable - MySQL users
  debug:
      msg: "name={{ item.0.user }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}"
  loop: "{{users|subelements('mysql.hosts')}}"
  register: mysql_user

- name: print the obtained values
  debug:
    var: mysql_user


问:
Pulling paragraphs from outlook emails and importing them into .txt or .doc
so the script I'm trying to write in Python would search for certain subjects such as "City status update" and "City issues" in my inbox and search for variables such as the city names. if the city names are in the email then it would pull that whole line of text to the period (.) and load it into a .txt file. Such as "Detroit: Cakes 15, Pies 12, Drinks 19." and not pull anything else. Below are two examples of the format for the emails along with what I have so far.

Subject: City status update

Detroit: Cakes 15, Pies 12, Drinks 19.
New York: Cakes 9, Pies 14, Drinks 2.

Subject: City issues

Detroit: 2 lost items, 2 unclaimed, 6 delivered.
Chicago: 5 lost items, 1 unclaimed, 9 delivered.

New York: 7 lost items, 3 unclaimed, 16 delivered.

```<code>import win32com.client
import os, re, html

outlook = win32com.client.Dispatch("OutlookApplication").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6)
messages.Sort("[ReceivedTime]", True)
messages = inbox.items
message = messages.GetFirst()

subject = message.Subject

city = input("What city/cities are you looking for?")

for message in messages:
  if message.Subject ["City status update, City issues"]
    name =str(message.subject)
    regex = re.search(r"city", msg.HTMLbody)
    body = regex.group()

OlSaveAsType = {
  "olTXT": 0,
  "olRTF": 1,
  "olTemplate": 2,
  "olMSG": 3,
  "olDoc": 4,
  "olHTML": 5,
  "olVCard": 6,
  "olVCal": 7,
  "olICal": 8
}

    message.SaveAs(os.getcwd()+'//'+name, OlSaveAsType(['olTXT])

    results = body

r = re.compile('.*/.*/.*:.*')
 if results, True
    print(results - ["."])

 else()
</code>```

This is what I have so far and a bunch of errors.

答:
First of all, there is no need to iterate over all items in a folder.

```<code>for message in messages:
  if message.Subject ["City status update, City issues"]
    name =str(message.subject)
    regex = re.search(r"city", msg.HTMLbody)
    body = regex.group()
</code>```

Instead, the Outlook object model provides the Find/FindNext or Restrict methods of the Items class. Read more about them in the following articles:

How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

How To: Use Restrict method to retrieve Outlook mail items from a folder

To deal with a message body I'd suggest using the Word object model. The WordEditor property of the Inspector class returns the Microsoft Word Document Object Model of the message being displayed.

The Outlook object model supports three main ways of customizing the message body:

The Body property returns or sets a string representing the clear-text body of the Outlook item.

The HTMLBody property of the MailItem class returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately.

The Word object model can be used for dealing with message bodies. See Chapter 17: Working with Item Bodies for more information.

Body:
so the script I'm trying to write in Python would search for certain subjects such as "City status update" and "City issues" in my inbox and search for variables such as the city names. if the city names are in the email then it would pull that whole line of text to the period (.) and load it into a .txt file. Such as "Detroit: Cakes 15, Pies 12, Drinks 19." and not pull anything else. Below are two examples of the format for the emails along with what I have so far.

Subject: City status update

Detroit: Cakes 15, Pies 12, Drinks 19.
New York: Cakes 9, Pies 14, Drinks 2.

Subject: City issues

Detroit: 2 lost items, 2 unclaimed, 6 delivered.
Chicago: 5 lost items, 1 unclaimed, 9 delivered.

New York: 7 lost items, 3 unclaimed, 16 delivered.

import win32com.client
import os, re, html

outlook = win32com.client.Dispatch("OutlookApplication").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6)
messages.Sort("[ReceivedTime]", True)
messages = inbox.items
message = messages.GetFirst()

subject = message.Subject

city = input("What city/cities are you looking for?")

for message in messages:
  if message.Subject ["City status update, City issues"]
    name =str(message.subject)
    regex = re.search(r"city", msg.HTMLbody)
    body = regex.group()

OlSaveAsType = {
  "olTXT": 0,
  "olRTF": 1,
  "olTemplate": 2,
  "olMSG": 3,
  "olDoc": 4,
  "olHTML": 5,
  "olVCard": 6,
  "olVCal": 7,
  "olICal": 8
}

    message.SaveAs(os.getcwd()+'//'+name, OlSaveAsType(['olTXT])

    results = body

r = re.compile('.*/.*/.*:.*')
 if results, True
    print(results - ["."])

 else()

This is what I have so far and a bunch of errors.

Body:
First of all, there is no need to iterate over all items in a folder.

for message in messages:
  if message.Subject ["City status update, City issues"]
    name =str(message.subject)
    regex = re.search(r"city", msg.HTMLbody)
    body = regex.group()

Instead, the Outlook object model provides the Find/FindNext or Restrict methods of the Items class. Read more about them in the following articles:

How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

How To: Use Restrict method to retrieve Outlook mail items from a folder

To deal with a message body I'd suggest using the Word object model. The WordEditor property of the Inspector class returns the Microsoft Word Document Object Model of the message being displayed.

The Outlook object model supports three main ways of customizing the message body:

The Body property returns or sets a string representing the clear-text body of the Outlook item.

The HTMLBody property of the MailItem class returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately.

The Word object model can be used for dealing with message bodies. See Chapter 17: Working with Item Bodies for more information.


问:
Parse HTML with jquery
suppose in a variable html is saved like

```<code>var vhtm="<div><div id='test'>zebra</div><div id='foo'>here is my many other html content</div></div>";
</code>```

i want to parse the above html stored in variable with the help of jquery.
i need to extract a particular div by id and including its content. the return result would like

```<code><div id='foo'>here is my many other html content</div>
</code>```

so i need to find div by id like id='foo'

please help me how to parse the above like jquery.

答:
try something like this : </p>

```<code>$(vhtml).find('#foo');
</code>```

Title: Parse HTML with jquery

Body:
suppose in a variable html is saved like

var vhtm="

zebra

here is my many other html content

";

i want to parse the above html stored in variable with the help of jquery.
i need to extract a particular div by id and including its content. the return result would like

here is my many other html content

so i need to find div by id like id='foo'

please help me how to parse the above like jquery.

Body:
try something like this :

$(vhtml).find('#foo');


问:
Removing a memory address from standard output in Golang
I am attempting to create a clone of git in Go. I am new to Go, especially the "os" and "io" packages.

Question: Why is my function returning a memory address (or maybe it's the number of bytes read?) at the beginning of my output? Is there a way to remove it from the output so that I get the expected output?

Expected output: dumpty vanilla dooby humpty donkey yikes

Got: blob 40\x00dumpty vanilla dooby humpty donkey yikes

Command: ./my_git.sh cat-file -p <HASH>

Relevant Code:

```<code>if os.Args[2] == "-p" {
            // Declare SHA
            sha := os.Args[3]

            // Convert SHA to readable file path
            folder := string(sha[0:2])
            blob := string(sha[2:])
            filePath := ".git/objects/" + folder + "/" + blob

            file, err := os.Open(filePath)
            if err != nil {
                log.Fatal(err)
            }

            r, readError := zlib.NewReader(file)
            if readError != nil {
                log.Fatal(readError)
            }

            io.Copy(os.Stdout, r)
            r.Close()
        }
</code>```

答:
blob 40\x00 is literally part of the (decompressed) file content. It is the object header:

the type of the object (here "blob"; other types include "commit" and "tree", for instance)

the object's size in bytes (here 40)

and a null byte

You can't just remove that. You have to understand the header to make sense of the object content proper.

See the "Git Internals - Git Objects" chapter of the git book for further information.

Body:
I am attempting to create a clone of git in Go. I am new to Go, especially the "os" and "io" packages.

Question: Why is my function returning a memory address (or maybe it's the number of bytes read?) at the beginning of my output? Is there a way to remove it from the output so that I get the expected output?

Expected output: dumpty vanilla dooby humpty donkey yikes

Got: blob 40\x00dumpty vanilla dooby humpty donkey yikes

Command: ./my_git.sh cat-file -p <HASH>

Relevant Code:

if os.Args[2] == "-p" {
            // Declare SHA
            sha := os.Args[3]

            // Convert SHA to readable file path
            folder := string(sha[0:2])
            blob := string(sha[2:])
            filePath := ".git/objects/" + folder + "/" + blob

            file, err := os.Open(filePath)
            if err != nil {
                log.Fatal(err)
            }

            r, readError := zlib.NewReader(file)
            if readError != nil {
                log.Fatal(readError)
            }

            io.Copy(os.Stdout, r)
            r.Close()
        }


问:
Error in -title : invalid argument to unary operator
I am not sure why I suddenly started getting this error (Error in -title : invalid argument to unary operator) when running my R Markdown file.

My Markdown file looks like this:.

```<code>---
title: "Bios653 HW1"
author: "Genevieve"
date: "1/28/2022"
output: html_document
---
</code>```

My Console looks like this: <\br>

```<code>> ---
+ title: "Bios653 HW1"
**Error in -title : invalid argument to unary operator**
> author: "Genevieve"
Error: object 'author' not found
> date: "1/28/2022"
Error in date:"1/28/2022" : NA/NaN argument
In addition: Warning message:
NAs introduced by coercion
> output: html_document
Error: object 'output' not found
> ---
</code>```

答:
It seems like you are just running this with R, e.g. with source, instead of knitting the document.

Use knitr::knit("FILENAME.Rmd"). If you are using RStudio you can click the knit button

Body:
I am not sure why I suddenly started getting this error (Error in -title : invalid argument to unary operator) when running my R Markdown file.

My Markdown file looks like this:.

---
title: "Bios653 HW1"
author: "Genevieve"
date: "1/28/2022"
output: html_document
---

My Console looks like this: <\br>

> ---
+ title: "Bios653 HW1"
**Error in -title : invalid argument to unary operator**
> author: "Genevieve"
Error: object 'author' not found
> date: "1/28/2022"
Error in date:"1/28/2022" : NA/NaN argument
In addition: Warning message:
NAs introduced by coercion
> output: html_document
Error: object 'output' not found
> ---