问:
Retrying messages with a timeout
We have to create a responder application as a windows service which will take messages off the queue, acknowledge the sender that we received them and that they are validated by sending a response back within 5 seconds. After we get another acknowledgement from the sender that we are okay to process the message, we process the message and send the result of that request back to them within another (5 sec). If at any point in that cycle either they or we do not get the message off the queue and respond within the time allotted the message will expire and we will need to re-try the message.

What we are having trouble with determining when messages will expire and need to be re-sent. I've been reading about putting them on the dead-letter queue, but I'm unsure that the purpose of it matches what we need. The dead-letter queue is not for items which just timeout, but failed in transmission. I've also read about using the Report option on the MQMessage itself to generate a report and possibly move it to a different queue which can be monitored. We'd then need to re-try the items that are on the new queue.

Are those my only two options if I need to monitor every incoming and outgoing message to ensure that we get a response from the other MQ server we are communicating with?

答:
I'd do it with message expiry and activity reporting in MQ, but that doesn't make it unnecessary for your applications to have a log of what they sent and received.

On every message you send, you could set an expiry time (meaning that the message will be discarded, if it is removed from the queue outside of that time frame). And by also setting the reporting option for getting reports when the message is discarded, the sender of the message (actually you can specify any queue for the reports not just one monitored by the sender) will get a report message identifying the discarded message, which can then be resent.

However the discarded message won't be put to any queue, the sending application needs to be able to resend the message from scratch.

And the processing side, when it's waiting on the 2nd message, it will need to have it's own "timer" for handling timeouts.

https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.1.0/com.ibm.mq.ref.dev.doc/q097490_.htm

https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.1.0/com.ibm.mq.mon.doc/q036600_.htm

All that said, it seems to me that you are not using MQ as intended and are trying to mimic a synchronous communication. MQ can gurantee exactly once delivery, so I'd say that if you have a properly configured and sized MQ route between your applications and properly set up message monitoring, then all this ack/nack is unnecessary.

Title: Retrying messages with a timeout


来源: stackexchange

问:
Return Date modified in Epoch ms using stat
I'm trying to get a list of file along with their modified time. I'm currently using find ~/Desktop -print0 | xargs -0 stat -f '%m %N' but this is only accurate to the second. Is there a way to format it for ms? I've tried google searches but a bit new to this and unsure of the terminology

答:
The default stat not giving milliseconds, you need to install coreutils :

```<code>brew install coreutils
</code>```

Then

```<code>find ~/Desktop -print0 | xargs -0 /usr/local/Cellar/coreutils/8.31/libexec/gnubin/stat --format='%.3Y %N'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The default stat not giving milliseconds, you need to install coreutils :

brew install coreutils

Then

find ~/Desktop -print0 | xargs -0 /usr/local/Cellar/coreutils/8.31/libexec/gnubin/stat --format='%.3Y %N'


问:
How to make 3 tables column in one column line?
I have the following 3 tables, but as you can see the columns are not in one line, i did the following CSS but still i get the same output. so how can i make the columns of different tables in one line and arrange them?

my HTML/CSS codes:

.calculated-value td {
  border: none;
}

div#time-div {
  margin-left: -4%;
  margin-right: -4%;
}

table.calculated-value tr td:first-child {
  border: none;
}

table.calculated-value tbody tr td:first-child h4 {
  font-weight: 300;
  letter-spacing: 3px;
}

table.calculated-value tbody tr td:not(:first-child) {
  font-weight: 600;
}

.calculated-value-title {
  letter-spacing: 5px;
  font-weight: 600 !important;
}

tr#time-row td {
  background-color: #22356d;
  width: 30px !important;
  text-align: left;
}

tr#time-row td:first-child {
  border-top-left-radius: 25px;
  border-bottom-left-radius: 25px;
  text-align: center;
}

tr#time-row td:last-child {
  border-top-right-radius: 25px;
  border-bottom-right-radius: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-md-9 offset-md-1" id="report-tables-container">
    <h4 class="text-center text-white font-weigh-bold calculated-value-title">FAIR MARKET VALUE </h4>
    <table class="table table-center text-white text-center calculated-value">
      <tbody>
        <tr>
          <td>
            <h4>INSTALLED</h4>
          </td>
          <td> 100
            <br>$149,350</td>
          <td> 100%
            <br>$149,350</td>
          <td> 100%
            <br>$149,350</td>

        </tr>
        <tr>
          <td>
            <h4>EXCHANGE</h4>
          </td>
          <td> 100
            <br>$149,350</td>
          <td> 100%
            <br>$149,350</td>

        </tr>
      </tbody>
    </table>
    <div id="time-div">
      <table class="table table-center  text-white text-center text-strong font-weight-bold calculated-value">
        <tbody>
          <tr id="time-row">
            <td>TIME (MONTHS)</td>
            <td> 0</td>
            <td> 12</td>
            <td> 24</td>

          </tr>
        </tbody>
      </table>

    </div>
    <h4 class="text-center text-white font-weight-bold calculated-value-title">LIQUIDATION VALUE</h4>
    <table class="table table-left text-white text-center calculated-value">
      <tbody>

        <tr>
          <td>
            <h4>ORDERLY</h4>
          </td>
          <td> 100
            <br>$149,350</td>
          <td> 100%
            <br>$149,350</td>
        </tr>
        <tr>
          <td>
            <h4>FORCED</h4>
          </td>
          <td> 100
            <br>$149,350</td>
          <td> 100%
            <br>$149,350</td>
          <td> 100%
            <br>$149,350</td>

        </tr>

      </tbody>
    </table>
  </div>
</div></code>```

Check this picture.

答:
Tables are not connected to each other in any way and will not align to each other automatically. CSS is a way to go to make them look consistent. This is approx way of doing it.

table {
  width: 100%;
}

th {
  text-align: left;
}

td {
  width: 9%;
}

td:first-child {
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Very long long long long long name</td>
        <td>Smith</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
    </tr>
</table>
<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
    </tr>
</table>
<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
    </tr>
</table></code>```

Body:
I have the following 3 tables, but as you can see the columns are not in one line, i did the following CSS but still i get the same output. so how can i make the columns of different tables in one line and arrange them?

my HTML/CSS codes:

.calculated-value td {
  border: none;
}

div#time-div {
  margin-left: -4%;
  margin-right: -4%;
}

table.calculated-value tr td:first-child {
  border: none;
}

table.calculated-value tbody tr td:first-child h4 {
  font-weight: 300;
  letter-spacing: 3px;
}

table.calculated-value tbody tr td:not(:first-child) {
  font-weight: 600;
}

.calculated-value-title {
  letter-spacing: 5px;
  font-weight: 600 !important;
}

tr#time-row td {
  background-color: #22356d;
  width: 30px !important;
  text-align: left;
}

tr#time-row td:first-child {
  border-top-left-radius: 25px;
  border-bottom-left-radius: 25px;
  text-align: center;
}

tr#time-row td:last-child {
  border-top-right-radius: 25px;
  border-bottom-right-radius: 25px;
}

FAIR MARKET VALUE

INSTALLED

           100

$149,350
           100%

$149,350
           100%

$149,350

EXCHANGE

           100

$149,350
           100%

$149,350

            TIME (MONTHS)
             0
             12
             24

LIQUIDATION VALUE

ORDERLY

           100

$149,350
           100%

$149,350

FORCED

           100

$149,350
           100%

$149,350
           100%

$149,350

Check this picture.

Body:
Tables are not connected to each other in any way and will not align to each other automatically. CSS is a way to go to make them look consistent. This is approx way of doing it.

table {
  width: 100%;
}

th {
  text-align: left;
}

td {
  width: 9%;
}

td:first-child {
  width: auto;
}

<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Very long long long long long name</td>
        <td>Smith</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
    </tr>
</table>
<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
    </tr>
</table>
<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
        <td>80</td>
    </tr>
</table>


问:
What should basically public folder contain in React
I was learning React and came across public folder which contains html file, favicon and the others. The question is for what public folder is actually created? and what should it contain?</p>

答:
React is a JavaScript library that needs to be "compiled" into code that the browser understands, so the public or build or dist folders are for holding the output of the compilation process or if you'd like, they store your artifact.

Just like target folder for Java projects.


问:
Passing by reference in C++ function
I am writing a simple program to calculate 6^5 using a function. Here's my code

```<code>#include <iostream>
using namespace std;

int raiseToPower(int &base, int exponent){
 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }
 return base;
}

int main() {
 int base = 6;
 cout << "6^5 is " << raiseToPower(base, 5)<< endl;

 return 0;
}
</code>```

The result is

```<code> 6^5 is -683606016
</code>```

instead of 7776

Can you guys explain to me why I got this result?
I am not looking for another way to write this code. I know there are simpler ways but I am trying to understand what went wrong

答:
Why are you using pass by reference. Setting as much const as possible reduces the odd of making mistakes:

```<code>#include <iostream>
using namespace std;

int raiseToPower(const int base, const int exponent) {
    int result = base;
    for (int i = 1; i < exponent; i = i + 1){
        result = result * base;
    }
    return result;
}

int main() {
    int base = 6;
    cout << "6^5 is " << raiseToPower(base, 5)<< endl;

    return 0;
}
</code>```

If it has to be pass by reference you could do this:

```<code>#include <iostream>
using namespace std;

void raiseToPower(const int base,
                 const int exponent,
                 int &result)
{
    result = base;
    for (int i = 1; i < exponent; i = i + 1){
        result = result * base;
    }
}

int main() {
    int base = 6;
    int result;
    raiseToPower(base, 5, result);

    cout << "6^5 is " << result << endl;

    return 0;
}
</code>```

Title: Passing by reference in C++ function

Body:
I am writing a simple program to calculate 6^5 using a function. Here's my code

#include <iostream>
using namespace std;

int raiseToPower(int &base, int exponent){
 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }
 return base;
}

int main() {
 int base = 6;
 cout << "6^5 is " << raiseToPower(base, 5)<< endl;

 return 0;
}

The result is

 6^5 is -683606016

instead of 7776

Can you guys explain to me why I got this result?
I am not looking for another way to write this code. I know there are simpler ways but I am trying to understand what went wrong

Body:
Why are you using pass by reference. Setting as much const as possible reduces the odd of making mistakes:

#include <iostream>
using namespace std;

int raiseToPower(const int base, const int exponent) {
    int result = base;
    for (int i = 1; i < exponent; i = i + 1){
        result = result * base;
    }
    return result;
}

int main() {
    int base = 6;
    cout << "6^5 is " << raiseToPower(base, 5)<< endl;

    return 0;
}

If it has to be pass by reference you could do this:

#include <iostream>
using namespace std;

void raiseToPower(const int base,
                 const int exponent,
                 int &result)
{
    result = base;
    for (int i = 1; i < exponent; i = i + 1){
        result = result * base;
    }
}

int main() {
    int base = 6;
    int result;
    raiseToPower(base, 5, result);

    cout << "6^5 is " << result << endl;

    return 0;
}


问:
Ideal way to store multiple texts in mongoose with Node JS?
I've been building a mongoose schema for texts that will be displayed across different pages, and it has end point to POST data for updating the texts.

For example, I would like to store text messages that will be displayed/updated in About Page and Contact Page

What would be the preferred way of designing the text model?

1) Model that has all messages stored in one data object

In front-end, the parent component fetches all text messages with Texts.findOne() and trickles down to pages that need it

const textsSchema = new Schema(
  {
    aboutMessage1: {
      type: String,
      required: true
    },
    aboutMessage2: {
      type: String,
      required: true
    },
    contactMessage1: {
      type: String
    },
    contactMessage2: {
      type: String
    }
  },
  { timestamps: true }
);
```

<p><strong>2) Model that contains each message--so it will have multiple objects</strong></p>

<ul>
<li>In fron-end, each page uses <strong>Text.findById(textId)</strong> to retrieve each message</li>
</ul>

<pre class="lang-js prettyprint-override"><code>const textSchema = new Schema(
  {
    // Example: name = contactMessage
    name: {
      type: String
    },
    message: {
      type: String
    }
  },
  { timestamps: true }
);
</code>```

3) Multiple models that contains texts for each page

Similar to 1) approach, texts get fetched with Texts.findOne(), but performed in each page

const aboutTextsSchema = new Schema(
  {
    message1: {
      type: String,
      required: true
    },
    message2: {
      type: String,
      required: true
    },
  },
  { timestamps: true }
);

const contactTextsSchema = new Schema(
  {
    message1: {
      type: String,
    },
    message2: {
      type: String,
    },
  },
  { timestamps: true }
);
```

答:
The most promising option is the second one. Because first and third options are static, and if in the future, you need to add a new page or or a new message to an existing page, it will require changes in the mongoose model, and deployment for API.

But I think, instead of creating a text schema, it would better to create a page schema for your scenario.

Here I embed messages inside the page schema.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const pageSchema = new Schema(
  {
    page: {
      type: String
    },
    messages: [
      new Schema({
        name: {
          type: String
        },
        message: {
          type: String
        }
      })
    ]
  },
  { timestamps: true }
);

module.exports = mongoose.model("Page", pageSchema);
```

<p>Now we can use this post route to create a page:</p>

<pre class="lang-js prettyprint-override"><code>router.post("/pages", async (req, res) => {
  const result = await Text.create(req.body);
  res.send(result);
});
</code>```

We can create a page and its messages using the previous post route.

Request Body:

```<code>{
    "_id": "5e4937e9e2454a2c0c162890",
    "page": "About",
    "messages": [
        {
            "_id": "5e4937e9e2454a2c0c162892",
            "name": "Abou1",
            "message": "About1 message..."
        },
        {
            "_id": "5e4937e9e2454a2c0c162891",
            "name": "Abou2",
            "message": "About2 message..."
        }
    ],
    "createdAt": "2020-02-16T12:39:05.154Z",
    "updatedAt": "2020-02-16T12:39:05.154Z",
    "__v": 0
}
</code>```

Response:

```<code>{
    "_id": "5e4937e9e2454a2c0c162890",
    "page": "About",
    "messages": [
        {
            "_id": "5e4937e9e2454a2c0c162892",
            "name": "Abou1",
            "message": "About1 message..."
        },
        {
            "_id": "5e4937e9e2454a2c0c162891",
            "name": "Abou2",
            "message": "About2 message..."
        }
    ],
    "createdAt": "2020-02-16T12:39:05.154Z",
    "updatedAt": "2020-02-16T12:39:05.154Z",
    "__v": 0
}
</code>```

If later we want to add a message to a page we can use the following put route.

router.put("/pages/:id", async (req, res) => {
  const result = await Page.findByIdAndUpdate(
    req.params.id,
    {
      $push: { messages: req.body }
    },
    { new: true }
  );
  res.send(result);
});
```

<p>Request Body:</p>

```{
    "name": "Abou3",
    "message": "About3 message..."
}
```

<p>Response:</p>

```{
    "_id": "5e4937e9e2454a2c0c162890",
    "page": "About",
    "messages": [
        {
            "_id": "5e4937e9e2454a2c0c162892",
            "name": "Abou1",
            "message": "About1 message..."
        },
        {
            "_id": "5e4937e9e2454a2c0c162891",
            "name": "Abou2",
            "message": "About2 message..."
        },
        {
            "_id": "5e493926f905ab3300106f94",
            "name": "Abou3",
            "message": "About3 message..."
        }
    ],
    "createdAt": "2020-02-16T12:39:05.154Z",
    "updatedAt": "2020-02-16T12:44:22.763Z",
    "__v": 0
}
```

<p>When client needs a page's messages, all we need to do is retrieving the page by it's id or page name:</p>

<pre class="lang-js prettyprint-override"><code>router.get("/pages/id/:id", async (req, res) => {
  const result = await Page.findById(req.params.id);
  res.send(result);
});

//or

router.get("/pages/name/:name", async (req, res) => {
  const result = await Page.findOne({ page: req.params.name });
  res.send(result);
});
</code>```

Body:
I've been building a mongoose schema for texts that will be displayed across different pages, and it has end point to POST data for updating the texts.

For example, I would like to store text messages that will be displayed/updated in About Page and Contact Page

What would be the preferred way of designing the text model?

1) Model that has all messages stored in one data object

In front-end, the parent component fetches all text messages with Texts.findOne() and trickles down to pages that need it

const textsSchema = new Schema(
  {
    aboutMessage1: {
      type: String,
      required: true
    },
    aboutMessage2: {
      type: String,
      required: true
    },
    contactMessage1: {
      type: String
    },
    contactMessage2: {
      type: String
    }
  },
  { timestamps: true }
);

2) Model that contains each message--so it will have multiple objects

In fron-end, each page uses Text.findById(textId) to retrieve each message

const textSchema = new Schema(
  {
    // Example: name = contactMessage
    name: {
      type: String
    },
    message: {
      type: String
    }
  },
  { timestamps: true }
);

3) Multiple models that contains texts for each page

Similar to 1) approach, texts get fetched with Texts.findOne(), but performed in each page

const aboutTextsSchema = new Schema(
  {
    message1: {
      type: String,
      required: true
    },
    message2: {
      type: String,
      required: true
    },
  },
  { timestamps: true }
);

const contactTextsSchema = new Schema(
  {
    message1: {
      type: String,
    },
    message2: {
      type: String,
    },
  },
  { timestamps: true }
);

Body:
The most promising option is the second one. Because first and third options are static, and if in the future, you need to add a new page or or a new message to an existing page, it will require changes in the mongoose model, and deployment for API.

But I think, instead of creating a text schema, it would better to create a page schema for your scenario.

Here I embed messages inside the page schema.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const pageSchema = new Schema(
  {
    page: {
      type: String
    },
    messages: [
      new Schema({
        name: {
          type: String
        },
        message: {
          type: String
        }
      })
    ]
  },
  { timestamps: true }
);

module.exports = mongoose.model("Page", pageSchema);

Now we can use this post route to create a page:

router.post("/pages", async (req, res) => {
  const result = await Text.create(req.body);
  res.send(result);
});

We can create a page and its messages using the previous post route.

Request Body:

{
    "_id": "5e4937e9e2454a2c0c162890",
    "page": "About",
    "messages": [
        {
            "_id": "5e4937e9e2454a2c0c162892",
            "name": "Abou1",
            "message": "About1 message..."
        },
        {
            "_id": "5e4937e9e2454a2c0c162891",
            "name": "Abou2",
            "message": "About2 message..."
        }
    ],
    "createdAt": "2020-02-16T12:39:05.154Z",
    "updatedAt": "2020-02-16T12:39:05.154Z",
    "__v": 0
}

Response:

{
    "_id": "5e4937e9e2454a2c0c162890",
    "page": "About",
    "messages": [
        {
            "_id": "5e4937e9e2454a2c0c162892",
            "name": "Abou1",
            "message": "About1 message..."
        },
        {
            "_id": "5e4937e9e2454a2c0c162891",
            "name": "Abou2",
            "message": "About2 message..."
        }
    ],
    "createdAt": "2020-02-16T12:39:05.154Z",
    "updatedAt": "2020-02-16T12:39:05.154Z",
    "__v": 0
}

If later we want to add a message to a page we can use the following put route.

router.put("/pages/:id", async (req, res) => {
  const result = await Page.findByIdAndUpdate(
    req.params.id,
    {
      $push: { messages: req.body }
    },
    { new: true }
  );
  res.send(result);
});

Request Body:

{
    "name": "Abou3",
    "message": "About3 message..."
}

Response:

{
    "_id": "5e4937e9e2454a2c0c162890",
    "page": "About",
    "messages": [
        {
            "_id": "5e4937e9e2454a2c0c162892",
            "name": "Abou1",
            "message": "About1 message..."
        },
        {
            "_id": "5e4937e9e2454a2c0c162891",
            "name": "Abou2",
            "message": "About2 message..."
        },
        {
            "_id": "5e493926f905ab3300106f94",
            "name": "Abou3",
            "message": "About3 message..."
        }
    ],
    "createdAt": "2020-02-16T12:39:05.154Z",
    "updatedAt": "2020-02-16T12:44:22.763Z",
    "__v": 0
}

When client needs a page's messages, all we need to do is retrieving the page by it's id or page name:

router.get("/pages/id/:id", async (req, res) => {
  const result = await Page.findById(req.params.id);
  res.send(result);
});

//or

router.get("/pages/name/:name", async (req, res) => {
  const result = await Page.findOne({ page: req.params.name });
  res.send(result);
});


问:
i want to make a functionality used only X number of times depending on the IP adress
for exemple if i have a user with an ip adress of 192.198.1.1 he only can use the functionality 5 times then he shoudn't be able to use it again until he sign in to the application. its more like a trial or somthing like that

i have already tried making a database table that save the ip of the user and the number of times he used the functionality but it dosn't seems to be logical solution for me its like allot of database calls and
could this be done in a better way/solution

the problem isn't about a code but a about a solution actually

答:
Since IP changes pretty frequently I'm not sure that this is the best solution for a trial.
However, you can do it with a DB as you said or with cache (if db is to slow or you don't want to use a DB) and if you're server is stable enough you can even hold this data in memory.

Anyway you can checkout Firebase as a free DB solution if you don't need to save huge amounts of data there

hope it helps :)


问:
How to print out a list with missing numbers?
I have a piece of code that is supposed to print out a list of numbers and also # for every time there is a duplicate number on the list, printing it out should look like this:

list = [6,7,7,9]

6#

7##

8

9#

Here is what i have so far:

```<code>def print_list(list1):
    list2 = [int(i) for i in list1]
    full_set = [x for x in range(list2[0], list2[-1] + 1)]
    list2.extend(full_set)
    list3 = list(set(list2))
    result = sorted([(x, list2.count(x)) for x in list3], key=lambda y: y[1])
    result.sort()
    for elem in result:
        print("{0:>2}".format(elem[0]), "{}".format(elem[1]*"#"))
</code>```

And it comes out wrong:

6 ##

 7 ###

 8 #

 9 ##

Any help is appreciated!

答:
I think this works:

```<code>def print_list(list1):
    list2 = [x for x in range(list1[0], list1[-1] + 1)]
    list3 = list(set(list2))
    result = sorted([(x, list1.count(x)) for x in list3], key=lambda y: y[1])
    result.sort()
    for elem in result:
        print("{0:>2}".format(elem[0]), "{}".format(elem[1]*"#"))

print_list([6,7,7,9])
</code>```

Output:

```<code> 6 #
 7 ##
 8
 9 #
</code>```

The issue with your current code is that you add your set of the numbers you're expecting to list2, so counting the amount of each number in list2 yields one more than you expect.

This is what list2 looks like with your original code:

```<code>[6, 7, 7, 9, 6, 7, 8, 9]
</code>```

This is because your call to the extend method takes list2 ( [6, 7, 7, 9] ), and adds full_set ( [6, 7, 8, 9] ) to it.  Thus when you count the occurrences of each number in list2, you are counting the original number, and then an extra one, because you've extended list2 with full_set.

Body:
I have a piece of code that is supposed to print out a list of numbers and also # for every time there is a duplicate number on the list, printing it out should look like this:

list = [6,7,7,9]

6#

7##

8

9#

Here is what i have so far:

def print_list(list1):
    list2 = [int(i) for i in list1]
    full_set = [x for x in range(list2[0], list2[-1] + 1)]
    list2.extend(full_set)
    list3 = list(set(list2))
    result = sorted([(x, list2.count(x)) for x in list3], key=lambda y: y[1])
    result.sort()
    for elem in result:
        print("{0:>2}".format(elem[0]), "{}".format(elem[1]*"#"))

And it comes out wrong:

6 ##

 7 ###

 8 #

 9 ##

Any help is appreciated!

Body:
I think this works:

def print_list(list1):
    list2 = [x for x in range(list1[0], list1[-1] + 1)]
    list3 = list(set(list2))
    result = sorted([(x, list1.count(x)) for x in list3], key=lambda y: y[1])
    result.sort()
    for elem in result:
        print("{0:>2}".format(elem[0]), "{}".format(elem[1]*"#"))

print_list([6,7,7,9])

Output:

 6 #
 7 ##
 8
 9 #

The issue with your current code is that you add your set of the numbers you're expecting to list2, so counting the amount of each number in list2 yields one more than you expect.

This is what list2 looks like with your original code:

[6, 7, 7, 9, 6, 7, 8, 9]

This is because your call to the extend method takes list2 ( [6, 7, 7, 9] ), and adds full_set ( [6, 7, 8, 9] ) to it.  Thus when you count the occurrences of each number in list2, you are counting the original number, and then an extra one, because you've extended list2 with full_set.


问:
Pandas : create a list based on index of a Dataframe
I am trying to obtain a list from a Dataframe based on a common value of the index.

In the example below I am trying to obtain the lists for 'type' and 'xx' based on 'date'.

Here is the Dataframe:

import pandas as pd
import numpy as np

idx = [np.array(['Jan', 'Jan', 'Feb', 'Mar', 'Mar', 'Mar']),np.array(['A1', 'A2', 'A2', 'A1', 'A3', 'A4'])]
data = [{'xx': 1}, {'xx': 5}, {'xx': 3}, {'xx': 2}, {'xx': 7}, {'xx': 3}]
df = pd.DataFrame(data, index=idx, columns=['xx'])
df.index.names=['date','type']
df.reset_index(inplace=True)
df=df.set_index(['date'])
```

<p>Which looks like this:</p>

<pre class="lang-py prettyprint-override"><code>      type  xx
date
 Jan    A1   1
 Jan    A2   5
 Feb    A2   3
 Mar    A1   2
 Mar    A3   7
 Mar    A4   3
</code>```

What I am trying to do is to create these two lists:

#list_type
[['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

#list_xx
[['1', '5'], ['3'], ['2', '7', '3']]
```

As you can see, the elements of the lists are constructed based on a common date.

I would really value an efficient way of doing this in Python.

答:
Use GroupBy.agg with list and then convert DataFrame to dictionary of lists by DataFrame.to_dict:

```<code>d = df.groupby(level=0, sort=False).agg(list).to_dict('l')
print (d)
{'type': [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']], 'xx': [[1, 5], [3], [2, 7, 3]]}

print (d['type'])
[['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

print (d['xx'])
[[1, 5], [3], [2, 7, 3]]
</code>```

Body:
I am trying to obtain a list from a Dataframe based on a common value of the index.

In the example below I am trying to obtain the lists for 'type' and 'xx' based on 'date'.

Here is the Dataframe:

import pandas as pd
import numpy as np

idx = [np.array(['Jan', 'Jan', 'Feb', 'Mar', 'Mar', 'Mar']),np.array(['A1', 'A2', 'A2', 'A1', 'A3', 'A4'])]
data = [{'xx': 1}, {'xx': 5}, {'xx': 3}, {'xx': 2}, {'xx': 7}, {'xx': 3}]
df = pd.DataFrame(data, index=idx, columns=['xx'])
df.index.names=['date','type']
df.reset_index(inplace=True)
df=df.set_index(['date'])

Which looks like this:

      type  xx
date
 Jan    A1   1
 Jan    A2   5
 Feb    A2   3
 Mar    A1   2
 Mar    A3   7
 Mar    A4   3

What I am trying to do is to create these two lists:

#list_type
[['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

#list_xx
[['1', '5'], ['3'], ['2', '7', '3']]

As you can see, the elements of the lists are constructed based on a common date.

I would really value an efficient way of doing this in Python.

Body:
Use GroupBy.agg with list and then convert DataFrame to dictionary of lists by DataFrame.to_dict:

d = df.groupby(level=0, sort=False).agg(list).to_dict('l')
print (d)
{'type': [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']], 'xx': [[1, 5], [3], [2, 7, 3]]}

print (d['type'])
[['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

print (d['xx'])
[[1, 5], [3], [2, 7, 3]]


问:
How create a query to filter by the total sum of an table column mysql
I have a quantity of data that I want to filter depending on the sum of the data, an example to be clear: I have that table

```<code>Nombre | nit | cantidad
andres | 222 | 1.5
joseff | 555 | 2
juanca | 777 | 3.5
ivanll | 999 | 4
amxsof | 111 | 6.1
</code>```

The query would have to do is, ask from this table the rows whose SUM of the cantidad column is equal or less (but as close as possible) than 13, and I would return the following:

```<code>Nombre | Nit | Cantidad
joseff | 555 | 2
ivanll | 999 | 4
amxsof | 111 | 6.1
</code>```

because the sum of 2 + 4 + 6.1 = 12.1, which is the closest sum to 13 that can be done with the records

答:
SQL is not optimal for this type of optimization problem.  You can do it, but it is brute force.

It also helps if you are limiting the number of rows that you are considering.  For instance, if you are considering combinations up to 4:

```<code>select t1.nombre, t2.nombre, t3.nombre, t4.nombre,
       (coalesce(t1.cantidad, 0) + coalesce(t2.cantidad, 0) + coalesce(t3.cantidad, 0) + coalesce(t4.cantidad, 0)
       ) as total
from t t1 left join
     t t2
     on t1.nombre < t2.nombre left join
     t t3
     on t2.nombre < t3.nombre left join
     t t4
     on t3.nombre < t4.nombre
where (coalesce(t1.cantidad, 0) + coalesce(t2.cantidad, 0) + coalesce(t3.cantidad, 0) + coalesce(t4.cantidad, 0)
       ) <= 13
order by total desc
limit 1;
</code>```

Here is a db<>fiddle.

If you want to consider additional combinations, you can add additional joins.

Body:
I have a quantity of data that I want to filter depending on the sum of the data, an example to be clear: I have that table

Nombre | nit | cantidad
andres | 222 | 1.5
joseff | 555 | 2
juanca | 777 | 3.5
ivanll | 999 | 4
amxsof | 111 | 6.1

The query would have to do is, ask from this table the rows whose SUM of the cantidad column is equal or less (but as close as possible) than 13, and I would return the following:

Nombre | Nit | Cantidad
joseff | 555 | 2
ivanll | 999 | 4
amxsof | 111 | 6.1

because the sum of 2 + 4 + 6.1 = 12.1, which is the closest sum to 13 that can be done with the records

Body:
SQL is not optimal for this type of optimization problem.  You can do it, but it is brute force.

It also helps if you are limiting the number of rows that you are considering.  For instance, if you are considering combinations up to 4:

select t1.nombre, t2.nombre, t3.nombre, t4.nombre,
       (coalesce(t1.cantidad, 0) + coalesce(t2.cantidad, 0) + coalesce(t3.cantidad, 0) + coalesce(t4.cantidad, 0)
       ) as total
from t t1 left join
     t t2
     on t1.nombre < t2.nombre left join
     t t3
     on t2.nombre < t3.nombre left join
     t t4
     on t3.nombre < t4.nombre
where (coalesce(t1.cantidad, 0) + coalesce(t2.cantidad, 0) + coalesce(t3.cantidad, 0) + coalesce(t4.cantidad, 0)
       ) <= 13
order by total desc
limit 1;

Here is a db<>fiddle.

If you want to consider additional combinations, you can add additional joins.


问:
What is the difference between traditional JavaScript objects and objects created using "new" keyword?
I need to know the differences between these person1 and person2.

class Person {
  constructor(Firstname, Lastname) {
    this.Firstname = Firstname;
    this.Lastname = Lastname;;
  }
  display() {
    console.log(this.Firstname + " " + this.Lastname);
  }
}

const person1 = new Person("George", "Clooney");

const person2 = {
  Firstname: "George",
  LastName: "Clooney"
}```

答: The first is instantiating a Person class, whereas the second is making an object. However, you have not provided anything about this Person class.


问:
Why does my server not seem to find the texture?
so we are about to improve our garrysmod server...
We want to add weaponicons to the weapon selection hud (scrolling)

So I made an addon: https://steamcommunity.com/sharedfiles/filedetails/?id=1988793385
(Currently has only one material in it)
Feel free to extract it :)

And in my darkrpmodifications addon i have inside of a module in a shared file:

```<code>weapon("arrest_stick").WepSelectIcon = surface.GetTextureID("hud/wepicons/icon_arrest")
</code>```

Problem is that ingame only the pink / black "not found" texture (dunno what to call it) appears as icon... And in my local gmod folder under the downloaded materials it also doesn't show the folder / icons provided in this addon...

Why is that please help me :(

Thank you in advance,
TheSaltyOne (Aaron).

EDIT: Here is my .vmt File:

```<code>"UnlitGeneric"
{
    "$basetexture" "hud/wepicons/icon_arrest"
    "$translucent" 1
    "$vertexalpha" 1
    "$vertexcolor" 1
}
</code>```

EDIT2:
After trying some stuff I now get the server to download it... (It shows in the cache/srcds)
But even if I download it as  client... 1. It doesnt show in my local addons folder and the texture is still not working :(

SOLUTION: FIXED IT!! I now have added the materials inside the addon and the server and provided a lua/autorun/sh_init.lua that does resource.AddFile to all the materials ^^

答: FIXED IT!! I now have added the materials inside the addon and the server and provided a lua/autorun/sh_init.lua that does resource.AddFile to all the materials ^^</p>

Body:
so we are about to improve our garrysmod server...
We want to add weaponicons to the weapon selection hud (scrolling)

So I made an addon: https://steamcommunity.com/sharedfiles/filedetails/?id=1988793385
(Currently has only one material in it)
Feel free to extract it :)

And in my darkrpmodifications addon i have inside of a module in a shared file:

weapon("arrest_stick").WepSelectIcon = surface.GetTextureID("hud/wepicons/icon_arrest")

Problem is that ingame only the pink / black "not found" texture (dunno what to call it) appears as icon... And in my local gmod folder under the downloaded materials it also doesn't show the folder / icons provided in this addon...

Why is that please help me :(

Thank you in advance,
TheSaltyOne (Aaron).

EDIT: Here is my .vmt File:

"UnlitGeneric"
{
    "$basetexture" "hud/wepicons/icon_arrest"
    "$translucent" 1
    "$vertexalpha" 1
    "$vertexcolor" 1
}

EDIT2:
After trying some stuff I now get the server to download it... (It shows in the cache/srcds)
But even if I download it as  client... 1. It doesnt show in my local addons folder and the texture is still not working :(

SOLUTION: FIXED IT!! I now have added the materials inside the addon and the server and provided a lua/autorun/sh_init.lua that does resource.AddFile to all the materials ^^


问:
Some images don't appear on in the browser
I'm making a website, consisting of 5 pages (e.g. page1.html, page2.html, etc. and following .css sheets). Weirdly, on some pages part of images appears without problem, but others do not. It seems like problem may be with pages/files, since when I tried to use the same image in different html file in place of the appearing image and it showed without problems. I tried using both copying whole url and name of the image with extension(images are in the same directory as the html and css files). Any thoughts?
(I'm using Chrome to view the website)

```<code><!DOCTYPE html>
<html>
<head>
  <meta name="description"  />
  <title> "animātiō" is "bestowing of life"</title>
   <link rel="stylesheet" type="text/css" href="CW1_page1_style.css" />
  </head>
<body>
  <h1>Just a small website about animation</h1>

  <div class="container">
    <div id="menu">

        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page0.html">Menu & Navigation</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page1.html">History and Beginnings</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page2.html">Traditional medium</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page3.html">Computer animation</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page4.html">2D or 3D: Which is Better?</a>
    </div>
  </div>

<br /><br /><br /><br />

<div>

  <section id="section-a">
    <div class="box-1">
       The first "animations" were sequences of consecutive images, which would give an illusion of movement.
       At the beginning there existed machines like Praxinoscope - series of images rotated at high speed - and Shadow plays - moving figures on a screen.
       Not to mention the technique known to every child that is a flipbook - conjuring "moving" image upon quickly flipping paper sheets.
  </div >
</section>
<section >
  <section id=section
  <p id="ex" >Examples of machines</p>
  <div class="examples">

   <img class="slide" src='magic-lantern.png' alt='Magic Lantern' />

  <img class="slide" src='zoetrope.gif' alt='Zoetrope'/>

   <img class="slide" src='flip-book.png' alt='Flip-Book'/>

    <img class="slide" src='praxinoscope.png' alt='Praxinoscope'/>

    </div>
</section>
<br />
  <section id="section-c">
    <div class-"box-2">
      The breakthrought began with the invention of motion pictures.
      Hand-drawn and painted animation was prevalent throughout the whole 20th century. From the first short movies of the silent era, to fresh creations with color and soundtrack
      animation started growing in popularity - and bringing more and more profit.
      </div>
      <div class="box-3">
        <img scr="snow-white.jpg" alt="Snow White'"/>
        The first hand-drawn animated movie - Disney's "Snow White" (1937)
        <img scr="disney.jpg" alt="Walt Disney'"/>
        Walt Disney - pioneer of American animation industry
      </div>
  </section>

<section id="section-d">
  <div class="box-3">
After addition of sound and color and subsequent success of Disney, other studios began to produce their own features. This was, no doubt, the golden years for Hollywood animation.
  </div>
  <div class="box-4">
    With the end of the 1950s and growing popolarity of television, stations began to emit various animated productions. A lot of them were cartoons aimed to kids
  </div>
  <div class="box-5">
Major animated productions from the Golden Era of American Televison feature cartoons like "The Flinstons", "Bear Yoggy"
  <br />
  <img scr="felixc.jpg" alt="Felix the Cat"/>
  <img scr="flinstones.jpg" alt="Flinstons"/>
  </div>
</section>

</div>

  </body>
</html>
</code>```

```<code>body {
  background-color: beige;
  font-size: 17px;
}

 /** {
  box-sizing: border-box;
} */
h1 {
  color: #3e3e80;
  text-align: center;
}

.container {
  position: absolute;
  margin: 20px;
  width: auto;
}

#menu {
   overflow: hidden;
   background-color: green
 }

 #menu a {
   float: left;
   color: white;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }
 #menu a:hover {
  color: #3e3e80;
  background-color: white;
 }

  .slide {
    float: left;
    width: 25%;
    padding: 0px;
  }

  .examples::after {
    content: "";
    clear: both;
    display: inline-flex;
  }

  #section-c {
    display : inline-flex;
  }
</code>```

Example above: Here first 4 images work, the rest doesn't

And below everything appears no problem:

```<code><!DOCTYPE html>
<html>
<head>
  <meta name="description"  />
    <title> "animātiō" is "bestowing of life"</title>
    <link rel="stylesheet" type="text/css" href="CW1_page2_style.css" />
  </head>
<body>
  <h1>Just a small website about animation</h1>

  <div class="container">
    <div id="menu">

        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page0.html">Menu & Navigation</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page1.html">History and Beginnings</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page2.html">Traditional medium</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page3.html">Computer animation</a>
        <a href="file:///C:/Users/Asia/Desktop/Uni/Semestr2/Introduction%20to%20Web%20Technologies/CW1_page4.html">2D or 3D: Which is Better?</a>
    </div>
  </div>

<br /><br /><br /><br />

  <div>
    <section id="section-a">
      <div class="box-0">
      Traditional animation (hand-drawn animation) is the first type of aniamtion that have been used (not counting any machines equipped with slides).
      <br /><br />
      The oldest and used commonly throughtout most of the history of animation,
      recently this style seemed to fall out of grace in favour of computer generated images.
      However, it's still used even nowadays and has many enthusiasts.
      <br />

    </div>
    <div class='box-1'>
      <img class="im" src="aniwork1.jpg" alt="Animator working on" />
    </div >
    <div class="small-fact">
      <img class="im" src="aniwork2.jpg" alt="Animator working on" />
    </div>
    <div class="small-fact">
        Did you know: The standard number of frames is 90 per minute of the movie!
        <br /> <br />
        That makes 8100 drawings for a 90 minutes-long film!
    </div>
    </section>

  <section id="section-b">
    <div class="box-2">
      The process of creating any animated piece starts with storyboards.
       Here, delegated artists prepare rough layouts of the scene, with characters and backgrounds taken into consideration.
      <img  class="board" src="storyboard.jpg" alt="Storyboard" />
    </div>
      <div class="box-3">

       <img class="phase" src="animatic phase.gif" alt="Animatic phase form Avatar: The Last Airbender" />
The next stage is animatic phase - similar to storyboarding, but consisting of key frame (the most important parts of the particular scenes).
  <br /> <br />
  (Above: animatic phase from "Avatar: The Last Airbender")
  <br /> <br />
  (Left: Storyboards indicate on surroundings, as well as the charaters and actions.)
     </div>
    <div class="box-4">
      Afterwards, there's a need to provide the in-between, additional images which will guarantee smoothness of the animation.
      Lastly, it's only the matter of inking and coloring the pages.
        <img class="slide1" src='inking.jpg' alt='Inking a character #1' />
        <img class="slide2" src='ink-color.jpg' alt='Inked and colored character' />

    </div>

  </section>
  <section>

  <div class="examples">
  <p id="ex" >Examples of traditionally animated features</p>
    <img class="pink" src='pinkp.jpg' alt='The Pink Panther'/>
     <img class="pi" src='pinoccio.jpg' alt='Pinoccio'/>
      <img class="lion" src='lion_king.webp' alt='The Lion King'/>
      <img class="eldorado" src='eldorado.jpg' alt='Road to El Dorado'/>

  </div>

</section>
  </body>
</html>
</code>```

```<code>body {
  background-color: beige;
  font-size: 17px;
}
h1 {
  color: #3e3e80;
  text-align: center;
}

.container {
  position: absolute;
  margin: 20px;
  width: auto;
}

#menu {
   overflow: hidden;
   background-color: brown;
 }

 #menu a {
   float: left;
   color: white;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }
 #menu a:hover {
  color: #3e3e80;
  background-color: white;
 }

  #section-a {
    display: flex;
  }
  #section-a .box-0{
      float: left;
      width: 70%;
      padding: 5px;
  }
  #section-a .box-1 .im{
    width: 250px;
    height: 200px;
  }
  #section-a .small-fact{
    float: left;
    width: 30%;
    padding: 5px;
  }
  #section-a .small-fact .im {
    width: 250px;
    height: 175px;
  }

  #section-b {
    display: inline-flex;
    background-color: brown;
    color: white;
  }

  #section-b .box-2{
    padding: 5px;
  }

  #section-b .box-2 .board {
    width: 400px;
    height: 400px;

  }

  #section-b .box-3 {
    padding: 5px;
  }

  #section-b .box-3 .phase .{
    width: 100vs;
    height: auto;
  }

   #section-b .box-4{
    padding: 5px;
  }

#section-b .box-4 .slide1 {
  width: 300px;
  height: 200px;

}
#section-b .box-4 .slide2 {
  width: 60%;
  height: 35%;

}

#ex {
  text-align: center;
  font-weight: bold;
  text-decoration: underline
}

.pink {
  float: left;
  width: 300px;
  padding: 0px;
}
.pi {
  float: left;
  width: 300px;
  height: 300px
  padding: 0px;
}
.lion {
  float: left;
  width: 300px;
  height: 20%;
  padding: 0px;
}
.eldorado {
  float: left;
  padding: 0px;
  height: 50vh;
  width: 65vh;
}

.examples::after {
  content: "";
  clear: both;
  display: table;
}
</code>```

答:
I recommend to put all your images on the same folder or assets folder.

Finally, some time, clearing the cache of the browser fix the problem.

Body:
I'm making a website, consisting of 5 pages (e.g. page1.html, page2.html, etc. and following .css sheets). Weirdly, on some pages part of images appears without problem, but others do not. It seems like problem may be with pages/files, since when I tried to use the same image in different html file in place of the appearing image and it showed without problems. I tried using both copying whole url and name of the image with extension(images are in the same directory as the html and css files). Any thoughts?
(I'm using Chrome to view the website)

<!DOCTYPE html>

  <meta name="description"  />
  <title> "animātiō" is "bestowing of life"</title>
   <link rel="stylesheet" type="text/css" href="CW1_page1_style.css" />

Just a small website about animation

        Menu & Navigation
        History and Beginnings
        Traditional medium
        Computer animation
        2D or 3D: Which is Better?

       The first "animations" were sequences of consecutive images, which would give an illusion of movement.
       At the beginning there existed machines like Praxinoscope - series of images rotated at high speed - and Shadow plays - moving figures on a screen.
       Not to mention the technique known to every child that is a flipbook - conjuring "moving" image upon quickly flipping paper sheets.

  <section id=section

Examples of machines

      The breakthrought began with the invention of motion pictures.
      Hand-drawn and painted animation was prevalent throughout the whole 20th century. From the first short movies of the silent era, to fresh creations with color and soundtrack
      animation started growing in popularity - and bringing more and more profit.

        The first hand-drawn animated movie - Disney's "Snow White" (1937)

        Walt Disney - pioneer of American animation industry

After addition of sound and color and subsequent success of Disney, other studios began to produce their own features. This was, no doubt, the golden years for Hollywood animation.

    With the end of the 1950s and growing popolarity of television, stations began to emit various animated productions. A lot of them were cartoons aimed to kids

Major animated productions from the Golden Era of American Televison feature cartoons like "The Flinstons", "Bear Yoggy"

body {
  background-color: beige;
  font-size: 17px;
}

 /** {
  box-sizing: border-box;
} */
h1 {
  color: #3e3e80;
  text-align: center;
}

.container {
  position: absolute;
  margin: 20px;
  width: auto;
}

#menu {
   overflow: hidden;
   background-color: green
 }

 #menu a {
   float: left;
   color: white;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }
 #menu a:hover {
  color: #3e3e80;
  background-color: white;
 }

  .slide {
    float: left;
    width: 25%;
    padding: 0px;
  }

  .examples::after {
    content: "";
    clear: both;
    display: inline-flex;
  }

  #section-c {
    display : inline-flex;
  }

Example above: Here first 4 images work, the rest doesn't

And below everything appears no problem:

<!DOCTYPE html>

  <meta name="description"  />
    <title> "animātiō" is "bestowing of life"</title>
    <link rel="stylesheet" type="text/css" href="CW1_page2_style.css" />

Just a small website about animation

        Menu & Navigation
        History and Beginnings
        Traditional medium
        Computer animation
        2D or 3D: Which is Better?

      Traditional animation (hand-drawn animation) is the first type of aniamtion that have been used (not counting any machines equipped with slides).

      The oldest and used commonly throughtout most of the history of animation,
      recently this style seemed to fall out of grace in favour of computer generated images.
      However, it's still used even nowadays and has many enthusiasts.

        Did you know: The standard number of frames is 90 per minute of the movie!

        That makes 8100 drawings for a 90 minutes-long film!

      The process of creating any animated piece starts with storyboards.
       Here, delegated artists prepare rough layouts of the scene, with characters and backgrounds taken into consideration.

The next stage is animatic phase - similar to storyboarding, but consisting of key frame (the most important parts of the particular scenes).

  (Above: animatic phase from "Avatar: The Last Airbender")

  (Left: Storyboards indicate on surroundings, as well as the charaters and actions.)

      Afterwards, there's a need to provide the in-between, additional images which will guarantee smoothness of the animation.
      Lastly, it's only the matter of inking and coloring the pages.

Examples of traditionally animated features

body {
  background-color: beige;
  font-size: 17px;
}
h1 {
  color: #3e3e80;
  text-align: center;
}

.container {
  position: absolute;
  margin: 20px;
  width: auto;
}

#menu {
   overflow: hidden;
   background-color: brown;
 }

 #menu a {
   float: left;
   color: white;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }
 #menu a:hover {
  color: #3e3e80;
  background-color: white;
 }

  #section-a {
    display: flex;
  }
  #section-a .box-0{
      float: left;
      width: 70%;
      padding: 5px;
  }
  #section-a .box-1 .im{
    width: 250px;
    height: 200px;
  }
  #section-a .small-fact{
    float: left;
    width: 30%;
    padding: 5px;
  }
  #section-a .small-fact .im {
    width: 250px;
    height: 175px;
  }

  #section-b {
    display: inline-flex;
    background-color: brown;
    color: white;
  }

  #section-b .box-2{
    padding: 5px;
  }

  #section-b .box-2 .board {
    width: 400px;
    height: 400px;

  }

  #section-b .box-3 {
    padding: 5px;
  }

  #section-b .box-3 .phase .{
    width: 100vs;
    height: auto;
  }

   #section-b .box-4{
    padding: 5px;
  }

#section-b .box-4 .slide1 {
  width: 300px;
  height: 200px;

}
#section-b .box-4 .slide2 {
  width: 60%;
  height: 35%;

}

#ex {
  text-align: center;
  font-weight: bold;
  text-decoration: underline
}

.pink {
  float: left;
  width: 300px;
  padding: 0px;
}
.pi {
  float: left;
  width: 300px;
  height: 300px
  padding: 0px;
}
.lion {
  float: left;
  width: 300px;
  height: 20%;
  padding: 0px;
}
.eldorado {
  float: left;
  padding: 0px;
  height: 50vh;
  width: 65vh;
}

.examples::after {
  content: "";
  clear: both;
  display: table;
}


问:
ProgressBar wont be visible in Android Studio from code
So I have made an app, and I'm trying to show the progress bar at the time when a button is clicked.

It shows only if I put the View.VISIBLE outside the handler.

Kotlin code:

```<code>button.setOnClickListener {

progressBar.visibility = View.VISIBLE
    runBlocking {

        try {
            //HTTP request removed because of confidentiality, assume I'm setting delay

        } catch (e: Exception) {
            Log.e(tag, "Error: " + e.message)
            Toast.makeText(this@MainActivity, "Could not find page", Toast.LENGTH_LONG)
                .show()
        }

    }
    progressBar.visibility = View.GONE
}
</code>```

Button XML:

```<code><ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:alpha="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility= "invisible"/>
</code>```

I've been searching for hours now and couldn't find something relevant to my case.

Output wanted:
Get the progress bar at the time the button is clicked.

答:
Remove the line from code : </p>

```<code>progressBar.visibility = View.GONE
</code>```

Body:
So I have made an app, and I'm trying to show the progress bar at the time when a button is clicked.

It shows only if I put the View.VISIBLE outside the handler.

Kotlin code:

button.setOnClickListener {

progressBar.visibility = View.VISIBLE
    runBlocking {

        try {
            //HTTP request removed because of confidentiality, assume I'm setting delay

        } catch (e: Exception) {
            Log.e(tag, "Error: " + e.message)
            Toast.makeText(this@MainActivity, "Could not find page", Toast.LENGTH_LONG)
                .show()
        }

    }
    progressBar.visibility = View.GONE
}

Button XML:

<ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:alpha="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility= "invisible"/>

I've been searching for hours now and couldn't find something relevant to my case.

Output wanted:
Get the progress bar at the time the button is clicked.

Body:
Remove the line from code :

progressBar.visibility = View.GONE


问:
Prevent on click on parent A tag when clicking button inside
I have problems with product cards on index page.
Inside product card I have Vue component to render form (quantity and add to cart button).
When I click on add to cart button I get expected result. Response is sent to root vue component and then I see toast notification that product is added to cart.
But when I click on plus, minus buttons or input field then href link is triggered from parent A tag.

How to disable it?
I found this Prevent on click on parent when clicking button inside div

But it works only if I put A tag inside vue component. I don't want to put too much html into vue.

```<code>        @foreach ($products as $product)
        <a href="{{ $category->fullpath.'/'.$product->sef }}" class="catalog__card">
          <div class="catalog__card-img"><img src="/storage/img/products/{{ $product->mediumpic }}" alt="{{ $product->title }}"></div>

          <div class="card__properties">
            <div class="card__price"><span>{{ $product->price }}<span class="currencySymbol">₽</span></span></div>
            <div class="card__stock">
              @if ( $product->stock > 0 )
              <i class="far fa-check-circle text-success"></i><span class="text-success"><strong> on stock</strong></span>
              @else
                <span><strong> on request</strong></span>
              @endif
            </div>
            <addtocart @added_to_cart="updateCart"></addtocart>
          </div>
          <div class="catalog__card-title"><span>{{ $product->title }}</span></div>
        </a>
        @endforeach
</code>```

in Vue component I have following

```<code><template>

  <div class="cart">
    <form method="POST" id="add_to_cart" action="/add_to_cart" @submit.prevent="onSubmit">
      <input type="hidden" name="_token" :value="csrf">
      <div class="quantity">
        <button type="button" class="minus_quantity" v-on:click="minus_quantity" v-long-press="300" @long-press-start="longMinusStart" @long-press-stop="longMinusStop">-</button>
        <input type="number" class="input-text qty text" step="1" min="1" max="9999" name="quantity" value="1" title="Qty" v-model.number="quantity">
        <button type="button" class="plus_quantity" v-on:click="plus_quantity" v-long-press="300" @long-press-start="longPlusStart" @long-press-stop="longPlusStop">+</button>
      </div>
      <button type="submit" name="add-to-cart" class="button-cart"><i class="fas fa-cart-plus"></i><span> order</span></button>
    </form>
  </div>

</template>

<script>
    import LongPress from 'vue-directive-long-press';

    export default {

        name: "addtocart",

        data: function () {
          return {
            csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            quantity: 1,
            plusInterval: null,
            minusInterval: null,
            success: false,
            errors: []
          }
        },

        directives: {
          'long-press': LongPress,
        },

        props: [],

        computed: {
          getName(){
             return this.$store.getters.Name
          }
        },

        methods: {
          // add to cart quantity plus and minus buttons
          // short mouse click event
          parent() { alert('you clicked the parent') },

          minus_quantity() {
            if (this.quantity > 0) {this.quantity -= 1}
          },
          plus_quantity() {this.quantity += 1},
          // long press buttons
          longPlusStart() {
            this.plusInterval = setInterval(() => {
              this.quantity += 1
            }, 100)
          },
          longPlusStop() {
            clearInterval(this.plusInterval)
          },
          longMinusStart() {
            this.minusInterval = setInterval(() => {
              if (this.quantity > 0) {this.quantity -= 1}
            }, 100)
          },
          longMinusStop() {
            clearInterval(this.minusInterval)
          },

          onSubmit() {
            axios.post('/add_to_cart', this.$data)
            .then(this.onSuccess)
            .catch(error => this.errors = error.response.data);
          },
          onSuccess(response) {
            this.success = true;
            this.$emit('added_to_cart', response);
          },

        },

        mounted() {

        },

    }
</script>
</code>```

答:
You can use "v-on:click.stop" directive for your plus, minus buttons instead of "v-on:click"

Read this for more information https://v2.vuejs.org/v2/guide/events.html

Body:
I have problems with product cards on index page.
Inside product card I have Vue component to render form (quantity and add to cart button).
When I click on add to cart button I get expected result. Response is sent to root vue component and then I see toast notification that product is added to cart.
But when I click on plus, minus buttons or input field then href link is triggered from parent A tag.

How to disable it?
I found this Prevent on click on parent when clicking button inside div

But it works only if I put A tag inside vue component. I don't want to put too much html into vue.

        @foreach ($products as $product)
        fullpath.'/'.$product->sef }}" class="catalog__card">

mediumpic }}" alt="{{ $product->title }}">

{{ $product->price }}₽

              @if ( $product->stock > 0 )
               on stock
              @else
                 on request
              @endif

            <addtocart @added_to_cart="updateCart"></addtocart>

{{ $product->title }}

        @endforeach

in Vue component I have following

<template>

    <form method="POST" id="add_to_cart" action="/add_to_cart" @submit.prevent="onSubmit">
      <input type="hidden" name="_token" :value="csrf">

        <button type="button" class="minus_quantity" v-on:click="minus_quantity" v-long-press="300" @long-press-start="longMinusStart" @long-press-stop="longMinusStop">-</button>
        <input type="number" class="input-text qty text" step="1" min="1" max="9999" name="quantity" value="1" title="Qty" v-model.number="quantity">
        <button type="button" class="plus_quantity" v-on:click="plus_quantity" v-long-press="300" @long-press-start="longPlusStart" @long-press-stop="longPlusStop">+</button>

      <button type="submit" name="add-to-cart" class="button-cart"> order</button>
    </form>

</template>


问:
SQLAlchemy: add a relationship using id instead of object?
Is it possible to add to a SQLAlchemy relationship using ids rather than objects?

For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:

```<code>class Review(Base):
    artist_id = Column(Integer, ForeignKey('artist.id'))
    artist = relationship(Artist, backref=backref('reviews', order_by=id))
    # etc.

class Artist(Base):
    # etc.
</code>```

With a list of review ids to add to an artist, I seem to need to look up the artist from the id, then add the artist object to the review, like this:

```<code>for review_id in review_ids:
    review = session.query(Review).filter(Review.id==review_id).first()
    artist.reviews.append(review)
</code>```

I'm sure it would be more efficient to skip the lookup and just add the ids, but is this possible?

答:
I'm not sure if I understood. I guess you want something like this:</p>

```<code>reviews = session.query(Review).filter(Review.id.in_(review_ids)).all()

artist.reviews.extend(reviews)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to add to a SQLAlchemy relationship using ids rather than objects?

For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:

class Review(Base):
    artist_id = Column(Integer, ForeignKey('artist.id'))
    artist = relationship(Artist, backref=backref('reviews', order_by=id))
    # etc.

class Artist(Base):
    # etc.

With a list of review ids to add to an artist, I seem to need to look up the artist from the id, then add the artist object to the review, like this:

for review_id in review_ids:
    review = session.query(Review).filter(Review.id==review_id).first()
    artist.reviews.append(review)

I'm sure it would be more efficient to skip the lookup and just add the ids, but is this possible?

Body:
I'm not sure if I understood. I guess you want something like this:

reviews = session.query(Review).filter(Review.id.in_(review_ids)).all()

artist.reviews.extend(reviews)


答: Becuase your style is (style="?android:attr/progressBarStyle"), and your width/height are (wrap_content). for Bar style. you should give it value (for example 100dp to WIDTH, and 20dp to HEIGHT.

Title: ProgressBar wont be visible in Android Studio from code


问:
Understanding the auipc+jalr sequence used for function calls
I was trying to read RISC-V assembly generated by gcc and I found that gcc creates sequence of auipc+jalr for some function calls and I don't understand how it works. Here's a simple example. Consider the following C source file:

```<code>unsigned long id(unsigned long x) {
    return x;
}

unsigned long add_one(unsigned long x) {
    return id(x)+1;
}
</code>```

I compile it with gcc -O2 -fno-inline -c test.c and I get the following assembly code:

```<code>$ objdump -d test.o

test.o:     file format elf64-littleriscv

Disassembly of section .text:

0000000000000000 <id>:
   0:   00008067            ret

0000000000000004 <add_one>:
   4:   ff010113            addi    sp,sp,-16
   8:   00113423            sd      ra,8(sp)
   c:   00000317            auipc   t1,0x0
  10:   000300e7            jalr    t1
  14:   00813083            ld      ra,8(sp)
  18:   00150513            addi    a0,a0,1
  1c:   01010113            addi    sp,sp,16
  20:   00008067            ret
</code>```

What confuses me are the two lines at the offsets 0x0c and 0x10, which is where the function id is supposed to be called. According to the spec, auipc t1,0x0 should write PC + 0x0<<12 (which is equal to PC) to t1 and then jalr t1 (which gets expanded to jalr ra,t1,0) jumps to the address stored in t1 and stores the return address to ra. So we end up jumping to the auipc line (offset 0x0c), not the entry point of id. What's going on here?

答:
When disassembling an object file, the displayed address information in auipc/jalr is kind of arbitrary because it's get relocated by the linker, anyways.

You can see that when also dumping the relocation information (add -r to your objdump call):

```<code>0000000000000000 <id>:
   0:   8082                    ret
0000000000000002 <add_one>:
   2:   1141                    addi    sp,sp,-16
   4:   e406                    sd  ra,8(sp)
   6:   00000097            auipc   ra,0x0
            6: R_RISCV_CALL id
            6: R_RISCV_RELAX    *ABS*
   a:   000080e7            jalr    ra # 6 <add_one+0x4>
   e:   60a2                    ld  ra,8(sp)
  10:   0505                    addi    a0,a0,1
  12:   0141                    addi    sp,sp,16
  14:   8082                    ret
</code>```

Those relocation entries tell the linker to relocate the jump instructions in a relaxed fashion (the default for the RISC-V toolchain). That means it's allowed to replace  auipc+jalr pairs with just one jal instruction iff the distance to the target address is short enough. Such replacements are advantageous because it saves instructions, i.e. the resulting program is shorter. Obviously, it complicates the relocation procedure a bit, because the offsets of following jump instructions need to be adjusted accordingly.

(This can be disabled with the -mno-relax GCC flag.)

Why can't the assembler directly emit final auipc/jalr/jal instructions for symbols local to the translation unit that don't need to be relocated? After all, those jumps are pc-relative.

In general it can't because with just the local view of one translation unit 1) a relaxed relocation to an external symbol may change all following offsets to internal symbols and 2) the linker might even apply some advanced rule, e.g. where an internal symbol is overlayed by an external one, such that it really has to be relocated in the linker. Or, another example, where the linker deletes a symbol.

If you want to look at relocated addresses/offsets you have to disassemble the linked binary, e.g.:

```<code>000000000001015c <id>:
   1015c:   8082                    ret
000000000001015e <add_one>:
   1015e:   1141                    addi    sp,sp,-16
   10160:   e406                    sd  ra,8(sp)
   10162:   ffbff0ef            jal ra,1015c <id>
   10166:   60a2                    ld  ra,8(sp)
   10168:   0505                    addi    a0,a0,1
   1016a:   0141                    addi    sp,sp,16
   1016c:   8082                    ret
</code>```

As expected, the linker relaxes auipc+jalr to just jal. Unfortunately, objdump doesn't display the raw jal offset - 1015c is the absolute address after adding the offset to 10162.1

You can verify it by decoding the binary instruction in the second column by yourself:

```<code>   0xffbff0ef
=  0b11111111101111111111000011101111 | split into the offset parts
=>   1 1111111101 1 11111111          | i.e. off[20], off[10:1], off[11], off[19:12]
                                      | merge them into off[20:1]
=> 0b11111111111111111101             | left-shift by 1
=> 0b111111111111111111010            | sign-extend
=> 0b11111111111111111111111111111010
=  -6
=> 0x10162 - 6
=  0x1015c
</code>```

Which matches the objdump output.

1 That means GNU binutils objdump doesn't display the raw jal offset. In contrast, llvm-objdump (LLVM 9 introduces official RISC-V support) does display the raw offset:

```<code>000000000001015e add_one:
   1015e: 41 11                         addi    sp, sp, -16
   10160: 06 e4                         sd  ra, 8(sp)
   10162: ef f0 bf ff                   jal -6
   10166: a2 60                         ld  ra, 8(sp)
   10168: 05 05                         addi    a0, a0, 1
   1016a: 41 01                         addi    sp, sp, 16
   1016c: 82 80                         ret
</code>```

However, in contrast to GNU binutils objdump, llvm-objdump doesn't include  the resulting absolute address as an annotation. Neither does it annotate the corresponding symbol. Thus, the GNU binutils objdump output arguably is more useful, in general.

Body:
I was trying to read RISC-V assembly generated by gcc and I found that gcc creates sequence of auipc+jalr for some function calls and I don't understand how it works. Here's a simple example. Consider the following C source file:

unsigned long id(unsigned long x) {
    return x;
}

unsigned long add_one(unsigned long x) {
    return id(x)+1;
}

I compile it with gcc -O2 -fno-inline -c test.c and I get the following assembly code:

$ objdump -d test.o

test.o:     file format elf64-littleriscv

Disassembly of section .text:

0000000000000000 <id>:
   0:   00008067            ret

0000000000000004 <add_one>:
   4:   ff010113            addi    sp,sp,-16
   8:   00113423            sd      ra,8(sp)
   c:   00000317            auipc   t1,0x0
  10:   000300e7            jalr    t1
  14:   00813083            ld      ra,8(sp)
  18:   00150513            addi    a0,a0,1
  1c:   01010113            addi    sp,sp,16
  20:   00008067            ret

What confuses me are the two lines at the offsets 0x0c and 0x10, which is where the function id is supposed to be called. According to the spec, auipc t1,0x0 should write PC + 0x0<<12 (which is equal to PC) to t1 and then jalr t1 (which gets expanded to jalr ra,t1,0) jumps to the address stored in t1 and stores the return address to ra. So we end up jumping to the auipc line (offset 0x0c), not the entry point of id. What's going on here?

Body:
When disassembling an object file, the displayed address information in auipc/jalr is kind of arbitrary because it's get relocated by the linker, anyways.

You can see that when also dumping the relocation information (add -r to your objdump call):

0000000000000000 <id>:
   0:   8082                    ret
0000000000000002 <add_one>:
   2:   1141                    addi    sp,sp,-16
   4:   e406                    sd  ra,8(sp)
   6:   00000097            auipc   ra,0x0
            6: R_RISCV_CALL id
            6: R_RISCV_RELAX    *ABS*
   a:   000080e7            jalr    ra # 6 <add_one+0x4>
   e:   60a2                    ld  ra,8(sp)
  10:   0505                    addi    a0,a0,1
  12:   0141                    addi    sp,sp,16
  14:   8082                    ret

Those relocation entries tell the linker to relocate the jump instructions in a relaxed fashion (the default for the RISC-V toolchain). That means it's allowed to replace  auipc+jalr pairs with just one jal instruction iff the distance to the target address is short enough. Such replacements are advantageous because it saves instructions, i.e. the resulting program is shorter. Obviously, it complicates the relocation procedure a bit, because the offsets of following jump instructions need to be adjusted accordingly.

(This can be disabled with the -mno-relax GCC flag.)

Why can't the assembler directly emit final auipc/jalr/jal instructions for symbols local to the translation unit that don't need to be relocated? After all, those jumps are pc-relative.

In general it can't because with just the local view of one translation unit 1) a relaxed relocation to an external symbol may change all following offsets to internal symbols and 2) the linker might even apply some advanced rule, e.g. where an internal symbol is overlayed by an external one, such that it really has to be relocated in the linker. Or, another example, where the linker deletes a symbol.

If you want to look at relocated addresses/offsets you have to disassemble the linked binary, e.g.:

000000000001015c <id>:
   1015c:   8082                    ret
000000000001015e <add_one>:
   1015e:   1141                    addi    sp,sp,-16
   10160:   e406                    sd  ra,8(sp)
   10162:   ffbff0ef            jal ra,1015c <id>
   10166:   60a2                    ld  ra,8(sp)
   10168:   0505                    addi    a0,a0,1
   1016a:   0141                    addi    sp,sp,16
   1016c:   8082                    ret

As expected, the linker relaxes auipc+jalr to just jal. Unfortunately, objdump doesn't display the raw jal offset - 1015c is the absolute address after adding the offset to 10162.1

You can verify it by decoding the binary instruction in the second column by yourself:

   0xffbff0ef
=  0b11111111101111111111000011101111 | split into the offset parts
=>   1 1111111101 1 11111111          | i.e. off[20], off[10:1], off[11], off[19:12]
                                      | merge them into off[20:1]
=> 0b11111111111111111101             | left-shift by 1
=> 0b111111111111111111010            | sign-extend
=> 0b11111111111111111111111111111010
=  -6
=> 0x10162 - 6
=  0x1015c

Which matches the objdump output.

1 That means GNU binutils objdump doesn't display the raw jal offset. In contrast, llvm-objdump (LLVM 9 introduces official RISC-V support) does display the raw offset:

000000000001015e add_one:
   1015e: 41 11                         addi    sp, sp, -16
   10160: 06 e4                         sd  ra, 8(sp)
   10162: ef f0 bf ff                   jal -6
   10166: a2 60                         ld  ra, 8(sp)
   10168: 05 05                         addi    a0, a0, 1
   1016a: 41 01                         addi    sp, sp, 16
   1016c: 82 80                         ret

However, in contrast to GNU binutils objdump, llvm-objdump doesn't include  the resulting absolute address as an annotation. Neither does it annotate the corresponding symbol. Thus, the GNU binutils objdump output arguably is more useful, in general.