问:
Sending embeds through discord.py
I've been doing a lot of work creating discord bots with the discord api through javascript with discord.js.

I am trying to create my first discord bot with python using the discord api through discord.py and with requests through requests.py.

My goal is to check status code on a site, and when a message is sent that contains "status code," it will reply with the site's status code in an embed.

Here is my code to do so:

```<code>import discord
import requests
r = requests.get('redactedurl')
test = r.status_code
class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        if (message.channel.id == redacted):
                if "status code" in message.content:
                    print('Message from {0.author}: {0.content}'.format(message))

                    embed = discord.Embed(color=0x00ff00)
                    embed.title = "test"
                    embed.description = '**Status Code:** {r.status_code}'
                    await message.channel.send(embed=embed)

client = MyClient()
client.run('redacted')
</code>```

The following is a list of questions I hope anybody can answer to help me out :)

As you see here: https://gyazo.com/f6ae7082486cade72389534a05655fec, this just sends "{r.status_code}" in the embed, instead of the actual status code, what am I doing wrong?

What does it mean when i see 0 in the curly brackets. For example, can somebody explain "('Logged on as {0}!'.format(self.user))" to me? Since I'm new to python and discord.py, I am confused about this whole line. I know what the outcome is, but forgive my ignorance, is it all necessary?

In "send(embed=embed)", why can't i just put send(embed)?

Finally, is there anything else that i can do to improve the code?

Thank you so much if you're able to help!

答:
In the line you set the embed description, outputting r.status_code as a string instead of the value it contains. Try  embed.description = '**Status Code:** {0}'.format(r.status_code)

The 0 resembles the index of the value that is supposed to be there. For example, '{1}'.format(10, 20) would print out the value at index 1 which in this case is 20.

When you use send(embed) then the bot will end up sending the embed in string form which will look very off, if you try sending it you will see what I mean. In this case, we have to specify which argument we are assigning the value to. This function accepts kwargs which are Keyworded arguments, in this case, embed is one of the kwargs in this send() function. This function accepts other kwargs as well such as content, tts, delete_after, etc. It is all documented.

You can simplify creating the embed by passing in the kwargs, for example: discord.Embed(title='whatever title', color='whatever color')
The discord.Embed() can support more arguments if you look at the documentation.

Here is a link to the documentation: https://discordpy.readthedocs.io/en/latest/index.html
If you search for TextChannel, and look for the send() function, you can find more arguments supported, as well as for discord.Embed().

Title: Sending embeds through discord.py

Body:
I've been doing a lot of work creating discord bots with the discord api through javascript with discord.js.

I am trying to create my first discord bot with python using the discord api through discord.py and with requests through requests.py.

My goal is to check status code on a site, and when a message is sent that contains "status code," it will reply with the site's status code in an embed.

Here is my code to do so:

import discord
import requests
r = requests.get('redactedurl')
test = r.status_code
class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        if (message.channel.id == redacted):
                if "status code" in message.content:
                    print('Message from {0.author}: {0.content}'.format(message))

                    embed = discord.Embed(color=0x00ff00)
                    embed.title = "test"
                    embed.description = '**Status Code:** {r.status_code}'
                    await message.channel.send(embed=embed)

client = MyClient()
client.run('redacted')

The following is a list of questions I hope anybody can answer to help me out :)

As you see here: https://gyazo.com/f6ae7082486cade72389534a05655fec, this just sends "{r.status_code}" in the embed, instead of the actual status code, what am I doing wrong?

What does it mean when i see 0 in the curly brackets. For example, can somebody explain "('Logged on as {0}!'.format(self.user))" to me? Since I'm new to python and discord.py, I am confused about this whole line. I know what the outcome is, but forgive my ignorance, is it all necessary?

In "send(embed=embed)", why can't i just put send(embed)?

Finally, is there anything else that i can do to improve the code?

Thank you so much if you're able to help!


来源: stackexchange

问:
mutate_if - warning message
Hello everybody,

```<code>library(dplyr)
library(tibble)
mtcars %>%
  rownames_to_column("modelle") %>%
  mutate_if(~is.numeric(.x) & mean(.x) > 50, ~(.x / 1000))

Warning message:
In mean.default(.x) : argument is not numeric or logical: returning NA
</code>```

This error seems to be because of the character vector. It works, but it´s still very ugly. Did I do anything wrong and what can be done better in that case?

Thank you!

答:
You should use "&&" instead of "&". The first is used for scalars and the second, for vectors. In your case, the average is a scalar.</p>

```<code>library(dplyr)
library(tibble)
mtcars %>%
rownames_to_column("modelle") %>%
mutate_if(~is.numeric(.x) && mean(.x) > 50, ~(.x / 1000))
</code>```

ContentLicense: CC BY-SA 4.0

Title: mutate_if - warning message

Body:
Hello everybody,

library(dplyr)
library(tibble)
mtcars %>%
  rownames_to_column("modelle") %>%
  mutate_if(~is.numeric(.x) & mean(.x) > 50, ~(.x / 1000))

Warning message:
In mean.default(.x) : argument is not numeric or logical: returning NA

This error seems to be because of the character vector. It works, but it´s still very ugly. Did I do anything wrong and what can be done better in that case?

Thank you!

Body:
You should use "&&" instead of "&". The first is used for scalars and the second, for vectors. In your case, the average is a scalar.

library(dplyr)
library(tibble)
mtcars %>%
rownames_to_column("modelle") %>%
mutate_if(~is.numeric(.x) && mean(.x) > 50, ~(.x / 1000))


问:
Inserting a NULL value into MySQL from PHP using a NULL-valued variable
I'm using the WordPress DB interface to insert some nullable row values.

The function:
$wpdb->insert( $table, $data, $format );

takes an array of values in the $data param.  If I exclude certain field values from the $data array, the fields show up null in the table.  However, I want to be able to populate the $data array with values for all the fields, but make those values null when I need to.  However, if I pass values that = NULL, the database values are not null, but blank.  What should I do?

答:
Looking at the wpdb source code, the "insert" method ends up being mapped into SQL that places every field value between single-quotes (line 1233):

```<code>    $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`)
                VALUES ('" . implode( "','", $formatted_fields ) . "')";
</code>```

To insert a real NULL, you need to place an unadorned NULL word into that expression, and it's  not allowed for. So what is being inserted is the 4-letter string "NULL".

Note that this method leaves it to the user to be inserting the proper data types and depends on MySQL to automatically convert quoted e.g. numerics into real numeric values.

ContentLicense: CC BY-SA 3.0

Body:
Looking at the wpdb source code, the "insert" method ends up being mapped into SQL that places every field value between single-quotes (line 1233):

    $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`)
                VALUES ('" . implode( "','", $formatted_fields ) . "')";

To insert a real NULL, you need to place an unadorned NULL word into that expression, and it's  not allowed for. So what is being inserted is the 4-letter string "NULL".

Note that this method leaves it to the user to be inserting the proper data types and depends on MySQL to automatically convert quoted e.g. numerics into real numeric values.


问:
How to pass environment variables via Travis CI into the docker build commands
I want to pass environment variables into the build commands both in before_install & after_success blocks. Below is the .travis.yml file.</p>

```<code>sudo: required
language: node_js
node_js:
  - 12.13.0
service:
  - docker

before_install:
  - docker build -t ******/react-test -f ./frontend/Dockerfile.dev ./frontend

script:
  - docker run -e CI=true ******/react-test npm run test

after_success:
  - docker build -t ******/video-chat-client ./frontend
  - docker build -t ******/video-chat-nginx ./nginx
  - docker build -t ******/video-chat-api ./backend

  # Log in to the docker-cli
  - echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_ID" --password-stdin

  # Push the production images to docker-hub
  - docker push ******/video-chat-client
  - docker push ******/video-chat-nginx
  - docker push ******/video-chat-api
</code>```

答: There is an Environment Variables section, in the settings of your project in travis-ci web console. In my projects, I have added some variables there, and then used them in the .travis.yml file.

Body:
I want to pass environment variables into the build commands both in before_install & after_success blocks. Below is the .travis.yml file.

sudo: required
language: node_js
node_js:
  - 12.13.0
service:
  - docker

before_install:
  - docker build -t ******/react-test -f ./frontend/Dockerfile.dev ./frontend

script:
  - docker run -e CI=true ******/react-test npm run test

after_success:
  - docker build -t ******/video-chat-client ./frontend
  - docker build -t ******/video-chat-nginx ./nginx
  - docker build -t ******/video-chat-api ./backend

  # Log in to the docker-cli
  - echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_ID" --password-stdin

  # Push the production images to docker-hub
  - docker push ******/video-chat-client
  - docker push ******/video-chat-nginx
  - docker push ******/video-chat-api


问:
How to submit a tag with Bootstrap Tags Input plugin with space key?
I'm building a form with a field that is using the Bootstrap Tags Input plugin. This plugin inputs a tag once the user clicks the Enter key.

Can anyone help use the documentation of the plugin to input a tag once the user puts a "," (comma) or a space in the field?

Here is the documentation - http://timschlechter.github.io/bootstrap-tagsinput/examples/

2020 edit: heres the doco: https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/

答:
I couldn't get confirmKeys to work. No error, it just made no difference to operation.

My root problem was that enter was submitting the form instead of creating the tag.

This issue solved it for me:

https://github.com/bootstrap-tagsinput/bootstrap-tagsinput/issues/625

Code reproduced here:

```<code>$('.bootstrap-tagsinput input').keydown(function (event) {
    debugger;
    if ( event.which == 13) {
        $(this).blur();
        $(this).focus();
        return false;
    }
})
</code>```

If the field recieves enter, it removes and returns focus.

return false stops the enter key event bubbling up to the form.

With regards to using space, you should be able to use event.which == 32 but that doesn't function for some reason.

EDIT:

After this I noticed that even when I removed the code, enter worked as required

Then I noticed the cancelConfirmKeysOnEmpty option. So I guess my original form just wasn't set up properly

Body:
I couldn't get confirmKeys to work. No error, it just made no difference to operation.

My root problem was that enter was submitting the form instead of creating the tag.

This issue solved it for me:

https://github.com/bootstrap-tagsinput/bootstrap-tagsinput/issues/625

Code reproduced here:

$('.bootstrap-tagsinput input').keydown(function (event) {
    debugger;
    if ( event.which == 13) {
        $(this).blur();
        $(this).focus();
        return false;
    }
})

If the field recieves enter, it removes and returns focus.

return false stops the enter key event bubbling up to the form.

With regards to using space, you should be able to use event.which == 32 but that doesn't function for some reason.

EDIT:

After this I noticed that even when I removed the code, enter worked as required

Then I noticed the cancelConfirmKeysOnEmpty option. So I guess my original form just wasn't set up properly


问:
SQL: SELECT rows with max date from created table
I´m wondering how to create a query that returns SERIALID, QTY, but only for the last INVOICEDATE.

To combine information from two tables I use UNION.

```<code>SELECT ab.SERIALID, ab.QTY, ab.INVOICEDATE
FROM (SELECT a.INVOICEDATE, a.SERIALID, a.QTY
      FROM SALESTRANS a
      UNION
      SELECT b.INVOICEDATE, b.SERIALID, b.QTY
      FROM SERVICETRANS b
     ) ab
</code>```

I have two tables combined with UNION and my table looks:

I would like to make a query that returns SERIALID, QTY, but only for the last INVOICEDDATE.

The result I would like to get:

Thanks in advance!

答:
If your RDBMS support ROW_NUMBER(), you can achieve this using ROW_NUMBER() PARTITION BY like following.

```<code>SELECT *
FROM (
    SELECT *
        ,ROW_NUMBER() OVER (
            PARTITION BY SERIALID ORDER BY INVOICEDATE DESC
            ) RN
    FROM SERVICETRANS
    ) T
WHERE RN = 1
</code>```

Above query will return you 1 record for each SERIALID having max INVOICEDATE

Same can be done without ROW_NUMBER() like following.

```<code>SELECT *
FROM SERVICETRANS ST
WHERE INVOICEDATE = (
        SELECT MAX(INVOICEDATE)
        FROM SERVICETRANS STI
        WHERE STI.SERIALID = ST.SERIALID
        )
</code>```

Note: Above query may return multiple rows for one SERIALID if the MAX(INVOICEDATE) is same for multiple records of same SERIALID.

Body:
I´m wondering how to create a query that returns SERIALID, QTY, but only for the last INVOICEDATE.

To combine information from two tables I use UNION.

SELECT ab.SERIALID, ab.QTY, ab.INVOICEDATE
FROM (SELECT a.INVOICEDATE, a.SERIALID, a.QTY
      FROM SALESTRANS a
      UNION
      SELECT b.INVOICEDATE, b.SERIALID, b.QTY
      FROM SERVICETRANS b
     ) ab

I have two tables combined with UNION and my table looks:

I would like to make a query that returns SERIALID, QTY, but only for the last INVOICEDDATE.

The result I would like to get:

Thanks in advance!

Body:
If your RDBMS support ROW_NUMBER(), you can achieve this using ROW_NUMBER() PARTITION BY like following.

SELECT *
FROM (
    SELECT *
        ,ROW_NUMBER() OVER (
            PARTITION BY SERIALID ORDER BY INVOICEDATE DESC
            ) RN
    FROM SERVICETRANS
    ) T
WHERE RN = 1

Above query will return you 1 record for each SERIALID having max INVOICEDATE

Same can be done without ROW_NUMBER() like following.

SELECT *
FROM SERVICETRANS ST
WHERE INVOICEDATE = (
        SELECT MAX(INVOICEDATE)
        FROM SERVICETRANS STI
        WHERE STI.SERIALID = ST.SERIALID
        )

Note: Above query may return multiple rows for one SERIALID if the MAX(INVOICEDATE) is same for multiple records of same SERIALID.


问:
How to cap the height of a lists parant div and make the content scrollable?
I successfully made the div in the background change to fit all items using:

```<code>       newHeight = document.getElementById("searchResultsList").offsetHeight+115;//document.getElementById(newHeight).offsetHeight+newHeight;//document.getElementsByClassName("searchUserDiv").offsetHeight
       document.getElementById('searchDiv').style.height = ''+newHeight+'px';
</code>```

The problem however is that at some point I need to stop adding height to the div and instead make the div scroll-able. I found the nav element but have not figured out a way to set a max height (At which point the list is scrollable) it can reach as elements are added dynamicaly. How can I achieve this?

//In for each loop I do the following

$('.searchResultsList').append('
'+username+'
');
           newHeight = document.getElementById("searchResultsList").offsetHeight+115;//document.getElementById(newHeight).offsetHeight+newHeight;//document.getElementsByClassName("searchUserDiv").offsetHeight
           document.getElementById('searchDiv').style.height = ''+newHeight+'px';```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.searchBar {
  width: 500px;
  height: 55px;
  background-color: #3C3C3C;
  border-radius: 50px;
  margin-top: 12px;

  box-shadow: 0 1px 2px rgba(0, 0, 0, 0);
  transition: box-shadow 0.05s ease-in-out;
}

.searchBar:hover {
  box-shadow: 0 0px 10px rgba(0, 0, 0, 0.5);
}

.searchBtn {
  margin-top: 1px;
  display: inline-block;
  width: 12%;
  height: 100%;
  background-color: transparent;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  /* background-image:url('../images/searchBtnIcon.png');
  background-size: 85%;
  background-repeat:no-repeat;
  vertical-align: middle; */
}

.searchBtn img {
  vertical-align: bottom;
  width: 96%;
  /* height: 100%; */
}

/* .searchBar button:hover {
  background-color: white;
} */

.searchDiv {
  vertical-align: top;
  height: 100%;
  margin-left: 50px;
  display: inline-block;
  background-color: #292929;
  border-bottom-left-radius: 30px;
  border-bottom-right-radius: 30px;
}

.searchDiv input {
  display: inline-block;
  padding-bottom: 5px;
  padding-left: 30px;
  /* width: 500px;
  height: 50px; */
  width: 78%;
  height: 95%;
  border: none;
  /* background-color: #3C3C3C; */
  background-color: transparent;
  color: white;
  font: Arial;
  font-family: sans-serif;
  font-size: 18px;
  font-weight:bold;
  outline: none;
  /* border-radius: 50px; */
  vertical-align: top;
}

.searchDiv:hover ::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
  color: #838383;
  opacity: 1; /* Firefox */
}
.searchDiv:hover {
  /* height: 600px; */
  /* background-color: #292929; */
  /* #3C3C3C; */
  box-shadow: 0 0px 10px rgba(41, 41, 41, 0.8);
}

.searchResultsList {
  /* background-color: grey; */
  padding-left: 0px;
}

.searchResultsList li {
  list-style: none;

  transition: 0.06s background-color;
}
.searchResultsList li:hover {
  background-color: rgba(255, 255, 255, 0.05);
}
.searchResultsList li:active {
  background-color: rgba(255, 255, 255, 0.1);
}
.searchResultsList * {
  /* background-color: grey; */
  /* margin: 13px 0 13px 0; */
  margin-top: 6px;
  margin-bottom: 6px;
  /* margin-left: 0px; */
  cursor: pointer;
}

.searchUserDiv {
  display: flex;
  align-items: center;
  /* background-color: #353258;
  border: 1px solid #4152F1; */
  color: white;
  cursor: pointer;
  padding-left: 10px;
  width: 98%;
  /* border-radius: 32px; */
}
.searchUsername {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  font: Arial;
  font-family: sans-serif;
  margin-top: 7px;
  padding-left: 13px;
}
.searchUserProfImg {
  border-radius: 25px;
  border: 1px solid #505050;
  margin-left: 5px;
  height: 47px;
  width:47px;
}</code>```

          <input type="text" placeholder="Search" name="search" id="search" required>
          <button class="searchBtn" id="searchBtn"> </button>

              Noha harrarri

              Nohasomething

              Noha_2

```

答: set the height a fix number like 200px then set the overflow scroll for the div.</p>

Body:
I successfully made the div in the background change to fit all items using:

       newHeight = document.getElementById("searchResultsList").offsetHeight+115;//document.getElementById(newHeight).offsetHeight+newHeight;//document.getElementsByClassName("searchUserDiv").offsetHeight
       document.getElementById('searchDiv').style.height = ''+newHeight+'px';

The problem however is that at some point I need to stop adding height to the div and instead make the div scroll-able. I found the nav element but have not figured out a way to set a max height (At which point the list is scrollable) it can reach as elements are added dynamicaly. How can I achieve this?

//In for each loop I do the following

$('.searchResultsList').append('
'+username+'
');
           newHeight = document.getElementById("searchResultsList").offsetHeight+115;//document.getElementById(newHeight).offsetHeight+newHeight;//document.getElementsByClassName("searchUserDiv").offsetHeight
           document.getElementById('searchDiv').style.height = ''+newHeight+'px';

.searchBar {
  width: 500px;
  height: 55px;
  background-color: #3C3C3C;
  border-radius: 50px;
  margin-top: 12px;

  box-shadow: 0 1px 2px rgba(0, 0, 0, 0);
  transition: box-shadow 0.05s ease-in-out;
}

.searchBar:hover {
  box-shadow: 0 0px 10px rgba(0, 0, 0, 0.5);
}

.searchBtn {
  margin-top: 1px;
  display: inline-block;
  width: 12%;
  height: 100%;
  background-color: transparent;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  /* background-image:url('../images/searchBtnIcon.png');
  background-size: 85%;
  background-repeat:no-repeat;
  vertical-align: middle; */
}

.searchBtn img {
  vertical-align: bottom;
  width: 96%;
  /* height: 100%; */
}

/* .searchBar button:hover {
  background-color: white;
} */

.searchDiv {
  vertical-align: top;
  height: 100%;
  margin-left: 50px;
  display: inline-block;
  background-color: #292929;
  border-bottom-left-radius: 30px;
  border-bottom-right-radius: 30px;
}

.searchDiv input {
  display: inline-block;
  padding-bottom: 5px;
  padding-left: 30px;
  /* width: 500px;
  height: 50px; */
  width: 78%;
  height: 95%;
  border: none;
  /* background-color: #3C3C3C; */
  background-color: transparent;
  color: white;
  font: Arial;
  font-family: sans-serif;
  font-size: 18px;
  font-weight:bold;
  outline: none;
  /* border-radius: 50px; */
  vertical-align: top;
}

.searchDiv:hover ::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
  color: #838383;
  opacity: 1; /* Firefox */
}
.searchDiv:hover {
  /* height: 600px; */
  /* background-color: #292929; */
  /* #3C3C3C; */
  box-shadow: 0 0px 10px rgba(41, 41, 41, 0.8);
}

.searchResultsList {
  /* background-color: grey; */
  padding-left: 0px;
}

.searchResultsList li {
  list-style: none;

  transition: 0.06s background-color;
}
.searchResultsList li:hover {
  background-color: rgba(255, 255, 255, 0.05);
}
.searchResultsList li:active {
  background-color: rgba(255, 255, 255, 0.1);
}
.searchResultsList * {
  /* background-color: grey; */
  /* margin: 13px 0 13px 0; */
  margin-top: 6px;
  margin-bottom: 6px;
  /* margin-left: 0px; */
  cursor: pointer;
}

.searchUserDiv {
  display: flex;
  align-items: center;
  /* background-color: #353258;
  border: 1px solid #4152F1; */
  color: white;
  cursor: pointer;
  padding-left: 10px;
  width: 98%;
  /* border-radius: 32px; */
}
.searchUsername {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  font: Arial;
  font-family: sans-serif;
  margin-top: 7px;
  padding-left: 13px;
}
.searchUserProfImg {
  border-radius: 25px;
  border: 1px solid #505050;
  margin-left: 5px;
  height: 47px;
  width:47px;
}

          <input type="text" placeholder="Search" name="search" id="search" required>
          <button class="searchBtn" id="searchBtn"> </button>

              Noha harrarri

              Nohasomething

              Noha_2


问:
Having problem in reset of checkboxes in react functional component want solution?
```<code>//Main functional component
function CustomizedTables(props) {
  const classes = useStyles();
  const [nameCheckbox, setnameCheckbox] = useState([]);
  const [emailCheckbox, setemailCheckbox] = useState([]);
  const [faxCheckbox, setfaxCheckbox] = useState([]);
  const [loopStopFlag, setFlag] = useState(true);
  const [emailFlag, setEmailFlag] = useState(false);
  const rows = props.data;

  //Initialization of checkboxes to true
  if (loopStopFlag) {
    let nameArray = [];
    let emailArray = [];
    let faxArray = [];
    rows.SupplierList.forEach((supplier, i) => {
      nameArray.push(true);
      if (supplier.Email) {
        emailArray.push(true);
      } else {
        emailArray.push(null);
      }
      if (supplier.Fax) {
        faxArray.push(true);
      } else {
        faxArray.push(null);
      }
    });
    setnameCheckbox(nameArray);
    setemailCheckbox(emailArray);
    setfaxCheckbox(faxArray);
    setFlag(false);
  }

  //Reseting all checkboxes
  const resetAllCheckbox = () => {
    let nameArray = [];
    let emailArray = [];
    let faxArray = [];

    rows.SupplierList.forEach((supplier, i) => {
      nameArray.push(false);
      if (supplier.Email) {
        emailArray.push(false);
      } else {
        emailArray.push(null);
      }
      if (supplier.Fax) {
        faxArray.push(false);
      } else {
        faxArray.push(null);
      }
    });
    setnameCheckbox(nameArray);
    setemailCheckbox(emailArray);
    setfaxCheckbox(faxArray);
    if (emailCheckbox.includes(true)) {
      setEmailFlag(false);
    } else {
      setEmailFlag(true);
    }
  };

  //Displaying data on screen
  return (
    <div>
      <Paper className={classes.root} style={{ marginLeft: "32px" }}>
        <Table className={classes.table} aria-label="customized table">
          <TableBody>
            {rows.SupplierList.map((row, i) => (
              <StyledTableRow key={i}>
                <StyledTableCell style={{ color: "#474747" }} align="center">
                  <label>
                    {row.Name}{" "}
                    <input
                      type="checkbox"
                      style={{ marginLeft: "5px", cursor: "pointer" }}
                      onChange={() => {
                        let arr = nameCheckbox;
                        arr[i] = !arr[i];
                        setnameCheckbox(arr);
                      }}
                      defaultChecked={nameCheckbox[i]}
                    />
                  </label>
                  <br />
                  <div style={{ fontSize: "11px" }}>{row.Gbf && "GBF"}</div>
                </StyledTableCell>
                <StyledTableCell align="center" style={{ color: "#474747" }}>
                  {row.Email && (
                    <React.Fragment>
                      <input
                        type="checkbox"
                        style={{ marginLeft: "5px", cursor: "pointer" }}
                        onChange={() => {
                          let arr1 = emailCheckbox;
                          arr1[i] = !arr1[i];
                          setemailCheckbox(arr1);
                          if (emailCheckbox.includes(true)) {
                            setEmailFlag(false);
                          } else {
                            setEmailFlag(true);
                          }
                        }}
                        defaultChecked={emailCheckbox[i]}
                      />
                    </React.Fragment>
                  )}
                </StyledTableCell>
                <StyledTableCell align="center" style={{ color: "#474747" }}>
                  {row.Fax && (
                    <React.Fragment>
                      <input
                        type="checkbox"
                        style={{ marginLeft: "5px", cursor: "pointer" }}
                        onChange={() => {
                          let arr2 = faxCheckbox;
                          arr2[i] = !arr2[i];
                          setfaxCheckbox(arr2);
                        }}
                        value={faxCheckbox[i]}
                        defaultChecked={faxCheckbox[i]}
                      />
                    </React.Fragment>
                  )}
                </StyledTableCell>
              </StyledTableRow>
            ))}
          </TableBody>
        </Table>
      </Paper>
      <br />
      <Button
        variant="danger"
        style={{ width: "100px" }}
        onClick={resetAllCheckbox}
      >
        Reset
      </Button>
    </div>
  );
}
export default CustomizedTables;
</code>```

I am facing problem in reseting checkboxes. When I reset them only array is updating but no action is performing or checkboxes. I used both checked and defaultChecked in checked also facing problem that bool is updating but checkbox is not updating. I want a solution for it. Actually when I click on reset button then my checkboxes remain same form but state is updating

答:
I couldn't replicate your exact code in a sandbox because of it's dependencies so I've put up a simple example that has a set of checkboxes, check action and reset action.

Modify your code based on the example and these notes and it would work as expected:

Whenever you render a react element from inside loops you should provide a unique key, this helps react identify what changed.

Keep your checkbox state in your react/store state and set it using checked prop and not defaultChecked. On reset update the store/local states and the component will re-render.

Check the sandbox:
https://codesandbox.io/s/pedantic-violet-twtvn?fontsize=14&hidenavigation=1&theme=dark

```<code>import React, { useState, useEffect } from "react";

function CheckboxDemo({ data }) {
  const [features, setFeatures] = useState([]);

  useEffect(() => {
    setFeatures(data);
  }, [data]);

  const resetCheckboxes = () => {
    const newFeatures = [];
    features.forEach(f => {
      newFeatures.push({ ...f, checked: false });
    });
    setFeatures(newFeatures);
  };

  const setFeatureCheck = index => () => {
    const updatedFeature = {
      ...features[index],
      checked: !features[index].checked
    };
    const newFeatures = [
      ...features.slice(0, index),
      updatedFeature,
      ...features.slice(index + 1)
    ];
    setFeatures(newFeatures);
  };

  const checkBoxes = features.map((f, i) => (
    <div className="box" key={i + "_" + f.label}>
      <input
        type="checkbox"
        checked={f.checked}
        onChange={setFeatureCheck(i)}
      />{" "}
      {f.label}
    </div>
  ));

  return (
    <div className="wrapper">
      {checkBoxes}
      <div className="controls">
        <input type="button" onClick={resetCheckboxes} value="Reset" />
      </div>
    </div>
  );
}
export default CheckboxDemo;
</code>```

Body:
//Main functional component
function CustomizedTables(props) {
  const classes = useStyles();
  const [nameCheckbox, setnameCheckbox] = useState([]);
  const [emailCheckbox, setemailCheckbox] = useState([]);
  const [faxCheckbox, setfaxCheckbox] = useState([]);
  const [loopStopFlag, setFlag] = useState(true);
  const [emailFlag, setEmailFlag] = useState(false);
  const rows = props.data;

  //Initialization of checkboxes to true
  if (loopStopFlag) {
    let nameArray = [];
    let emailArray = [];
    let faxArray = [];
    rows.SupplierList.forEach((supplier, i) => {
      nameArray.push(true);
      if (supplier.Email) {
        emailArray.push(true);
      } else {
        emailArray.push(null);
      }
      if (supplier.Fax) {
        faxArray.push(true);
      } else {
        faxArray.push(null);
      }
    });
    setnameCheckbox(nameArray);
    setemailCheckbox(emailArray);
    setfaxCheckbox(faxArray);
    setFlag(false);
  }

  //Reseting all checkboxes
  const resetAllCheckbox = () => {
    let nameArray = [];
    let emailArray = [];
    let faxArray = [];

    rows.SupplierList.forEach((supplier, i) => {
      nameArray.push(false);
      if (supplier.Email) {
        emailArray.push(false);
      } else {
        emailArray.push(null);
      }
      if (supplier.Fax) {
        faxArray.push(false);
      } else {
        faxArray.push(null);
      }
    });
    setnameCheckbox(nameArray);
    setemailCheckbox(emailArray);
    setfaxCheckbox(faxArray);
    if (emailCheckbox.includes(true)) {
      setEmailFlag(false);
    } else {
      setEmailFlag(true);
    }
  };

  //Displaying data on screen
  return (

      <Paper className={classes.root} style={{ marginLeft: "32px" }}>

          <TableBody>
            {rows.SupplierList.map((row, i) => (

              </StyledTableRow>
            ))}
          </TableBody>

      </Paper>

      <Button
        variant="danger"
        style={{ width: "100px" }}
        onClick={resetAllCheckbox}
      >
        Reset
      </Button>

  );
}
export default CustomizedTables;

I am facing problem in reseting checkboxes. When I reset them only array is updating but no action is performing or checkboxes. I used both checked and defaultChecked in checked also facing problem that bool is updating but checkbox is not updating. I want a solution for it. Actually when I click on reset button then my checkboxes remain same form but state is updating

Body:
I couldn't replicate your exact code in a sandbox because of it's dependencies so I've put up a simple example that has a set of checkboxes, check action and reset action.

Modify your code based on the example and these notes and it would work as expected:

Whenever you render a react element from inside loops you should provide a unique key, this helps react identify what changed.

Keep your checkbox state in your react/store state and set it using checked prop and not defaultChecked. On reset update the store/local states and the component will re-render.

Check the sandbox:
https://codesandbox.io/s/pedantic-violet-twtvn?fontsize=14&hidenavigation=1&theme=dark

import React, { useState, useEffect } from "react";

function CheckboxDemo({ data }) {
  const [features, setFeatures] = useState([]);

  useEffect(() => {
    setFeatures(data);
  }, [data]);

  const resetCheckboxes = () => {
    const newFeatures = [];
    features.forEach(f => {
      newFeatures.push({ ...f, checked: false });
    });
    setFeatures(newFeatures);
  };

  const setFeatureCheck = index => () => {
    const updatedFeature = {
      ...features[index],
      checked: !features[index].checked
    };
    const newFeatures = [
      ...features.slice(0, index),
      updatedFeature,
      ...features.slice(index + 1)
    ];
    setFeatures(newFeatures);
  };

  const checkBoxes = features.map((f, i) => (
    <div className="box" key={i + "_" + f.label}>
      <input
        type="checkbox"
        checked={f.checked}
        onChange={setFeatureCheck(i)}
      />{" "}
      {f.label}
    </div>
  ));

  return (
    <div className="wrapper">
      {checkBoxes}
      <div className="controls">
        <input type="button" onClick={resetCheckboxes} value="Reset" />
      </div>
    </div>
  );
}
export default CheckboxDemo;


问:
POSIX message queue connection issue: mq_open No such file or directory
```<code>#define MESSAGE_QUEUE_NAME "/project"

int main (int argc, char **argv){
    char user_name[USER_NAME_LEN];
    mqd_t qd_server;
    int flags;

   if (argc != 2) {
       printf ("Usage: %s user-name\n", argv[0]);
       exit (EXIT_FAILURE);
   }
   strcpy (user_name, argv[1]);
   printf ("User %s connecting to server\n", user_name);

   if ((qd_server = mq_open (SERVER_QUEUE_NAME, O_WRONLY)) == -1) {
       perror ("Client: mq_open (server)");
       exit (1);
   }
   …
</code>```

I tried to open the message queue before sending a message to the queue. Before sending a message, I need to open queue server, but when I run it, the error said:

```<code>Client: mq_open (server): No such file or directory
</code>```

I just have no idea what is going on.

答:
According to the man page, you are getting the ENOENT error number because "The O_CREAT flag was not specified in oflag, and no queue with this name exists."

So, you may have not created your message queue. You can create it if it does not exist by changing your call to mq_open to  mq_open(SERVER_QUEUE_NAME, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR, NULL). Instead of passing NULL as the attrargument, you can specify your own mq_attr struct with the maximum queue length and message size.

Body:
#define MESSAGE_QUEUE_NAME "/project"

int main (int argc, char **argv){
    char user_name[USER_NAME_LEN];
    mqd_t qd_server;
    int flags;

   if (argc != 2) {
       printf ("Usage: %s user-name\n", argv[0]);
       exit (EXIT_FAILURE);
   }
   strcpy (user_name, argv[1]);
   printf ("User %s connecting to server\n", user_name);

   if ((qd_server = mq_open (SERVER_QUEUE_NAME, O_WRONLY)) == -1) {
       perror ("Client: mq_open (server)");
       exit (1);
   }
   …

I tried to open the message queue before sending a message to the queue. Before sending a message, I need to open queue server, but when I run it, the error said:

Client: mq_open (server): No such file or directory

I just have no idea what is going on.


问:
Writing a custom case_when function to use in dplyr mutate using tidyeval
I'm trying to write a custom case_when function to use inside dplyr. I've been reading through the tidyeval examples posted in other questions, but still can't figure out how to make it work. Here's a reprex:

```<code>df1 <- data.frame(animal_1 = c("Horse", "Pig", "Chicken", "Cow", "Sheep"),
           animal_2 = c(NA, NA, "Horse", "Sheep", "Chicken"))

translate_title <- function(data, input_col, output_col) {
  mutate(data,
    !!output_col := case_when(
    input_col == "Horse" ~ "Cheval",
    input_col == "Pig" ~ "Рorc",
    input_col == "Chicken" ~ "Poulet",
    TRUE ~ NA)
  )
}

df1 %>%
  translate_title("animal_1", "animaux_1") %>%
  translate_title("animal_2", "animaux_2")
</code>```

When I try to run this, I'm getting
Error in mutate_impl(.data, dots) : Evaluation error: must be type string, not logical.

Also I would actually like to rewrite the function so that it can be used like this:

```<code>df1 %>%
  mutate(animaux_1 = translate_title(animal_1),
         animaux_2 = translate_title(animal_2)
         )
</code>```

But not sure how.

答:
Depending on how you want to pass your input to the function you can solve it in two ways :

1) Pass input as unquoted using {{}}

```<code>library(dplyr)

translate_title <- function(data, input_col, output_col) {

   mutate(data,
        !!output_col := case_when(
        {{input_col}} == "Horse" ~ "Cheval",
        {{input_col}} == "Pig" ~ "Рorc",
        {{input_col}} == "Chicken" ~ "Poulet",
        TRUE ~ NA_character_)
  )
}

df1 %>%
  translate_title(animal_1, "animaux_1") %>%
  translate_title(animal_2, "animaux_2")

#  animal_1 animal_2 animaux_1 animaux_2
#1    Horse     <NA>    Cheval      <NA>
#2      Pig     <NA>      Рorc      <NA>
#3  Chicken    Horse    Poulet    Cheval
#4      Cow    Sheep      <NA>      <NA>
#5    Sheep  Chicken      <NA>    Poulet
</code>```

2) Pass input quoted using sym and !!

```<code>translate_title <- function(data, input_col, output_col) {
   mutate(data,
         !!output_col := case_when(
          !!sym(input_col) == "Horse" ~ "Cheval",
          !!sym(input_col) == "Pig" ~ "Рorc",
          !!sym(input_col) == "Chicken" ~ "Poulet",
          TRUE ~ NA_character_)
  )
}

df1 %>%
  translate_title("animal_1", "animaux_1") %>%
  translate_title("animal_2", "animaux_2")
</code>```

Body:
I'm trying to write a custom case_when function to use inside dplyr. I've been reading through the tidyeval examples posted in other questions, but still can't figure out how to make it work. Here's a reprex:

df1 <- data.frame(animal_1 = c("Horse", "Pig", "Chicken", "Cow", "Sheep"),
           animal_2 = c(NA, NA, "Horse", "Sheep", "Chicken"))

translate_title <- function(data, input_col, output_col) {
  mutate(data,
    !!output_col := case_when(
    input_col == "Horse" ~ "Cheval",
    input_col == "Pig" ~ "Рorc",
    input_col == "Chicken" ~ "Poulet",
    TRUE ~ NA)
  )
}

df1 %>%
  translate_title("animal_1", "animaux_1") %>%
  translate_title("animal_2", "animaux_2")

When I try to run this, I'm getting
Error in mutate_impl(.data, dots) : Evaluation error: must be type string, not logical.

Also I would actually like to rewrite the function so that it can be used like this:

df1 %>%
  mutate(animaux_1 = translate_title(animal_1),
         animaux_2 = translate_title(animal_2)
         )

But not sure how.

Body:
Depending on how you want to pass your input to the function you can solve it in two ways :

1) Pass input as unquoted using {{}}

library(dplyr)

translate_title <- function(data, input_col, output_col) {

   mutate(data,
        !!output_col := case_when(
        {{input_col}} == "Horse" ~ "Cheval",
        {{input_col}} == "Pig" ~ "Рorc",
        {{input_col}} == "Chicken" ~ "Poulet",
        TRUE ~ NA_character_)
  )
}

df1 %>%
  translate_title(animal_1, "animaux_1") %>%
  translate_title(animal_2, "animaux_2")

#  animal_1 animal_2 animaux_1 animaux_2
#1    Horse     <NA>    Cheval      <NA>
#2      Pig     <NA>      Рorc      <NA>
#3  Chicken    Horse    Poulet    Cheval
#4      Cow    Sheep      <NA>      <NA>
#5    Sheep  Chicken      <NA>    Poulet

2) Pass input quoted using sym and !!

translate_title <- function(data, input_col, output_col) {
   mutate(data,
         !!output_col := case_when(
          !!sym(input_col) == "Horse" ~ "Cheval",
          !!sym(input_col) == "Pig" ~ "Рorc",
          !!sym(input_col) == "Chicken" ~ "Poulet",
          TRUE ~ NA_character_)
  )
}

df1 %>%
  translate_title("animal_1", "animaux_1") %>%
  translate_title("animal_2", "animaux_2")


问:
Serializing protocol buffers to XML?
The protocol buffers Java tutorial states:

One key feature provided by protocol message classes is reflection. [...] One very useful way to use reflection is for converting protocol messages to and from other encodings, such as XML or JSON.

And if you look at com.google.protobuf.Message it says:

The biggest added features [of the Message class over the MessageLite class] are introspection and reflection.

This would seem to suggest that protocol buffers are ready for use with the many existing Java reflection based serialization libraries, but actually I don't think they mean reflection in the traditional Java sense of the word.

E.g. if I attempt to serialize one of my protocol buffer messages with XStream (a popular library for serializing Java objects to XML using reflection), I get:

```<code><com.x.MyProtos_-MyMessage resolves-to="com.google.protobuf.GeneratedMessageLite$SerializedForm">
    <messageClassName>com.x.MyProtos$MyMessage</messageClassName>
    <asBytes>CjkKDkJXQkUwMDAzNzkzMTA3EgsZAAAAAAAA8D8gASIGEJYBGMIDKhIpuB6F61G4nj8xuB6F61G4
Xnj8KMQoGQURBQkliEgsZAAAAAAAA8D8gASIGEJYBGMIDKhIpuB6F61G4nj8xuB6F61G4nj8qAyDQ
Dw==</asBytes>
</code>```

[ I notice the XML mentions GeneratedMessageLite, i.e. a subclass of MessageLite, even though the instance that was serialized was an instanceof com.google.protobuf.Message ]

The only existing solution for serializing protocol buffers to XML (such that the result is somewhat human readable) that I found was protobuf-java-format.

This produces nice output - however as it doesn't output the tag values, i.e. the numeric ids of the fields. So it doesn't look like the resulting XML would be very robust when it comes to deserialization, i.e. as far as I understand, with the standard protocol buffer serialization things will continue working fine if you change the field names, but keep the tag values the same, and then try to deserialize a byte sequence that was serialized before these changes.

Has anyone come across an XML serialization solution that keeps most of the attractive features of protocol buffers (with just the penalty of slower serialization time and larger resulting messages)?

Or worked out how to take advantage of the "reflection" features of protocol buffers with one of the popular existing Java XML serialization libraries?

Regards,

/George

PS if you're wondering why I want to serialize to XML it's because I want a cheap (in programming terms) way to manually edit messages under certain circumstances.

答:
Protostuff is another Protobuf-compatible library that supports serializing to JSON in "numeric" mode.

http://code.google.com/p/protostuff/wiki/JsonSerialization

Title: Serializing protocol buffers to XML?

Body:
The protocol buffers Java tutorial states:

One key feature provided by protocol message classes is reflection. [...] One very useful way to use reflection is for converting protocol messages to and from other encodings, such as XML or JSON.

And if you look at com.google.protobuf.Message it says:

The biggest added features [of the Message class over the MessageLite class] are introspection and reflection.

This would seem to suggest that protocol buffers are ready for use with the many existing Java reflection based serialization libraries, but actually I don't think they mean reflection in the traditional Java sense of the word.

E.g. if I attempt to serialize one of my protocol buffer messages with XStream (a popular library for serializing Java objects to XML using reflection), I get:

<com.x.MyProtos_-MyMessage resolves-to="com.google.protobuf.GeneratedMessageLite$SerializedForm">
    <messageClassName>com.x.MyProtos$MyMessage</messageClassName>
    <asBytes>CjkKDkJXQkUwMDAzNzkzMTA3EgsZAAAAAAAA8D8gASIGEJYBGMIDKhIpuB6F61G4nj8xuB6F61G4
Xnj8KMQoGQURBQkliEgsZAAAAAAAA8D8gASIGEJYBGMIDKhIpuB6F61G4nj8xuB6F61G4nj8qAyDQ
Dw==</asBytes>

[ I notice the XML mentions GeneratedMessageLite, i.e. a subclass of MessageLite, even though the instance that was serialized was an instanceof com.google.protobuf.Message ]

The only existing solution for serializing protocol buffers to XML (such that the result is somewhat human readable) that I found was protobuf-java-format.

This produces nice output - however as it doesn't output the tag values, i.e. the numeric ids of the fields. So it doesn't look like the resulting XML would be very robust when it comes to deserialization, i.e. as far as I understand, with the standard protocol buffer serialization things will continue working fine if you change the field names, but keep the tag values the same, and then try to deserialize a byte sequence that was serialized before these changes.

Has anyone come across an XML serialization solution that keeps most of the attractive features of protocol buffers (with just the penalty of slower serialization time and larger resulting messages)?

Or worked out how to take advantage of the "reflection" features of protocol buffers with one of the popular existing Java XML serialization libraries?

Regards,

/George

PS if you're wondering why I want to serialize to XML it's because I want a cheap (in programming terms) way to manually edit messages under certain circumstances.


问:
How can I catch a marshalling error in Go?
I have an API that is expecting a "username":"string" request body, I am unmarshalling the request body into a user struct that matches what I am expecting. My code does not throw an error on mismatched struct data. Is there a function I could use instead of json.Unmarshal? If not how would I be able to catch a 400 error in this case?  (I have also tried using json.decoder)

Here is my code:

```<code>type User struct {
   Username string `json:"username" gorm:"primary_key;Column:username"`
}

var user models.User

body, err := ioutil.ReadAll(r.Body)
if err = json.Unmarshal(body, &user); err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}
</code>```

答:
If you want to both ensure that the key "username" is present, and that other fields are not, you would need to implement the Unmarshaler interface, and iterate over all of the received keys.

```<code>func (user *User) UnmarshalJSON(data []byte) (error) {
    d := make(map[string]interface{})
    err = json.Unmarshal(data, &d)
    if err != nil {
        return err
    }
    if _, ok := d["username"]; !ok {
        return fmt.Errorf("username is required")
    }
    for k, v := range d {
        if k == "username" {
            username, ok := v.(string)
            if !ok {
                return fmt.Errorf("username must be a string, got %T", v)
            }
            user.Username = username
        } else {
            return fmt.Errorf("Unexpected key %s", k)
        }
    }
    return
}
</code>```

Body:
I have an API that is expecting a "username":"string" request body, I am unmarshalling the request body into a user struct that matches what I am expecting. My code does not throw an error on mismatched struct data. Is there a function I could use instead of json.Unmarshal? If not how would I be able to catch a 400 error in this case?  (I have also tried using json.decoder)

Here is my code:

type User struct {
   Username string `json:"username" gorm:"primary_key;Column:username"`
}

var user models.User

body, err := ioutil.ReadAll(r.Body)
if err = json.Unmarshal(body, &user); err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
}

Body:
If you want to both ensure that the key "username" is present, and that other fields are not, you would need to implement the Unmarshaler interface, and iterate over all of the received keys.

func (user *User) UnmarshalJSON(data []byte) (error) {
    d := make(map[string]interface{})
    err = json.Unmarshal(data, &d)
    if err != nil {
        return err
    }
    if _, ok := d["username"]; !ok {
        return fmt.Errorf("username is required")
    }
    for k, v := range d {
        if k == "username" {
            username, ok := v.(string)
            if !ok {
                return fmt.Errorf("username must be a string, got %T", v)
            }
            user.Username = username
        } else {
            return fmt.Errorf("Unexpected key %s", k)
        }
    }
    return
}


问:
How does setting instance variable public and not using setter method might break collaborators' code who are using my class in java?
I found the following passage in the book "Headfirst java". I don't understand the bolded part in the below passage.

Object: The point to setters (and getters, too) is that you can change
  your mind later, without breaking anybody else's code! Imagine if half
  the people in your com- pany used your class with public instance
  variables, and one day you suddenly realized,
  " Oops - there's something I didn't plan for with that value, I'm going to have to switch to a setter method." You break everyone's
  code. The cool thing about encapsulation is that you get to change
  your mind. And nobody gets hurt. The performance gains from using
  variables directly is so miniscule and would rarely be worth it.

答: The internal representation of that value may change and require a new type be used, which could be hidden from other code using getter/setter methods.</p>


问:
Is there any difference between `xtratim` and overriding p3?
According to reference csound manual, one should use xtratim (or opcodes that implicitly use it e.g. madsr) when writing instruments that respond to MIDI since the duration of the key/note is not know in advance (for live performances).

However, I also noted in an external example that one can override p3 (the score note length) from within the instrument code. So, is there any difference between doing this and using xtratim?

答:
Since xtratim gets an i-arg for the extra time, I was hoping that changing p3 would be more flexible, but that's not actually the case...

For starters, p3 is treated as an i-var, i.e. it's only assignable on the initial pass, so something like

```<code>instr 1
if p3 < 9 then
  p3 = p3 + 1 ; runs only once
  printk 0.1, p3
endif
endin
</code>```

will only run for three seconds if called from the score as

```<code>i1 0 2
</code>```

This much was to be expected. On the other hand the following hack that calls reinit to [re]run the initialization phase does update p3 more than once, but this has zero effect on the note play time, i.e. only the first ("real init") changes the actual note duration... the perf-time reinits, while changing p3 as read from the instrument, don't have any effect on the note play duration, i.e.

```<code>top:
p3  = p3 + 1
printk 0.1, p3
if p3 < 9 then
  reinit top
endif
</code>```

still plays for exactly 3 seconds with the same score (even if I make sure Csound runs long enough), i.e. with:

```<code>i1 0 2
e 10
</code>```

although the printk does display p3 as reaching the value 9 with the latter instrument...

As for xtratim it doesn't change p3 at all, the "extra time" is implemented outside this as Steven' Yi's answer correctly points out.

Looking at the source code for xtratim, it is actually possible to extend the "extra time", by calling xtratim several times, with ever increasing values, but not shorten it...

```<code>int32_t xtratim(CSOUND *csound, XTRADUR *p)
{
    IGN(csound);
    int32_t *xtra = &(p->h.insdshead->xtratim);
    int32_t tim = (int32_t)(*p->extradur * p->h.insdshead->ekr);
    if (*xtra < tim)  /* gab-a5 revised */
      *xtra = tim;
    return OK;
}
</code>```

So armed with this info, I tried

```<code>ixtr = 0
top:
ixtr += 1
xtratim ixtr
print ixtr
if ixtr < 8 then
  reinit top
endif
</code>```

And lo and behold, the latter hack does work, i.e. this latter code actually extends the instrument/note play time to 10 seconds using the previous score. So it's possible to extend the note programmatically this way from inside the instrument at perf time, for as much as you want, unlike hacking p3.

For those curious, xtratim even takes effect (properly) on play (actually release) time even if called after release has been asserted, i.e. even from the "release segment", e.g.

```<code>xtratim 1
kflag release
kdone init 0
if (kflag == 1) && (kdone == 0)  then
  kdone = 1
  reinit more
  more:
  xtratim 4
endif
</code>```

will give 4 extra seconds of play. Given this, I'm not sure if p3 updates being ignored during perf time is a bug or "by design".

Body:
Since xtratim gets an i-arg for the extra time, I was hoping that changing p3 would be more flexible, but that's not actually the case...

For starters, p3 is treated as an i-var, i.e. it's only assignable on the initial pass, so something like

instr 1
if p3 < 9 then
  p3 = p3 + 1 ; runs only once
  printk 0.1, p3
endif
endin

will only run for three seconds if called from the score as

i1 0 2

This much was to be expected. On the other hand the following hack that calls reinit to [re]run the initialization phase does update p3 more than once, but this has zero effect on the note play time, i.e. only the first ("real init") changes the actual note duration... the perf-time reinits, while changing p3 as read from the instrument, don't have any effect on the note play duration, i.e.

top:
p3  = p3 + 1
printk 0.1, p3
if p3 < 9 then
  reinit top
endif

still plays for exactly 3 seconds with the same score (even if I make sure Csound runs long enough), i.e. with:

i1 0 2
e 10

although the printk does display p3 as reaching the value 9 with the latter instrument...

As for xtratim it doesn't change p3 at all, the "extra time" is implemented outside this as Steven' Yi's answer correctly points out.

Looking at the source code for xtratim, it is actually possible to extend the "extra time", by calling xtratim several times, with ever increasing values, but not shorten it...

int32_t xtratim(CSOUND *csound, XTRADUR *p)
{
    IGN(csound);
    int32_t *xtra = &(p->h.insdshead->xtratim);
    int32_t tim = (int32_t)(*p->extradur * p->h.insdshead->ekr);
    if (*xtra < tim)  /* gab-a5 revised */
      *xtra = tim;
    return OK;
}

So armed with this info, I tried

ixtr = 0
top:
ixtr += 1
xtratim ixtr
print ixtr
if ixtr < 8 then
  reinit top
endif

And lo and behold, the latter hack does work, i.e. this latter code actually extends the instrument/note play time to 10 seconds using the previous score. So it's possible to extend the note programmatically this way from inside the instrument at perf time, for as much as you want, unlike hacking p3.

For those curious, xtratim even takes effect (properly) on play (actually release) time even if called after release has been asserted, i.e. even from the "release segment", e.g.

xtratim 1
kflag release
kdone init 0
if (kflag == 1) && (kdone == 0)  then
  kdone = 1
  reinit more
  more:
  xtratim 4
endif

will give 4 extra seconds of play. Given this, I'm not sure if p3 updates being ignored during perf time is a bug or "by design".


问:
Why adding only multiDexEnabled works fine
Recently I've been struggling with multidexing in android and this question comes to my mind:

To enable multiDex in android project

If you only and only add this line:

```<code>// gradle build config
multiDexEnabled true
</code>```

The app will compile and works fine.

But the real solution is to:

Add multiDexEnabled true

Add the support library androidx.multidex

Override Application class.

Why adding only multiDexEnabled true works and project runs successfully? What about the other two steps remained

Am I not considering something?

BTW, my minSdkVersion is 15

答:
This happens when your App has exceeded the methods/dex size limit (64K).

As your minSdk is 15, you have to add MultiDex manually which is not required on Api 21+.

Do the following for supporting MultiDex on Pre-21

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}

Make your application class extend MultiDexApplication

```<code>public class Application extends MultiDexApplication {}
</code>```

Or else you can use Proguard to strip off unused classes and methods if you don't want to use MultiDex at all..

Body:
Recently I've been struggling with multidexing in android and this question comes to my mind:

To enable multiDex in android project

If you only and only add this line:

// gradle build config
multiDexEnabled true

The app will compile and works fine.

But the real solution is to:

Add multiDexEnabled true

Add the support library androidx.multidex

Override Application class.

Why adding only multiDexEnabled true works and project runs successfully? What about the other two steps remained

Am I not considering something?

BTW, my minSdkVersion is 15

Body:
This happens when your App has exceeded the methods/dex size limit (64K).

As your minSdk is 15, you have to add MultiDex manually which is not required on Api 21+.

Do the following for supporting MultiDex on Pre-21

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}

Make your application class extend MultiDexApplication

public class Application extends MultiDexApplication {}

Or else you can use Proguard to strip off unused classes and methods if you don't want to use MultiDex at all..


问:
MVC - Partially update the model in the view
Heres the scenario: I have a User object like this:

```<code> public class User : BaseEntity<User>, IAggregateRoot
 {
    public virtual string Name { get; set; }
    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    public virtual string SecretQuestion { get; set; }
    public virtual string SecretAnswer { get; set; }
    public virtual DateTime LastLogin { get; set; }
 }
</code>```

During the editing of this object, i load it into the view, but i only want to update some of the properties (ie i wouldnt want to update LastLogin property). In this situation what would i do?

Is the best strategy to create a user viewmodel, and will nhibernate cope with this when i try to update a user object with a null LastLogin field?

Thanks in advance.

EDIT

Something like this:

```<code>public class UserViewModel
{
  public string Name {get;set;}
  public string UserName {get;set;}
  public string Password {get;set;}
  public string SecretQuestion {get;set;}
  public string SecretAnswer {get;set;}
}
</code>```

And then the editing:

```<code>public ActionResult Edit(int id)
{
  return View(_userRepository.FindById(id));
}

[HttpPost]
public ActionResult Edit(int id, UserViewModel userViewModel)
{
  try
  {

    //Not sure how to update the model
    //with the view Model and save.

    _userRepository.Update(????);
    return RedirectToAction("Index");
  }
  catch
  {
    return View();
  }
}
</code>```

答:
A good approach is to create a UserViewModel with only the properties you want to display/update.  Don't let nHibernate know about the view model.  Then, when the edits are posted back to your controller you retrieve the actual User object from nHibernate, update it's properties from the view model, and then save it back to the database.

Update

Something like this:

```<code>[HttpPost]
public ActionResult Edit(int id, UserViewModel userViewModel)
{
  try
  {
    User model = _userRepository.FindById(id);

    model.Name = userViewModel.Name;
    model.Username = userViewModel.Username;
    model.Password = userViewModel.Password;
    model.SecretQuestion = userViewModel.SecretQuestion;
    model.SecretAnswer = userViewModel.SecretAnswer;

    _userRepository.Update(model);
    return RedirectToAction("Index");
  }
  catch
  {
    return View();
  }
}
</code>```

In a project I've been working on recently I created a ViewModelBase class which includes methods that maps properties from a domain model to a view model and back again based on matching the property name and type.  All my view models are derived from ViewModelBase.

There are other tools like AutoMapper that do this sort of thing and much, much more.

Body:
Heres the scenario: I have a User object like this:

 public class User : BaseEntity<User>, IAggregateRoot
 {
    public virtual string Name { get; set; }
    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    public virtual string SecretQuestion { get; set; }
    public virtual string SecretAnswer { get; set; }
    public virtual DateTime LastLogin { get; set; }
 }

During the editing of this object, i load it into the view, but i only want to update some of the properties (ie i wouldnt want to update LastLogin property). In this situation what would i do?

Is the best strategy to create a user viewmodel, and will nhibernate cope with this when i try to update a user object with a null LastLogin field?

Thanks in advance.

EDIT

Something like this:

public class UserViewModel
{
  public string Name {get;set;}
  public string UserName {get;set;}
  public string Password {get;set;}
  public string SecretQuestion {get;set;}
  public string SecretAnswer {get;set;}
}

And then the editing:

public ActionResult Edit(int id)
{
  return View(_userRepository.FindById(id));
}

[HttpPost]
public ActionResult Edit(int id, UserViewModel userViewModel)
{
  try
  {

    //Not sure how to update the model
    //with the view Model and save.

    _userRepository.Update(????);
    return RedirectToAction("Index");
  }
  catch
  {
    return View();
  }
}

Body:
A good approach is to create a UserViewModel with only the properties you want to display/update.  Don't let nHibernate know about the view model.  Then, when the edits are posted back to your controller you retrieve the actual User object from nHibernate, update it's properties from the view model, and then save it back to the database.

Update

Something like this:

[HttpPost]
public ActionResult Edit(int id, UserViewModel userViewModel)
{
  try
  {
    User model = _userRepository.FindById(id);

    model.Name = userViewModel.Name;
    model.Username = userViewModel.Username;
    model.Password = userViewModel.Password;
    model.SecretQuestion = userViewModel.SecretQuestion;
    model.SecretAnswer = userViewModel.SecretAnswer;

    _userRepository.Update(model);
    return RedirectToAction("Index");
  }
  catch
  {
    return View();
  }
}

In a project I've been working on recently I created a ViewModelBase class which includes methods that maps properties from a domain model to a view model and back again based on matching the property name and type.  All my view models are derived from ViewModelBase.

There are other tools like AutoMapper that do this sort of thing and much, much more.


问:
Issue with migrate on server
I have deployed my django project to a digital ocean server and sucessfully installed all requirements. However, when I run migrate, after makemigrations, I get the following exception:

```<code>django.db.utils.ProgrammingError: relation "auth_permission" already exists

Operations to perform:
  Synchronize unmigrated apps: formtools, django_filters, djcelery, storages
  Apply all migrations: sessions, admin, sites, auth, contenttypes, directory, easy_thumbnails
Synchronizing apps without migrations:
  Creating tables...
    Creating table celery_taskmeta
    Creating table celery_tasksetmeta
    Creating table djcelery_intervalschedule
    Creating table djcelery_crontabschedule
    Creating table djcelery_periodictasks
    Creating table djcelery_periodictask
    Creating table djcelery_workerstate
    Creating table djcelery_taskstate
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying contenttypes.0001_initial... FAKED
  Applying auth.0001_initial...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 262, in create_model
    self.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 103, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_permission" already exists
</code>```

How can I fix this  - please help!

答:
You shouldn't need to upgrade Django manually - the Django will be upgraded automatically along with other dependencies when you update tendenci with

```<code>pip install -r requirements/tendenci.txt --upgrade
</code>```

or just

```<code>pip install -r requirements.txt --upgrade
</code>```

Please uninstall Django and djcelery then run the above command. You might need to fake djcelery 0001.

```<code>python manage.py migrate djcelery 0001 --fake
</code>```

Please note that tendenci is currently compatible to Django 1.8.x.

Title: Issue with migrate on server

Body:
I have deployed my django project to a digital ocean server and sucessfully installed all requirements. However, when I run migrate, after makemigrations, I get the following exception:

django.db.utils.ProgrammingError: relation "auth_permission" already exists

Operations to perform:
  Synchronize unmigrated apps: formtools, django_filters, djcelery, storages
  Apply all migrations: sessions, admin, sites, auth, contenttypes, directory, easy_thumbnails
Synchronizing apps without migrations:
  Creating tables...
    Creating table celery_taskmeta
    Creating table celery_tasksetmeta
    Creating table djcelery_intervalschedule
    Creating table djcelery_crontabschedule
    Creating table djcelery_periodictasks
    Creating table djcelery_periodictask
    Creating table djcelery_workerstate
    Creating table djcelery_taskstate
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying contenttypes.0001_initial... FAKED
  Applying auth.0001_initial...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 262, in create_model
    self.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 103, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "auth_permission" already exists

How can I fix this  - please help!

Body:
You shouldn't need to upgrade Django manually - the Django will be upgraded automatically along with other dependencies when you update tendenci with

pip install -r requirements/tendenci.txt --upgrade

or just

pip install -r requirements.txt --upgrade

Please uninstall Django and djcelery then run the above command. You might need to fake djcelery 0001.

python manage.py migrate djcelery 0001 --fake

Please note that tendenci is currently compatible to Django 1.8.x.


问:
MSTest: CS0117 'Assert' does not contain a definition for 'ThrowsException'
I'm writing some unit tests with MSTest, using C#, MSVS 2015 and .Net 4.6.1.

This line:

```<code>Assert.ThrowsException<ArgumentOutOfRangeException>( () =>
  select.AllSelectedOptions[0]
);
</code>```

Fails with this compile error:

CS0117 'Assert' does not contain a definition for 'ThrowsException'

My namespace is Microsoft.VisualStudio.TestTools.UnitTesting (the default when you create a unit test project in MSVS).

According to the documentation, Assert.ThrowsException(Action) should exist.  But I don't see it in Intellisense ... and I'm getting the compile error.

I've tried a couple of different versions of MSVS (MSVS 2015 and MSVS 2019) and a couple of different versions of MSTest.

Q: Any ideas what might be wrong?

As Clint said below, I need to install MSTest v2 from NuGet in order to use Assert.ThrowsException<T>() in MSVS 2015.

But after doing this, MSVS isn't finding any of my tests anymore:

MSVS > Test > Run All (or "Test > Debug > All Tests"):

```<code>------ Discover test started ------
========== Discover test finished: 0 found (0:00:01.127375) ==========
</code>```

Any suggestions?

答:
You need to use [MSTest V2] to be able to Assert.ThrowsException

Starting with VS2017, the in-box Unit Test Project templates use only MSTest V2.

Now that you're on VS2015 you can install this package MSTest.Test from Nuget but make sure to remove the old test references like Microsoft.VisualStudio.QualityTools.UnitTestFramework before upgrading to this package

Add > New Test project > Select MSTest project type

After this you should be able to use Assert.ThrowsException<ArgumentOutOfRangeException>(

To discover and execute tests also ensure to install MSTest.TestAdapter.

Further Reading

Body:
I'm writing some unit tests with MSTest, using C#, MSVS 2015 and .Net 4.6.1.

This line:

Assert.ThrowsException<ArgumentOutOfRangeException>( () =>
  select.AllSelectedOptions[0]
);

Fails with this compile error:

CS0117 'Assert' does not contain a definition for 'ThrowsException'

My namespace is Microsoft.VisualStudio.TestTools.UnitTesting (the default when you create a unit test project in MSVS).

According to the documentation, Assert.ThrowsException(Action) should exist.  But I don't see it in Intellisense ... and I'm getting the compile error.

I've tried a couple of different versions of MSVS (MSVS 2015 and MSVS 2019) and a couple of different versions of MSTest.

Q: Any ideas what might be wrong?

As Clint said below, I need to install MSTest v2 from NuGet in order to use Assert.ThrowsException<T>() in MSVS 2015.

But after doing this, MSVS isn't finding any of my tests anymore:

MSVS > Test > Run All (or "Test > Debug > All Tests"):

------ Discover test started ------
========== Discover test finished: 0 found (0:00:01.127375) ==========

Any suggestions?


问:
Inner Join returning wrong number of results
My query is returning 54 rows when it should return 59. I feel like I only need the Inner join because I wouldn't want to include NULL values in my results. I've also tried doing Left Outer Joins to filter out some of the non matching values but it returns too many results (62). I'm using DISTINCT so Duplicates shouldn't be the issue.

The query I'm trying to Create:

"List all ingredient classes and the titles of any recipes that use at least one
ingredient of that class, if any. Eliminate all duplicates. (2 columns, 59 rows)"

My Code:

```<code>select DISTINCT Ingredients.IngredientClassID, Recipes.RecipeTitle
from Ingredients
Inner join Recipe_Ingredients on Ingredients.IngredientID =
Recipe_Ingredients.IngredientID
Inner join Recipes on Recipe_Ingredients.RecipeID = Recipes.RecipeID;
</code>```

Link to a DB Fiddle I setup

Diagram of Database:

答:
I think 54 rows is the correct output. My query gave the same number of rows.

```<code>FROM Ingredient_Classes ic
    LEFT JOIN Ingredients i ON i.IngredientClassID = ic.IngredientClassID
    LEFT JOIN Recipe_Ingredients ri ON ri.ingredientId = i.ingredientId
    JOIN recipes r ON r.recipeid = ri.recipeId
WHERE i.ingredientId IS NOT NULL
GROUP BY ic.IngredientClassDescription, r.recipetitle
ORDER BY recipetitle;
</code>```

You can select distinct(recipe.title) and see that all recipes are present in the output. So I don't think we missed anything.

Body:
My query is returning 54 rows when it should return 59. I feel like I only need the Inner join because I wouldn't want to include NULL values in my results. I've also tried doing Left Outer Joins to filter out some of the non matching values but it returns too many results (62). I'm using DISTINCT so Duplicates shouldn't be the issue.

The query I'm trying to Create:

"List all ingredient classes and the titles of any recipes that use at least one
ingredient of that class, if any. Eliminate all duplicates. (2 columns, 59 rows)"

My Code:

select DISTINCT Ingredients.IngredientClassID, Recipes.RecipeTitle
from Ingredients
Inner join Recipe_Ingredients on Ingredients.IngredientID =
Recipe_Ingredients.IngredientID
Inner join Recipes on Recipe_Ingredients.RecipeID = Recipes.RecipeID;

Link to a DB Fiddle I setup

Diagram of Database:

Body:
I think 54 rows is the correct output. My query gave the same number of rows.

FROM Ingredient_Classes ic
    LEFT JOIN Ingredients i ON i.IngredientClassID = ic.IngredientClassID
    LEFT JOIN Recipe_Ingredients ri ON ri.ingredientId = i.ingredientId
    JOIN recipes r ON r.recipeid = ri.recipeId
WHERE i.ingredientId IS NOT NULL
GROUP BY ic.IngredientClassDescription, r.recipetitle
ORDER BY recipetitle;

You can select distinct(recipe.title) and see that all recipes are present in the output. So I don't think we missed anything.


问:
Swapping user integer input for a variable so that it incrementally increases and decreases
As the title says, I'm trying to replace the "i" variable listed with what a user inputs so that it'll incrementally increase and decrease based off of whatever they put in for the base integer when prompted. Basically I want my "for" loops to base the increment off of whatever the speed integer entered is.

I've tried inputting various things but clearly I don't know what I'm doing or clearly what those particular are. Also I have no idea what the standards are for writing Java so I apologize for the sloppy code.

Here is my actual objective:

2. Car Class

Write a class named car that has the following fields:

yearModal. The yearModel field is an int that holds the car's year model.

maka. The make field references a String object that holds the make of the car.

speed. The speed field is an int that holds the car's current speed.

In addition, the class should have the following constructor and other methods.

Constructor. The constructor should accept the car's year model and make as arguments. These values should be assigned to the object's yearModel and make fields. The constructor should also assign 0 to the speed field.

Accessor. Appropriate accessor methods should get the values stored in an object's yearModel, make, and speed fields.

accelerate. The accelerate method should add 5 to the speed field each time it is called.

brake. The brake method should subtract 5 from the speed field each time it is called.

Demonstrate the class in a program that creates a Car object, and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times. After each call to the brake method, get the current speed of the car and display it.

```<code>import java.util.Scanner;

public class CarProgramAssignment {
    int yearModel;
    String make;
    int speed;

    CarProgramAssignment(int yearModel, String make) {
        this.yearModel = yearModel;
        this.make = make;
        this.speed = 0;
    }

    int getYearModel()
    {
      return yearModel;
    }

    String getMake() {
      return make;
    }

    int getSpeed() {
      return speed;
    }

    void Accelerate() {
       this.speed = this.speed + 5;
    }

    void Brake() {
    this.speed = this.speed - 5;
    }

     public static void main(String[] args)
    {

     Scanner input = new Scanner( System.in );

      // This displays the current status
      System.out.println("Current status of the car:");
      System.out.println("Car Year: ");

      int carMakeYear = input.nextInt();

      input.nextLine();

      System.out.println("Car Make: ");
      String carModel = input.nextLine();

      System.out.println("Speed: ");

      int speed = input.nextInt();

     CarProgramAssignment car = new CarProgramAssignment(1, "Audi R8");
     for(int i=0;i<5;i++) {
     car.Accelerate();
     }

     System.out.printf("After accelerating 5 times, the speed is = %d km/h\n", car.getSpeed());
     for(int i=0;i<5;i++) {
        car.Brake();
     }

     System.out.println("After braking 5 times, the speed is = "+car.getSpeed());

    }
}
</code>```

Edit: I cleaned up some things and tried to clarify it a bit more.

答:
Alright so I sort of figured it out. I created 2 classes and started over and this sort of works now.

Here is my first class:

```<code>public class carclass1 {//Start of Class

    private int yearModel; //an int that holds the car's year model
    private String make; //references a string object that holds the make of the car
    private int speed; //an int that holds the car's speed.

    public int getYearModel() {
        return yearModel;
    }

    public String getMake(){
        return make; //This is the field of the particular object
    }

    public int getSpeed(){
        return speed;
    }

    public void accelerate() {
        speed = speed + 5;
    }

    public void brake() {
        speed = speed - 5;
    }

    Scanner input = new Scanner(System.in);

    public carclass1( int yearModelGiven, String makeGiven ){
        yearModel = yearModelGiven;
        make = makeGiven;
        System.out.println("Please enter in the initial speed of the car:");
        speed = input.nextInt();
    }
}
</code>```

SECOND CLASS:

```<code>public class carclass2{

    public static void main(String [] args ) { //this is a main method

        Scanner input = new Scanner( System.in );

        System.out.println("What is the vehicle year: ");

        int carYear;
        carYear = input.nextInt();

        System.out.println( "The vehicle year is "+ carYear + " (type a number on the` next prompt to proceed");
        carYear = input.nextInt();

        System.out.println( "What is the vehicle make: ");

        input.nextLine(); /*The purpose for this is to skip to the next prompt
        * I couldn't find another way around why my code won't work without it.*/
        String carMake1;
        carMake1 = input.nextLine();

        System.out.println( "The vehicle make is "+ carMake1);

        carclass1 car1 = new carclass1( carYear, "Honda" );

        System.out.println( "Accelerating the vehicle now:" );
        for( int seconds = 1; seconds <= 5; seconds++ ) {
            car1.accelerate();
            System.out.println( "The current speed of the" + " " + car1.getYearModel() + " " + car1.getMake() + " is " +
                      car1.getSpeed() + " km/h" );
        }

        // This is now the braking method
        System.out.println( "Braking the vehicle now:" );
        for (int seconds = 1; seconds <= 5; seconds++ ) {
             car1.brake();
             System.out.println( "The current speed of the" + " " + car1.getYearModel() + " " + car1.getMake() + " is " +
                      car1.getSpeed() + " km/h" );
        }
    }
}
</code>```

Body:
As the title says, I'm trying to replace the "i" variable listed with what a user inputs so that it'll incrementally increase and decrease based off of whatever they put in for the base integer when prompted. Basically I want my "for" loops to base the increment off of whatever the speed integer entered is.

I've tried inputting various things but clearly I don't know what I'm doing or clearly what those particular are. Also I have no idea what the standards are for writing Java so I apologize for the sloppy code.

Here is my actual objective:

2. Car Class

Write a class named car that has the following fields:

yearModal. The yearModel field is an int that holds the car's year model.

maka. The make field references a String object that holds the make of the car.

speed. The speed field is an int that holds the car's current speed.

In addition, the class should have the following constructor and other methods.

Constructor. The constructor should accept the car's year model and make as arguments. These values should be assigned to the object's yearModel and make fields. The constructor should also assign 0 to the speed field.

Accessor. Appropriate accessor methods should get the values stored in an object's yearModel, make, and speed fields.

accelerate. The accelerate method should add 5 to the speed field each time it is called.

brake. The brake method should subtract 5 from the speed field each time it is called.

Demonstrate the class in a program that creates a Car object, and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times. After each call to the brake method, get the current speed of the car and display it.

import java.util.Scanner;

public class CarProgramAssignment {
    int yearModel;
    String make;
    int speed;

    CarProgramAssignment(int yearModel, String make) {
        this.yearModel = yearModel;
        this.make = make;
        this.speed = 0;
    }

    int getYearModel()
    {
      return yearModel;
    }

    String getMake() {
      return make;
    }

    int getSpeed() {
      return speed;
    }

    void Accelerate() {
       this.speed = this.speed + 5;
    }

    void Brake() {
    this.speed = this.speed - 5;
    }

     public static void main(String[] args)
    {

     Scanner input = new Scanner( System.in );

      // This displays the current status
      System.out.println("Current status of the car:");
      System.out.println("Car Year: ");

      int carMakeYear = input.nextInt();

      input.nextLine();

      System.out.println("Car Make: ");
      String carModel = input.nextLine();

      System.out.println("Speed: ");

      int speed = input.nextInt();

     CarProgramAssignment car = new CarProgramAssignment(1, "Audi R8");
     for(int i=0;i<5;i++) {
     car.Accelerate();
     }

     System.out.printf("After accelerating 5 times, the speed is = %d km/h\n", car.getSpeed());
     for(int i=0;i<5;i++) {
        car.Brake();
     }

     System.out.println("After braking 5 times, the speed is = "+car.getSpeed());

    }
}

Edit: I cleaned up some things and tried to clarify it a bit more.

Body:
Alright so I sort of figured it out. I created 2 classes and started over and this sort of works now.

Here is my first class:

public class carclass1 {//Start of Class

    private int yearModel; //an int that holds the car's year model
    private String make; //references a string object that holds the make of the car
    private int speed; //an int that holds the car's speed.

    public int getYearModel() {
        return yearModel;
    }

    public String getMake(){
        return make; //This is the field of the particular object
    }

    public int getSpeed(){
        return speed;
    }

    public void accelerate() {
        speed = speed + 5;
    }

    public void brake() {
        speed = speed - 5;
    }

    Scanner input = new Scanner(System.in);

    public carclass1( int yearModelGiven, String makeGiven ){
        yearModel = yearModelGiven;
        make = makeGiven;
        System.out.println("Please enter in the initial speed of the car:");
        speed = input.nextInt();
    }
}

SECOND CLASS:

public class carclass2{

    public static void main(String [] args ) { //this is a main method

        Scanner input = new Scanner( System.in );

        System.out.println("What is the vehicle year: ");

        int carYear;
        carYear = input.nextInt();

        System.out.println( "The vehicle year is "+ carYear + " (type a number on the` next prompt to proceed");
        carYear = input.nextInt();

        System.out.println( "What is the vehicle make: ");

        input.nextLine(); /*The purpose for this is to skip to the next prompt
        * I couldn't find another way around why my code won't work without it.*/
        String carMake1;
        carMake1 = input.nextLine();

        System.out.println( "The vehicle make is "+ carMake1);

        carclass1 car1 = new carclass1( carYear, "Honda" );

        System.out.println( "Accelerating the vehicle now:" );
        for( int seconds = 1; seconds <= 5; seconds++ ) {
            car1.accelerate();
            System.out.println( "The current speed of the" + " " + car1.getYearModel() + " " + car1.getMake() + " is " +
                      car1.getSpeed() + " km/h" );
        }

        // This is now the braking method
        System.out.println( "Braking the vehicle now:" );
        for (int seconds = 1; seconds <= 5; seconds++ ) {
             car1.brake();
             System.out.println( "The current speed of the" + " " + car1.getYearModel() + " " + car1.getMake() + " is " +
                      car1.getSpeed() + " km/h" );
        }
    }
}


问:
jquery attr works but animate fails
I have an svg line with id='slope'. I want to change the slope by altering the y1 and y2 values. This works fine:

```<code>$('#slope').attr({y1:10});
$('#slope').attr({y2:30});
</code>```

As expected, the line changes angle so it starts from y=10 and ends at y=30. However, I cannot animate it. This gives me an error claiming that y1 and y2 are read-only attributes:

```<code>$('#slope').animate({y1:10});
$('#slope').animate({y2:30});
</code>```

Is this a bug in jquery or is jquery unable to animate y1 and y2 of a line. I tested this with the cx and cy attributes for circles and it works fine. So, I know that jquery can animate position of svg elements. For some reason, it cannot do lines from what I am seeing.

I am using jquery 3.4.1, in case this is a bug.

答:
The description of JQuery's animate is:

Description: Perform a custom animation of a set of CSS properties.

Whereas the x and y attributes of an SVG line are exactly that, attributes.

A future specification may convert the ‘x1’, ‘y1’, ‘x2’, and ‘y2’ attributes to geometric properties. Currently, they can only be specified via element attributes, and not CSS.

They are not CSS properties and therefore jQuery won't animate them. If you want to animate lines you'll need to use SMIL or javascript (or a library that internally uses SMIL or javascript).

Somewhat confusingly the SVG 2 specification has made circle's cx and cy mapped CSS properties rather than attributes. In SVG 1.1 they too used to be attributes.

Title: jquery attr works but animate fails

Body:
I have an svg line with id='slope'. I want to change the slope by altering the y1 and y2 values. This works fine:

$('#slope').attr({y1:10});
$('#slope').attr({y2:30});

As expected, the line changes angle so it starts from y=10 and ends at y=30. However, I cannot animate it. This gives me an error claiming that y1 and y2 are read-only attributes:

$('#slope').animate({y1:10});
$('#slope').animate({y2:30});

Is this a bug in jquery or is jquery unable to animate y1 and y2 of a line. I tested this with the cx and cy attributes for circles and it works fine. So, I know that jquery can animate position of svg elements. For some reason, it cannot do lines from what I am seeing.

I am using jquery 3.4.1, in case this is a bug.


问:
Replace duplicate values from one DF to another DF
df1

```<code>ITEM      CATEGORY       COLOR

48684      CAR           RED
54519      BIKE          BLACK
14582      CAR           BLACK
45685      JEEP          WHITE
23661      BIKE          BLUE
23226      BIKE          BLUE
54252      BIKE          BLACK

</code>```

df2

```<code>    USERID  WEBBROWSE   ITEM     PURCHASE
1   1541    CHROME      54252    YES
2   3351    EXPLORER    54519    YES
3   2639    MOBILE APP  23661    YES

</code>```

df2 has many other columns.

The output I need is:

```<code>    USERID  WEBBROWSE   ITEM     PURCHASE
1   1541    CHROME      54519    YES
2   3351    EXPLORER    54519    YES
3   2639    MOBILE APP  23661    YES

</code>```

From df1 it is clear that ITEM 54252 and 54519 are the same. So based on df1 we need to replace the values in df2.

答:
I modify previous solution with new column orig for remember original values of ITEM, create Series by DataFrame.set_index and Series.replace values in another DataFrame:

```<code>df = df1.assign(orig=df1['ITEM'])
m = df.duplicated(['CATEGORY', 'COLOR'], keep=False)
df.loc[m, 'ITEM'] = df[m].groupby(['CATEGORY', 'COLOR'])['ITEM'].transform('first')

s = df[m].set_index('orig')['ITEM']
print (s)
orig
54519    54519
23661    23661
23226    23661
54252    54519
Name: ITEM, dtype: int64

df2['ITEM'] = df2['ITEM'].replace(s)
print (df2)
   USERID   WEBBROWSE   ITEM PURCHASE
1    1541      CHROME  54519      YES
2    3351    EXPLORER  54519      YES
3    2639  MOBILE APP  23661      YES
</code>```

Another alternative without new column is replace by dictionary:

```<code>orig = df1['ITEM']
m = df1.duplicated(['CATEGORY', 'COLOR'], keep=False)
df1.loc[m, 'ITEM'] = df1[m].groupby(['CATEGORY', 'COLOR'])['ITEM'].transform('first')
print (df1)
    ITEM CATEGORY  COLOR
0  48684      CAR    RED
1  54519     BIKE  BLACK
2  14582      CAR  BLACK
3  45685     JEEP  WHITE
4  23661     BIKE   BLUE
5  23661     BIKE   BLUE
6  54519     BIKE  BLACK

d = dict(zip(orig[m], df1.loc[m, 'ITEM']))
print (d)
{54519: 54519, 23661: 23661}

df2['ITEM'] = df2['ITEM'].replace(d)
print (df2)
   USERID   WEBBROWSE   ITEM PURCHASE
1    1541      CHROME  54252      YES
2    3351    EXPLORER  54519      YES
3    2639  MOBILE APP  23661      YES
</code>```

Body:
df1

ITEM      CATEGORY       COLOR

48684      CAR           RED
54519      BIKE          BLACK
14582      CAR           BLACK
45685      JEEP          WHITE
23661      BIKE          BLUE
23226      BIKE          BLUE
54252      BIKE          BLACK

df2

    USERID  WEBBROWSE   ITEM     PURCHASE
1   1541    CHROME      54252    YES
2   3351    EXPLORER    54519    YES
3   2639    MOBILE APP  23661    YES

df2 has many other columns.

The output I need is:

    USERID  WEBBROWSE   ITEM     PURCHASE
1   1541    CHROME      54519    YES
2   3351    EXPLORER    54519    YES
3   2639    MOBILE APP  23661    YES

From df1 it is clear that ITEM 54252 and 54519 are the same. So based on df1 we need to replace the values in df2.

Body:
I modify previous solution with new column orig for remember original values of ITEM, create Series by DataFrame.set_index and Series.replace values in another DataFrame:

df = df1.assign(orig=df1['ITEM'])
m = df.duplicated(['CATEGORY', 'COLOR'], keep=False)
df.loc[m, 'ITEM'] = df[m].groupby(['CATEGORY', 'COLOR'])['ITEM'].transform('first')

s = df[m].set_index('orig')['ITEM']
print (s)
orig
54519    54519
23661    23661
23226    23661
54252    54519
Name: ITEM, dtype: int64

df2['ITEM'] = df2['ITEM'].replace(s)
print (df2)
   USERID   WEBBROWSE   ITEM PURCHASE
1    1541      CHROME  54519      YES
2    3351    EXPLORER  54519      YES
3    2639  MOBILE APP  23661      YES

Another alternative without new column is replace by dictionary:

orig = df1['ITEM']
m = df1.duplicated(['CATEGORY', 'COLOR'], keep=False)
df1.loc[m, 'ITEM'] = df1[m].groupby(['CATEGORY', 'COLOR'])['ITEM'].transform('first')
print (df1)
    ITEM CATEGORY  COLOR
0  48684      CAR    RED
1  54519     BIKE  BLACK
2  14582      CAR  BLACK
3  45685     JEEP  WHITE
4  23661     BIKE   BLUE
5  23661     BIKE   BLUE
6  54519     BIKE  BLACK

d = dict(zip(orig[m], df1.loc[m, 'ITEM']))
print (d)
{54519: 54519, 23661: 23661}

df2['ITEM'] = df2['ITEM'].replace(d)
print (df2)
   USERID   WEBBROWSE   ITEM PURCHASE
1    1541      CHROME  54252      YES
2    3351    EXPLORER  54519      YES
3    2639  MOBILE APP  23661      YES