问:
How to avoid database from being hit hard when API is getting bursted?
I have an API which allows other microservices to call on to check whether a particular product exists in the inventory. The API takes in only one parameter which is the ID of the product.

The API is served through API Gateway in Lambda and it simply queries against a Postgres RDS to check for the product ID. If it finds the product, it returns the information about the product in the response. If it doesn't, it just returns an empty response. The SQL is basically this:

```<code>SELECT * FROM inventory where expired = false and product_id = request.productId;
</code>```

However, the problem is that many services are calling this particular API very heavily to check the existence of products. Not only that, the calls often come in bursts. I assume those services loop through a list of product IDs and check for their existence individually, hence the burst.

The number of concurrent calls on the API has resulted in it making many queries to the database. The rate can burst beyond 30 queries per sec and there can be a few hundred thousands of requests to fulfil. The queries are mostly the same, except for the product ID in the where clause. The column has been indexed and it takes an average of only 5-8ms to complete. Still, the connection to the database occasionally time out when the rate gets too high.

I'm using Sequelize as my ORM and the error I get when it time out is SequelizeConnectionAcquireTimeoutError. There is a good chance that the burst rate was too high and it max'ed out the pool too.

Some options I have considered:

Using a cache layer. But I have noticed that, most
of the time, 90% of the product IDs in the requests are not repeated.
This would mean that 90% of the time, it would be a cache miss and it
will still query against the database.

Auto scale up the database. But because the calls are bursty and I don't
know when they may come, the autoscaling won't complete in time to
avoid the time out. Moreover, the query is a very simple select statement and the CPU of the RDS instance hardly crosses 80% during the bursts. So I doubt scaling it would do much too.

What other techniques can I do to avoid the database from being hit hard when the API is getting burst calls which are mostly unique and difficult to cache?

答:
Start with a covering index to handle your query. You might create an index like this for your table:

```<code>CREATE INDEX inv_lkup ON inventory (product_id, expired) INCLUDE (col, col, col);
</code>```

Mention all the columns in your SELECT in the index, either in the main list of indexed columns or in the INCLUDE clause. Then the DBMS can satisfy your query completely from the index. It's faster.

You could start using AWS lambda throttling to handle this problem. But, for that to work the consumers of your API will need to retry when they get 429 responses. That might be super-inconvenient.

Sorry to say, you may need to stop using lambda. Ordinary web servers have good stuff in them to manage burst workload.

They have an incoming connection (TCP/IP listen) queue. Each new request coming in lands in that queue, where it waits until the server software accept the connection. When the server is busy requests wait in that queue. When there's a high load the requests wait for a bit longer in that queue. In nodejs's case, if you use clustering there's just one of these incoming connection queues, and all the processes in the cluster use it.

The server software you run (to handle your API) has a pool of connections to your DBMS. That pool has a maximum number of connections it it. As your server software handles each request, it awaits a connection from the pool. If no connection is immediately available the request-handling pauses until one is available, then handles it.  This too smooths out the requests to the DBMS. (Be aware that each process in a nodejs cluster has its own pool.)

Paradoxically, a smaller DBMS connection pool can improve overall performance, by avoiding too many concurrent SELECTs (or other queries) on the DBMS.

This kind of server configuration can be scaled out: a load balancer will do. So will a server with more cores and more nodejs cluster processes. An elastic load balancer can also add new server VMs when necessary.

Body:
I have an API which allows other microservices to call on to check whether a particular product exists in the inventory. The API takes in only one parameter which is the ID of the product.

The API is served through API Gateway in Lambda and it simply queries against a Postgres RDS to check for the product ID. If it finds the product, it returns the information about the product in the response. If it doesn't, it just returns an empty response. The SQL is basically this:

SELECT * FROM inventory where expired = false and product_id = request.productId;

However, the problem is that many services are calling this particular API very heavily to check the existence of products. Not only that, the calls often come in bursts. I assume those services loop through a list of product IDs and check for their existence individually, hence the burst.

The number of concurrent calls on the API has resulted in it making many queries to the database. The rate can burst beyond 30 queries per sec and there can be a few hundred thousands of requests to fulfil. The queries are mostly the same, except for the product ID in the where clause. The column has been indexed and it takes an average of only 5-8ms to complete. Still, the connection to the database occasionally time out when the rate gets too high.

I'm using Sequelize as my ORM and the error I get when it time out is SequelizeConnectionAcquireTimeoutError. There is a good chance that the burst rate was too high and it max'ed out the pool too.

Some options I have considered:

Using a cache layer. But I have noticed that, most
of the time, 90% of the product IDs in the requests are not repeated.
This would mean that 90% of the time, it would be a cache miss and it
will still query against the database.

Auto scale up the database. But because the calls are bursty and I don't
know when they may come, the autoscaling won't complete in time to
avoid the time out. Moreover, the query is a very simple select statement and the CPU of the RDS instance hardly crosses 80% during the bursts. So I doubt scaling it would do much too.

What other techniques can I do to avoid the database from being hit hard when the API is getting burst calls which are mostly unique and difficult to cache?

Body:
Start with a covering index to handle your query. You might create an index like this for your table:

CREATE INDEX inv_lkup ON inventory (product_id, expired) INCLUDE (col, col, col);

Mention all the columns in your SELECT in the index, either in the main list of indexed columns or in the INCLUDE clause. Then the DBMS can satisfy your query completely from the index. It's faster.

You could start using AWS lambda throttling to handle this problem. But, for that to work the consumers of your API will need to retry when they get 429 responses. That might be super-inconvenient.

Sorry to say, you may need to stop using lambda. Ordinary web servers have good stuff in them to manage burst workload.

They have an incoming connection (TCP/IP listen) queue. Each new request coming in lands in that queue, where it waits until the server software accept the connection. When the server is busy requests wait in that queue. When there's a high load the requests wait for a bit longer in that queue. In nodejs's case, if you use clustering there's just one of these incoming connection queues, and all the processes in the cluster use it.

The server software you run (to handle your API) has a pool of connections to your DBMS. That pool has a maximum number of connections it it. As your server software handles each request, it awaits a connection from the pool. If no connection is immediately available the request-handling pauses until one is available, then handles it.  This too smooths out the requests to the DBMS. (Be aware that each process in a nodejs cluster has its own pool.)

Paradoxically, a smaller DBMS connection pool can improve overall performance, by avoiding too many concurrent SELECTs (or other queries) on the DBMS.

This kind of server configuration can be scaled out: a load balancer will do. So will a server with more cores and more nodejs cluster processes. An elastic load balancer can also add new server VMs when necessary.


来源: stackexchange

问:
Purpose of overloading member function returning iterator and const_iterator
In my class assignment I am suppose to implement member functions of a predefined class. I am confused on the purpose of these the overload on findStudent. Can this class not be designed to only contain one definition, which returns a regular iterator that can be casted as const? Or rather, use std::find since it is already overloaded to return a const_iterator?</p>

```<code>class Class{
public:
   Class(std::string name, std::string teacher, std::string capacity);
   std::string getTeacher();
   std::string getName();
   int getCapacity();
   void addStudent(std::string);
   void removeStudent(std::string);
   std::vector<std::string>::iterator findStudent();
   std::vector<std::string>::const_iterator findStudent() const;
private:
   std::string name;
   std::string teacher;
   int capacity;
   std::vector<std::string> students;
};
</code>```

答:
When a member function is const-qualified, it can be called on a const object.  (It can also be called on a non-const object, since a const conversion that ADDs const is a valid implicit conversion.)

Member functions that are not const qualified can only be called on non-const objects (because they can change the state of the object, defeating the meaning of const if such a conversion could happen.)

Thus:

```<code>class Foo {
public:
...
    int& operator[](int idx) { return values[idx]; }       // 1
    int operator[](int idx) const { return values[idx]; }  // 2
private:
    int values[10];
};
</code>```

We have two versions of operator[], one returning a mutable reference, and the other returning a copy (on which changes won't affect the object it came from.

And so

```<code>Foo f;
int& x = f[3]; // calls 1, since f is non-const

const Foo cf;
int y = cf[3]; // calls 2, since cf is const
</code>```

If you want your code to work on const and non-const objects, but always return a const_iterator, then you could get by with only implementing a version of findStudent that has the const qualification, like op 2 does above, and not overload it with the non-const version.

I am guessing that findStudent is supposed to take a name (or other criteria) and return an iterator to that student, or an "end" iterator if it's not found.  In that case, you'd use std::find() in the implementation of find_student.  So be sure to allow callers to say what student they want to find!

ContentLicense: CC BY-SA 4.0

Body:
In my class assignment I am suppose to implement member functions of a predefined class. I am confused on the purpose of these the overload on findStudent. Can this class not be designed to only contain one definition, which returns a regular iterator that can be casted as const? Or rather, use std::find since it is already overloaded to return a const_iterator?

class Class{
public:
   Class(std::string name, std::string teacher, std::string capacity);
   std::string getTeacher();
   std::string getName();
   int getCapacity();
   void addStudent(std::string);
   void removeStudent(std::string);
   std::vector<std::string>::iterator findStudent();
   std::vector<std::string>::const_iterator findStudent() const;
private:
   std::string name;
   std::string teacher;
   int capacity;
   std::vector<std::string> students;
};

Body:
When a member function is const-qualified, it can be called on a const object.  (It can also be called on a non-const object, since a const conversion that ADDs const is a valid implicit conversion.)

Member functions that are not const qualified can only be called on non-const objects (because they can change the state of the object, defeating the meaning of const if such a conversion could happen.)

Thus:

class Foo {
public:
...
    int& operator[](int idx) { return values[idx]; }       // 1
    int operator[](int idx) const { return values[idx]; }  // 2
private:
    int values[10];
};

We have two versions of operator[], one returning a mutable reference, and the other returning a copy (on which changes won't affect the object it came from.

And so

Foo f;
int& x = f[3]; // calls 1, since f is non-const

const Foo cf;
int y = cf[3]; // calls 2, since cf is const

If you want your code to work on const and non-const objects, but always return a const_iterator, then you could get by with only implementing a version of findStudent that has the const qualification, like op 2 does above, and not overload it with the non-const version.

I am guessing that findStudent is supposed to take a name (or other criteria) and return an iterator to that student, or an "end" iterator if it's not found.  In that case, you'd use std::find() in the implementation of find_student.  So be sure to allow callers to say what student they want to find!


答:
Use cache in the boot time

You can load all necessary columns into an in-memory data storage (redis). Every update in database (cron job) will affect cached data.

Problems: memory overhead of updating cache

Limit db calls

Create a buffer for ids. Store n ids and then make one query for all of them. Or empty the buffer every m seconds!

Problems: client response time extra process for query result

Change your database

Use NoSql database for these data.  According to this article and this one, I think choosing NoSql database is a better idea.

Problems: multiple data stores

Title: How to avoid database from being hit hard when API is getting bursted?


问:
How to get value from html input radio and put it in input hidden field in jsp java
I have the code for radio buttons

```<code><input type="radio" name="opt" id="1" value="1"/><label for="1">${dto.quesOpt1}</label>
<br/>
<input type="radio" name="opt" id="2" value="2"/><label for="2">${dto.quesOpt2}</label>
<br/>
<input type="radio" name="opt" id="3" value="3"/><label for="3">${dto.quesOpt3}</label>
<br/>
<input type="radio" name="opt" id="4" value="4"/><label for="4">${dto.quesOpt4}</label>
</code>```

And I want to put the value here so I can pass it to my Servlet

```<code><form action="MainController" method="POST">
       <input type="hidden" name="quesNum" value="${requestScope.QUESNUM}"/>
       <input type="hidden" name="quesId" value="${dto.quesId}"/>
       <input type="hidden" name="quesChoice" value="${param.opt}"/>               <--------- here
       <input type="hidden" name="amount" value="${requestScope.AMOUNT}"/>
       <input type="hidden" name="action" value="Previous Question"/>
       <input type="submit" value="Previous" <c:if test="${requestScope.QUESNUM == 0}">disabled</c:if>/>
</form>
</code>```

I always get null value in Servlet

```<code>request.getParameter("quesChoice")
</code>```

I don't know how to pass the value. Please guide me. Thank you.

答:
What you're trying to do is execute server side code (like ${dto.quesId}) inside the browser. You cannot do that.

What you're trying to do is super nasty and is probably not the right way to go. You probably don't need to copy the values from the radio to the form as you can put the radios directly inside the form.

JSPs are a super old technology that most companies have already abandoned years ago and those that still use it, plan to abandon it.

If you really have to use JSPs, your life would be much easier if you used JSTL libraries and MKYoung has some awesome tutorial on how to handle a lot of old java issues, including the one you're struggling with right now: https://mkyong.com/spring-mvc/spring-mvc-radiobutton-and-radiobuttons-example/

If you say "fuck it, I want to code it the way I was planning to do that all along anyway", you still need JavaScript to copy your values as this is the JavaScript that handles the browser-side actions.

Having said all that, this is how you can do it with pure JS:

```<code><html>
  <script>
    function copyValue() {
  let allOptions = Array.prototype.slice.call(document.getElementsByName('opt'));
  let selectedOption = allOptions.filter(opt => opt.checked)[0];
  let selectedOptionValue = selectedOption ? selectedOption.value : undefined;
  document.getElementById('quesNum').value = selectedOptionValue;
}
  </script>
  <body>
    <input type="radio" name="opt" id="1" value="1"/><label for="1">${dto.quesOpt1}</label>
    <br/>
    <input type="radio" name="opt" id="2" value="2"/><label for="2">${dto.quesOpt2}</label>
    <br/>
    <input type="radio" name="opt" id="3" value="3"/><label for="3">${dto.quesOpt3}</label>
    <br/>
    <input type="radio" name="opt" id="4" value="4"/><label for="4">${dto.quesOpt4}</label>

    <input type="hidden" name="quesNum" id="quesNum" value="${requestScope.QUESNUM}"/>

    <input type="button" value="Copy Value" onClick="copyValue()"/>
  </body>
</html>
</code>```

Note how I had to add the id="quesNum" and then the onClick="copyValue()" to trigger an action.

Here's the example in JSFiddle if you want to play with it: https://jsfiddle.net/kgjanowski/5ymubn6v/22/

Body:
I have the code for radio buttons

<input type="radio" name="opt" id="1" value="1"/>${dto.quesOpt1}

<input type="radio" name="opt" id="2" value="2"/>${dto.quesOpt2}

<input type="radio" name="opt" id="3" value="3"/>${dto.quesOpt3}

<input type="radio" name="opt" id="4" value="4"/>${dto.quesOpt4}

And I want to put the value here so I can pass it to my Servlet

<form action="MainController" method="POST">
       <input type="hidden" name="quesNum" value="${requestScope.QUESNUM}"/>
       <input type="hidden" name="quesId" value="${dto.quesId}"/>
       <input type="hidden" name="quesChoice" value="${param.opt}"/>               <--------- here
       <input type="hidden" name="amount" value="${requestScope.AMOUNT}"/>
       <input type="hidden" name="action" value="Previous Question"/>
       <input type="submit" value="Previous" <c:if test="${requestScope.QUESNUM == 0}">disabled</c:if>/>
</form>

I always get null value in Servlet

request.getParameter("quesChoice")

I don't know how to pass the value. Please guide me. Thank you.

Body:
What you're trying to do is execute server side code (like ${dto.quesId}) inside the browser. You cannot do that.

What you're trying to do is super nasty and is probably not the right way to go. You probably don't need to copy the values from the radio to the form as you can put the radios directly inside the form.

JSPs are a super old technology that most companies have already abandoned years ago and those that still use it, plan to abandon it.

If you really have to use JSPs, your life would be much easier if you used JSTL libraries and MKYoung has some awesome tutorial on how to handle a lot of old java issues, including the one you're struggling with right now: https://mkyong.com/spring-mvc/spring-mvc-radiobutton-and-radiobuttons-example/

If you say "fuck it, I want to code it the way I was planning to do that all along anyway", you still need JavaScript to copy your values as this is the JavaScript that handles the browser-side actions.

Having said all that, this is how you can do it with pure JS:

<html>
  <script>
    function copyValue() {
  let allOptions = Array.prototype.slice.call(document.getElementsByName('opt'));
  let selectedOption = allOptions.filter(opt => opt.checked)[0];
  let selectedOptionValue = selectedOption ? selectedOption.value : undefined;
  document.getElementById('quesNum').value = selectedOptionValue;
}
  </script>
  <body>
    <input type="radio" name="opt" id="1" value="1"/><label for="1">${dto.quesOpt1}</label>
    <br/>
    <input type="radio" name="opt" id="2" value="2"/><label for="2">${dto.quesOpt2}</label>
    <br/>
    <input type="radio" name="opt" id="3" value="3"/><label for="3">${dto.quesOpt3}</label>
    <br/>
    <input type="radio" name="opt" id="4" value="4"/><label for="4">${dto.quesOpt4}</label>

    <input type="hidden" name="quesNum" id="quesNum" value="${requestScope.QUESNUM}"/>

    <input type="button" value="Copy Value" onClick="copyValue()"/>
  </body>
</html>

Note how I had to add the id="quesNum" and then the onClick="copyValue()" to trigger an action.

Here's the example in JSFiddle if you want to play with it: https://jsfiddle.net/kgjanowski/5ymubn6v/22/


问:
php newsletter script duplicating body content
just done a little bit of code to send out a newsletter based on a sql table.

first one with 70/80 subscribers went off fine, now when i've moved to the second one that has around 250, the body_message of the email is repeated inside the email equally to the number of people on the mailing list, in this case I was sending emails with 250 duplicates of the content inside...

not sure whats wrong with the code, have stripped it down as much as i could and was wondering if someone could talk a look and hopefully point out the issue

```<code>    <?php

$i=1;
if (isset($_POST['submit_btn'])) {
connect_newsletter();

$result = mysql_query("SELECT id, mail FROM test") or die('Could not connect. ' . mysql_error());

while ($row = mysql_fetch_array($result)) {

    $email = $row['mail'];
    $nid = $row['id'];

    $ip=$_SERVER['REMOTE_ADDR'];

    $ref="http://www.domain.co.uk";

    $body_message ='newsletter html code';

    $y_email="noreply@domain.co.uk";
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers4=$y_email;
    $headers .="Reply-to: $headers4\n";
    $headers .= "From: $headers4\n";
    $headers .= "Errors-to: $headers4\n";

    $subject="subject";

    mail($email,$subject,$body_message,$headers);

    echo $i." sent to ".$email;
    echo "<br>";
    $i++;
}
}

?>
</code>```

答:
Watching your code that is not possibile because in the loop you safely reset the value of $body and $subject

The problem could be somewhere else. Check your sendmail log

ContentLicense: CC BY-SA 3.0

Body:
just done a little bit of code to send out a newsletter based on a sql table.

first one with 70/80 subscribers went off fine, now when i've moved to the second one that has around 250, the body_message of the email is repeated inside the email equally to the number of people on the mailing list, in this case I was sending emails with 250 duplicates of the content inside...

not sure whats wrong with the code, have stripped it down as much as i could and was wondering if someone could talk a look and hopefully point out the issue

    <?php

$i=1;
if (isset($_POST['submit_btn'])) {
connect_newsletter();

$result = mysql_query("SELECT id, mail FROM test") or die('Could not connect. ' . mysql_error());

while ($row = mysql_fetch_array($result)) {

    $email = $row['mail'];
    $nid = $row['id'];

    $ip=$_SERVER['REMOTE_ADDR'];

    $ref="http://www.domain.co.uk";

    $body_message ='newsletter html code';

    $y_email="noreply@domain.co.uk";
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers4=$y_email;
    $headers .="Reply-to: $headers4\n";
    $headers .= "From: $headers4\n";
    $headers .= "Errors-to: $headers4\n";

    $subject="subject";

    mail($email,$subject,$body_message,$headers);

    echo $i." sent to ".$email;
    echo "
";
    $i++;
}
}

?>


问:
How to pass specific links through LinkedIn Share Article?
When clicking on the LinkedIn button, the whole link doesn't get passed when the picture is clicked, however the facebook link works completely fine.
The linkedIn also used to work but not anymore, has anything changed since then?

```<code>            <div align="center">
              <a target="_blank" rel="noopener noreferrer" href={"https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2FmyCompany.com%2Fanbefal%3Fcompany%3D" + encodeURI(this.state.company) + "%26token%3D" + this.state.token + "&src=sdkpreparse"} className="fb-xfbml-parse-ignore"><img alt="Share Facebook" style={{ width: '40px', marginRight: '50px' }} src={require('../static/img/icons/facebook.png')} /></a>
              <a target="_blank" rel="noopener noreferrer" href={"https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2FmyCompany.com%2Fanbefal%3Fcompany%3D" + encodeURI(this.state.company) + "%26token%3D" + encodeURI(this.state.token) + "&src=sdkpreparse"} className="a2a_button_linkedin_share"><img alt="Share LinkedIn" style={{ width: '40px' }} src={require('../static/img/icons/linkedin.png')} /></a>
            </div>
            <br />
</code>```

Any help is appreciated!

答:
That is just a preview that you are seeing.  The full URLs still do fully display -- but only once they shared.

You can still pass specific links (i.e., not just a domain) to LinkedIn.  It seems, though, that the preview for the link is what is showing just the domain, instead of the full URL.  It's just a preview, though:

But now look at the LinkedIn conversation, after I have shared the URL...

See!  Even though the preview only lists example.com, the actual sharing will show example.com/Your/Full/Specific/Page.html.

Body:
When clicking on the LinkedIn button, the whole link doesn't get passed when the picture is clicked, however the facebook link works completely fine.
The linkedIn also used to work but not anymore, has anything changed since then?

Any help is appreciated!


问:
BS4 carousel indicator highlights wrong image on click (active)
I'm making a BS4 carousel.
I'm using Jquery to fetch images to display.
The images is named 1.jpg - 72.jpg
Everything works fine except the indicator thumbnails highlights wrong image on click.

If image 2 is clicked image 3 is highlighted etc.

I can't find out why this is happening.

here is a fiddle

I use this Jquery to fetch the images and append them to a div.

```<code>$(document).ready(function(){
  for(var j = 1; j < 72; j++) {
$('<div class="carousel-item"><img src=" ./images/'+ j+'.jpg " width="100%">
  </div>').appendTo('.carousel-inner');
$('<li data-target="#carousel" data-slide-to="'+j+'"><img  src=" ./images/'+ j+'.jpg " class="img- fluid"></li>').appendTo('.carousel-indicators')
console.log(j);
}
$('.carousel-item').first().addClass('active');
$('.carousel-indicators > li').first().addClass('active');
$('#carousel').carousel({
 pause: true,
 interval: true,
});
});
</code>```

The HTML is just basic.

```<code>
<div id="carousel" class="carousel slide" data-interval="false">
  <div class='carousel-outer'>
    <div class="carousel-inner"></div>
      <a class="carousel-control-prev" href="#carousel" data-slide="prev"> <span class="carousel-control-prev-icon"></span>
      </a>
      <a class="carousel-control-next" href="#carousel" data-slide="next"> <span class="carousel-control-next-icon"></span>
      </a>
     </div>
<!-- Indicators -->
    <ol class="carousel-indicators"></ol>
</div>

</code>```

The css

```<code>#carousel {
      margin: 20px auto;
      max-height:658px;
      width: 1024px;
  }
  #carousel .carousel-indicators {
    flex-wrap: wrap;
       justify-content: center;
       padding: 0 15px;
       width: 100%;
       position: static;
       right: 0;
       bottom: 0;
       margin-right: 0;
       margin-left: 0;

  }
  #carousel .carousel-indicators li {
      background-color: transparent;
      -webkit-border-radius: 0;
      border-radius: 0;
      display: inline-block;
      height: auto;
      margin: 0 !important;
      width: auto;
  }
  #carousel .carousel-indicators li img {
      width: 50px;
      display: block;
      opacity: 0.9;
  }
  #carousel .carousel-indicators li.active img {
      opacity: 1;
  }
  #carousel .carousel-indicators li:hover img {
      opacity: 0.75;
  }
  #carousel .carousel-outer {
      position: relative;
  }

  .carousel-item-next, .carousel-item-prev, .carousel-item.active {
    display: block !important;
}
</code>```

答:
I think the issue is with for loop it starts from 1 and for data-slide-to it must start with 0 , so you can try this

$('

').appendTo('.carousel-indicators')```

Body:
I'm making a BS4 carousel.
I'm using Jquery to fetch images to display.
The images is named 1.jpg - 72.jpg
Everything works fine except the indicator thumbnails highlights wrong image on click.

If image 2 is clicked image 3 is highlighted etc.

I can't find out why this is happening.

here is a fiddle

I use this Jquery to fetch the images and append them to a div.

$(document).ready(function(){
  for(var j = 1; j < 72; j++) {
$('

').appendTo('.carousel-inner');
$('

').appendTo('.carousel-indicators')
console.log(j);
}
$('.carousel-item').first().addClass('active');
$('.carousel-indicators > li').first().addClass('active');
$('#carousel').carousel({
 pause: true,
 interval: true,
});
});

The HTML is just basic.

The css

#carousel {
      margin: 20px auto;
      max-height:658px;
      width: 1024px;
  }
  #carousel .carousel-indicators {
    flex-wrap: wrap;
       justify-content: center;
       padding: 0 15px;
       width: 100%;
       position: static;
       right: 0;
       bottom: 0;
       margin-right: 0;
       margin-left: 0;

  }
  #carousel .carousel-indicators li {
      background-color: transparent;
      -webkit-border-radius: 0;
      border-radius: 0;
      display: inline-block;
      height: auto;
      margin: 0 !important;
      width: auto;
  }
  #carousel .carousel-indicators li img {
      width: 50px;
      display: block;
      opacity: 0.9;
  }
  #carousel .carousel-indicators li.active img {
      opacity: 1;
  }
  #carousel .carousel-indicators li:hover img {
      opacity: 0.75;
  }
  #carousel .carousel-outer {
      position: relative;
  }

  .carousel-item-next, .carousel-item-prev, .carousel-item.active {
    display: block !important;
}

Body:
I think the issue is with for loop it starts from 1 and for data-slide-to it must start with 0 , so you can try this

$('<li data-target="#carousel" data-slide-to="'+(j-1)+'"><img  src=" ./images/'+ j+'.jpg " class="img- fluid"></li>').appendTo('.carousel-indicators')


问:
How can I clear the localstorage when user close react application window?
I am developing a react-redux application where once the user logs in, I was to store some information about the user in local storage. This is so that I can easily retrieve the user information when they perform a action.

If the user close the browser window, I would like to clear all localstorage for the react application. How can I achieve that?

答:
To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close.

```<code>window.onunload = () => {
   // Clear the local storage
   window.MyStorage.clear()
}
</code>```

Body:
To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close.

window.onunload = () => {
   // Clear the local storage
   window.MyStorage.clear()
}


问:
How to find specific strings in a file?
This is a script that I have written to find all the lines with usb in it. However, the problem is that if also returns lines if they have words such as usbcore as well. I am interested in lines that contain only the words usb.</p>

```<code>#!/usr/bin/python

import sys

logFile = open(sys.argv[1])

print("Printing all lines with USB in it...")

for line in logFile.readlines():
    if line.lower().find('usb') != -1:
        print(line)

print('Done!')
</code>```

答:
You can try to find the word ' usb ' with spaces :

```<code>import sys

logFile = open(sys.argv[1])

print("Printing all lines with USB in it...")

for line in logFile.readlines():
    if line.lower().find(' usb ') != -1:
        print(line)

print('Done!')
</code>```

Example :

```<code>a = ' i have usbbox '
b = ' i have usb '
a.find('usb') # != -1
a.find(' usb ') # = -1 , bcs it doesnt contain the word 'usb' only
b.find(' usb ') # != -1 , it contains it
</code>```

Title: How to find specific strings in a file?

Body:
This is a script that I have written to find all the lines with usb in it. However, the problem is that if also returns lines if they have words such as usbcore as well. I am interested in lines that contain only the words usb.

#!/usr/bin/python

import sys

logFile = open(sys.argv[1])

print("Printing all lines with USB in it...")

for line in logFile.readlines():
    if line.lower().find('usb') != -1:
        print(line)

print('Done!')

Body:
You can try to find the word ' usb ' with spaces :

import sys

logFile = open(sys.argv[1])

print("Printing all lines with USB in it...")

for line in logFile.readlines():
    if line.lower().find(' usb ') != -1:
        print(line)

print('Done!')

Example :

a = ' i have usbbox '
b = ' i have usb '
a.find('usb') # != -1
a.find(' usb ') # = -1 , bcs it doesnt contain the word 'usb' only
b.find(' usb ') # != -1 , it contains it


问:
How can I resolve ReLU is not a member of torch::nn error while building?
I am trying to build a simple network using torch. But when I try to build the project it returns some error messages like error: ‘ReLU’ is not a member of ‘torch::nn’

My network definitions is as follows:

```<code>#pragma once

#include <torch/torch.h>

class ConvNetImpl : public torch::nn::Module {
 public:
    explicit ConvNetImpl(int64_t num_classes = 10);
    torch::Tensor forward(torch::Tensor x);

 private:
    torch::nn::Sequential layer1{
        torch::nn::Conv2d(torch::nn::Conv2dOptions(1, 16, 5).stride(1).padding(2)),
        torch::nn::BatchNorm2d(16),
        torch::nn::ReLU(),
        torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
    };

    torch::nn::Sequential layer2{
        torch::nn::Conv2d(torch::nn::Conv2dOptions(16, 32, 5).stride(1).padding(2)),
        torch::nn::BatchNorm2d(32),
        torch::nn::ReLU(),
        torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
    };

    torch::nn::Linear fc;
};

TORCH_MODULE(ConvNet);
</code>```

When I try to build with: cmake --build . --config Release

It returns me this message:

```<code>[ 33%] Building CXX object CMakeFiles/freespace_torch.dir/src/convnet.cpp.o
In file included from /home/fugurcal/freespace_torch/src/convnet.cpp:2:0:
/home/fugurcal/freespace_torch/include/convnet.h:13:20: error: ‘BatchNorm2d’ is not a member of ‘torch::nn’
         torch::nn::BatchNorm2d(16),
                    ^~~~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:13:20: note: suggested alternative: ‘BatchNorm’
         torch::nn::BatchNorm2d(16),
                    ^~~~~~~~~~~
                    BatchNorm
/home/fugurcal/freespace_torch/include/convnet.h:14:20: error: ‘ReLU’ is not a member of ‘torch::nn’
         torch::nn::ReLU(),
                    ^~~~
/home/fugurcal/freespace_torch/include/convnet.h:15:20: error: ‘MaxPool2d’ is not a member of ‘torch::nn’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                    ^~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:15:41: error: ‘MaxPool2dOptions’ is not a member of ‘torch::nn’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                                         ^~~~~~~~~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:15:41: note: suggested alternative: ‘Conv2dOptions’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                                         ^~~~~~~~~~~~~~~~
                                         Conv2dOptions
/home/fugurcal/freespace_torch/include/convnet.h:16:5: error: could not convert ‘{torch::nn::Conv2d((* &(& torch::nn::ConvOptions<2>(1, 16, torch::ExpandingArray<2, long int>(5)).torch::nn::ConvOptions<2>::stride(torch::ExpandingArray<2, long int>(1)))->torch::nn::ConvOptions<2>::padding(torch::ExpandingArray<2, long int>(2)))), <expression error>, <expression error>, <expression error>}’ from ‘<brace-enclosed initializer list>’ to ‘torch::nn::Sequential’
     };
     ^
/home/fugurcal/freespace_torch/include/convnet.h:20:20: error: ‘BatchNorm2d’ is not a member of ‘torch::nn’
         torch::nn::BatchNorm2d(32),
                    ^~~~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:20:20: note: suggested alternative: ‘BatchNorm’
         torch::nn::BatchNorm2d(32),
                    ^~~~~~~~~~~
                    BatchNorm
/home/fugurcal/freespace_torch/include/convnet.h:21:20: error: ‘ReLU’ is not a member of ‘torch::nn’
         torch::nn::ReLU(),
                    ^~~~
/home/fugurcal/freespace_torch/include/convnet.h:22:20: error: ‘MaxPool2d’ is not a member of ‘torch::nn’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                    ^~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:22:41: error: ‘MaxPool2dOptions’ is not a member of ‘torch::nn’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                                         ^~~~~~~~~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:22:41: note: suggested alternative: ‘Conv2dOptions’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                                         ^~~~~~~~~~~~~~~~
                                         Conv2dOptions
/home/fugurcal/freespace_torch/include/convnet.h:23:5: error: could not convert ‘{torch::nn::Conv2d((* &(& torch::nn::ConvOptions<2>(16, 32, torch::ExpandingArray<2, long int>(5)).torch::nn::ConvOptions<2>::stride(torch::ExpandingArray<2, long int>(1)))->torch::nn::ConvOptions<2>::padding(torch::ExpandingArray<2, long int>(2)))), <expression error>, <expression error>, <expression error>}’ from ‘<brace-enclosed initializer list>’ to ‘torch::nn::Sequential’
     };
     ^
CMakeFiles/freespace_torch.dir/build.make:62: recipe for target 'CMakeFiles/freespace_torch.dir/src/convnet.cpp.o' failed
make[2]: *** [CMakeFiles/freespace_torch.dir/src/convnet.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/freespace_torch.dir/all' failed
make[1]: *** [CMakeFiles/freespace_torch.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

I know mentioned methods are member of torch::nn. How can I resolve this issue?

答: Issue solved. While making "cmake -DCMAKE_PREFIX_PATH=/absolute/path/to/libtorch .." my libtorch directory was "/home/user/folder/libtorch". After changing the libtorch directory to "/home/user/libtorch" issue solved.</p>

Body:
I am trying to build a simple network using torch. But when I try to build the project it returns some error messages like error: ‘ReLU’ is not a member of ‘torch::nn’

My network definitions is as follows:

#pragma once

#include <torch/torch.h>

class ConvNetImpl : public torch::nn::Module {
 public:
    explicit ConvNetImpl(int64_t num_classes = 10);
    torch::Tensor forward(torch::Tensor x);

 private:
    torch::nn::Sequential layer1{
        torch::nn::Conv2d(torch::nn::Conv2dOptions(1, 16, 5).stride(1).padding(2)),
        torch::nn::BatchNorm2d(16),
        torch::nn::ReLU(),
        torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
    };

    torch::nn::Sequential layer2{
        torch::nn::Conv2d(torch::nn::Conv2dOptions(16, 32, 5).stride(1).padding(2)),
        torch::nn::BatchNorm2d(32),
        torch::nn::ReLU(),
        torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
    };

    torch::nn::Linear fc;
};

TORCH_MODULE(ConvNet);

When I try to build with: cmake --build . --config Release

It returns me this message:

[ 33%] Building CXX object CMakeFiles/freespace_torch.dir/src/convnet.cpp.o
In file included from /home/fugurcal/freespace_torch/src/convnet.cpp:2:0:
/home/fugurcal/freespace_torch/include/convnet.h:13:20: error: ‘BatchNorm2d’ is not a member of ‘torch::nn’
         torch::nn::BatchNorm2d(16),
                    ^~~~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:13:20: note: suggested alternative: ‘BatchNorm’
         torch::nn::BatchNorm2d(16),
                    ^~~~~~~~~~~
                    BatchNorm
/home/fugurcal/freespace_torch/include/convnet.h:14:20: error: ‘ReLU’ is not a member of ‘torch::nn’
         torch::nn::ReLU(),
                    ^~~~
/home/fugurcal/freespace_torch/include/convnet.h:15:20: error: ‘MaxPool2d’ is not a member of ‘torch::nn’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                    ^~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:15:41: error: ‘MaxPool2dOptions’ is not a member of ‘torch::nn’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                                         ^~~~~~~~~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:15:41: note: suggested alternative: ‘Conv2dOptions’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                                         ^~~~~~~~~~~~~~~~
                                         Conv2dOptions
/home/fugurcal/freespace_torch/include/convnet.h:16:5: error: could not convert ‘{torch::nn::Conv2d((* &(& torch::nn::ConvOptions<2>(1, 16, torch::ExpandingArray<2, long int>(5)).torch::nn::ConvOptions<2>::stride(torch::ExpandingArray<2, long int>(1)))->torch::nn::ConvOptions<2>::padding(torch::ExpandingArray<2, long int>(2)))), <expression error>, <expression error>, <expression error>}’ from ‘<brace-enclosed initializer list>’ to ‘torch::nn::Sequential’
     };
     ^
/home/fugurcal/freespace_torch/include/convnet.h:20:20: error: ‘BatchNorm2d’ is not a member of ‘torch::nn’
         torch::nn::BatchNorm2d(32),
                    ^~~~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:20:20: note: suggested alternative: ‘BatchNorm’
         torch::nn::BatchNorm2d(32),
                    ^~~~~~~~~~~
                    BatchNorm
/home/fugurcal/freespace_torch/include/convnet.h:21:20: error: ‘ReLU’ is not a member of ‘torch::nn’
         torch::nn::ReLU(),
                    ^~~~
/home/fugurcal/freespace_torch/include/convnet.h:22:20: error: ‘MaxPool2d’ is not a member of ‘torch::nn’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                    ^~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:22:41: error: ‘MaxPool2dOptions’ is not a member of ‘torch::nn’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                                         ^~~~~~~~~~~~~~~~
/home/fugurcal/freespace_torch/include/convnet.h:22:41: note: suggested alternative: ‘Conv2dOptions’
         torch::nn::MaxPool2d(torch::nn::MaxPool2dOptions(2).stride(2))
                                         ^~~~~~~~~~~~~~~~
                                         Conv2dOptions
/home/fugurcal/freespace_torch/include/convnet.h:23:5: error: could not convert ‘{torch::nn::Conv2d((* &(& torch::nn::ConvOptions<2>(16, 32, torch::ExpandingArray<2, long int>(5)).torch::nn::ConvOptions<2>::stride(torch::ExpandingArray<2, long int>(1)))->torch::nn::ConvOptions<2>::padding(torch::ExpandingArray<2, long int>(2)))), <expression error>, <expression error>, <expression error>}’ from ‘<brace-enclosed initializer list>’ to ‘torch::nn::Sequential’
     };
     ^
CMakeFiles/freespace_torch.dir/build.make:62: recipe for target 'CMakeFiles/freespace_torch.dir/src/convnet.cpp.o' failed
make[2]: *** [CMakeFiles/freespace_torch.dir/src/convnet.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/freespace_torch.dir/all' failed
make[1]: *** [CMakeFiles/freespace_torch.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

I know mentioned methods are member of torch::nn. How can I resolve this issue?


问:
Aggregate of string on anonymous type
I want to concat multiple string value into single string with comma separated,i tried using aggregate function but it shows cannot convert string to  how to fix this issue,

I tried below code

```<code>var res = (from e in WYNKContext.SurgeryAssigned.Where(x => x.CmpID == cmpid && x.IsCancelled == false)
                       select new
                       {
                           ID = e.SAID,
                           UIN = e.UIN,
                           SurgeryDate = e.SurgeryDate,
                           SurgeryID = e.SurgeryID,
                           Surgery = ((from st in WYNKContext.SurgeryTran.
                                       Where(x => x.SurgeryID ==  e.SurgeryID)
                                       select new
                                       {
                                             desc = icdmaster
                                                  .Where(x => x.ID ==
                                                   st.IcdSpecialityCode).Select(x =>
                                                   x.SpecialityDescription).FirstOrDefault(),
                                       }).ToList()).Aggregate((a, b) => a.desc + "," + b.desc),

                                     }).ToList();
</code>```

I want Output like inside surgery property like = string1,string 2 ,etc....

without using aggregate i am getting as count in  Surgery Property

```<code> var res = (from e in WYNKContext.SurgeryAssigned.Where(x => x.CmpID == cmpid && x.IsCancelled == false)
                           select new
                           {
                               ID = e.SAID,
                               UIN = e.UIN,
                               SurgeryDate = e.SurgeryDate,
                               SurgeryID = e.SurgeryID,
                               Surgery = (from st in WYNKContext.SurgeryTran.Where(x => x.SurgeryID == e.SurgeryID)
                                      select new
                                      {
                                          icd = icdmaster.Where(x => x.ID == st.IcdSpecialityCode).Select(x => x.SpecialityDescription).FirstOrDefault(),
                                       }).ToList(),

                                         }).ToList();
</code>```

also tried string join :

```<code>   Surgery = string.Join(",", (from st in WYNKContext.SurgeryTran.Where(x => x.SurgeryID == e.SurgeryID)
                              select new
                              {
                                  icd = icdmaster.Where(x => x.ID == st.IcdSpecialityCode).Select(x => x.SpecialityDescription).FirstOrDefault(),
                              }).ToList()),
</code>```

but in output  i am getting like this

```<code>Surgery ={ icd = CORNEA },{ icd = CATARACT/IOL }
</code>```

can some one tell what i did wrong in string.join.....

答:
The string class has a static method named Join, which takes in a collection of items and a string to join them with, which should work for you here.

If I'm reading your code correctly, it would look something like this:

```<code>Surgery = string.Join(",", WYNKContext.SurgeryTran
    .Where(surgTran => surgTran.SurgeryID == e.SurgeryID)
    .Select(surgTran => icdmaster
        .Where(icd => icd.ID == surgTran.IcdSpecialityCode)
        .Select(icd => icd.SpecialityDescription)
        .FirstOrDefault())),
</code>```

Title: Aggregate of string on anonymous type

Body:
I want to concat multiple string value into single string with comma separated,i tried using aggregate function but it shows cannot convert string to  how to fix this issue,

I tried below code

var res = (from e in WYNKContext.SurgeryAssigned.Where(x => x.CmpID == cmpid && x.IsCancelled == false)
                       select new
                       {
                           ID = e.SAID,
                           UIN = e.UIN,
                           SurgeryDate = e.SurgeryDate,
                           SurgeryID = e.SurgeryID,
                           Surgery = ((from st in WYNKContext.SurgeryTran.
                                       Where(x => x.SurgeryID ==  e.SurgeryID)
                                       select new
                                       {
                                             desc = icdmaster
                                                  .Where(x => x.ID ==
                                                   st.IcdSpecialityCode).Select(x =>
                                                   x.SpecialityDescription).FirstOrDefault(),
                                       }).ToList()).Aggregate((a, b) => a.desc + "," + b.desc),

                                     }).ToList();

I want Output like inside surgery property like = string1,string 2 ,etc....

without using aggregate i am getting as count in  Surgery Property

 var res = (from e in WYNKContext.SurgeryAssigned.Where(x => x.CmpID == cmpid && x.IsCancelled == false)
                           select new
                           {
                               ID = e.SAID,
                               UIN = e.UIN,
                               SurgeryDate = e.SurgeryDate,
                               SurgeryID = e.SurgeryID,
                               Surgery = (from st in WYNKContext.SurgeryTran.Where(x => x.SurgeryID == e.SurgeryID)
                                      select new
                                      {
                                          icd = icdmaster.Where(x => x.ID == st.IcdSpecialityCode).Select(x => x.SpecialityDescription).FirstOrDefault(),
                                       }).ToList(),

                                         }).ToList();

also tried string join :

   Surgery = string.Join(",", (from st in WYNKContext.SurgeryTran.Where(x => x.SurgeryID == e.SurgeryID)
                              select new
                              {
                                  icd = icdmaster.Where(x => x.ID == st.IcdSpecialityCode).Select(x => x.SpecialityDescription).FirstOrDefault(),
                              }).ToList()),

but in output  i am getting like this

Surgery ={ icd = CORNEA },{ icd = CATARACT/IOL }

can some one tell what i did wrong in string.join.....

Body:
The string class has a static method named Join, which takes in a collection of items and a string to join them with, which should work for you here.

If I'm reading your code correctly, it would look something like this:

Surgery = string.Join(",", WYNKContext.SurgeryTran
    .Where(surgTran => surgTran.SurgeryID == e.SurgeryID)
    .Select(surgTran => icdmaster
        .Where(icd => icd.ID == surgTran.IcdSpecialityCode)
        .Select(icd => icd.SpecialityDescription)
        .FirstOrDefault())),


问:
Javascript array, building from a set of variables
The variables following are defined through a Car prototype:

var Car = function(maker, type, model) {
  this.maker = maker;
  this.type = type;
  this.model = model;
}

var golf = new Car('VW', 'Hatchback', 'Golf');
var sentra = new Car('Nissan', 'Sedan', 'Sentra');
var _328i = new Car('BMW', 'Convertible', "328i");
var gallardo = new Car('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");

Car.prototype.year = 0;

golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;
```

How does one build an array of the var values for the property maker

Something that might console log like this:

(5) ['VW', 'Nissan', 'BMW', 'Lamborghini', 'Roll Royce']

答:
You could create an array of the car instances and use the map function

console.log(
  [golf, sentra, _328i, gallardo, corniche].map((car) => car.maker)
)
```

Body:
The variables following are defined through a Car prototype:

var Car = function(maker, type, model) {
  this.maker = maker;
  this.type = type;
  this.model = model;
}

var golf = new Car('VW', 'Hatchback', 'Golf');
var sentra = new Car('Nissan', 'Sedan', 'Sentra');
var _328i = new Car('BMW', 'Convertible', "328i");
var gallardo = new Car('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");

Car.prototype.year = 0;

golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;

How does one build an array of the var values for the property maker

Something that might console log like this:

(5) ['VW', 'Nissan', 'BMW', 'Lamborghini', 'Roll Royce']


问:
I am using jupyter i am not able to find the video file
I have 120 images at folder in Jupyter.

I want to create a video from this images, and I am using OpenCV tool but i am not able to find the video.

```<code>import cv2
image = ''
image_arr = []
for i in range(1,121):
    if i < 10:
        x =  '000' + str(i)
        image = x + '.jpg'
        out_scores, out_boxes, out_classes,output_image = predict(sess, image)
        image_arr.append(output_image)

    if 100 > i >= 10:
        x =  '00' + str(i)
        image = x + '.jpg'
        out_scores, out_boxes, out_classes,output_image = predict(sess, image)
        image_arr.append(output_image)
    if  i >= 100:
        x =  '0' + str(i)
        image = x + '.jpg'
        out_scores, out_boxes, out_classes,output_image = predict(sess, image)
        image_arr.append(output_image)
#To Create video
video = cv2.VideoWriter('test.avi',cv2.VideoWriter_fourcc(*'mp4v'), 20, (608,608))
for i in range(len(image_arr)):
    video.write(image_arr[i])
cv2.destroyAllWindows()
video.release()
</code>```

Can someone please tell me what's wrong?

答:
You can't *store files in Jupyter. It's a python virtualization manager, not a file system (unless you are talking about JupyterHub). You placed the file in some directory on your PC. Find where that is. In a new cell in your notebook, type the following:

```<code>!pwd
</code>```

This will print the current directory of your notebook. At this point, you can move the images to the folder of your jupyter instance or you can run jupyter in a different directory.

Body:
I have 120 images at folder in Jupyter.

I want to create a video from this images, and I am using OpenCV tool but i am not able to find the video.

import cv2
image = ''
image_arr = []
for i in range(1,121):
    if i < 10:
        x =  '000' + str(i)
        image = x + '.jpg'
        out_scores, out_boxes, out_classes,output_image = predict(sess, image)
        image_arr.append(output_image)

    if 100 > i >= 10:
        x =  '00' + str(i)
        image = x + '.jpg'
        out_scores, out_boxes, out_classes,output_image = predict(sess, image)
        image_arr.append(output_image)
    if  i >= 100:
        x =  '0' + str(i)
        image = x + '.jpg'
        out_scores, out_boxes, out_classes,output_image = predict(sess, image)
        image_arr.append(output_image)
#To Create video
video = cv2.VideoWriter('test.avi',cv2.VideoWriter_fourcc(*'mp4v'), 20, (608,608))
for i in range(len(image_arr)):
    video.write(image_arr[i])
cv2.destroyAllWindows()
video.release()

Can someone please tell me what's wrong?

Body:
You can't *store files in Jupyter. It's a python virtualization manager, not a file system (unless you are talking about JupyterHub). You placed the file in some directory on your PC. Find where that is. In a new cell in your notebook, type the following:

!pwd

This will print the current directory of your notebook. At this point, you can move the images to the folder of your jupyter instance or you can run jupyter in a different directory.


答:
Most probably it happens because of the loop starting from 1 instead of 0.

A possible fix would be to change the data-slide-to attribute's value to j - 1 instead of j:

```<code>$(document).ready(function(){
  for(var j = 1; j < 72; j++) {
    $('<div class="carousel-item"><img src=" ./images/'+ j +'.jpg " width="100%"></div>').appendTo('.carousel-inner');
    $('<li data-target="#carousel" data-slide-to="'+ (j - 1) +'"><img  src=" ./images/'+ j +'.jpg " class="img- fluid"></li>').appendTo('.carousel-indicators')
console.log(j);
}
    $('.carousel-item').first().addClass('active');
    $('.carousel-indicators > li').first().addClass('active');
    $('#carousel').carousel({
        pause: true,
        interval: true,
    });
});
</code>```

Title: BS4 carousel indicator highlights wrong image on click (active)

Body:
Most probably it happens because of the loop starting from 1 instead of 0.

A possible fix would be to change the data-slide-to attribute's value to j - 1 instead of j:

$(document).ready(function(){
  for(var j = 1; j < 72; j++) {
    $('<div class="carousel-item"><img src=" ./images/'+ j +'.jpg " width="100%"></div>').appendTo('.carousel-inner');
    $('<li data-target="#carousel" data-slide-to="'+ (j - 1) +'"><img  src=" ./images/'+ j +'.jpg " class="img- fluid"></li>').appendTo('.carousel-indicators')
console.log(j);
}
    $('.carousel-item').first().addClass('active');
    $('.carousel-indicators > li').first().addClass('active');
    $('#carousel').carousel({
        pause: true,
        interval: true,
    });
});


问:
Custom Kafka Connector : Connector has errored out but Tasks are still running
I am building a Custom Kafka Source connector. This connector is up and running. I use the rest API to update the connector configuration settings (Source endpoint and connection key for instance). I use the below Rest API

PUT /connectors/{name}/config

Due to some issue the (wrong key for instance) the API does not succeed and the Connector fails

The API output is as below. Note that connector is in failed state, but the tasks are still running. In fact they are still 'connected' to the old endpoint and connection key instead of gracefully terminating the task.

```<code>{
    "name": "CustomSrcConnector_V1",
    "connector": {
        "state": "FAILED",
        "worker_id": "XXX.XX.XX.XX:8083",
        "trace": "org.apache.kafka.connect.errors.ConnectException: Exception happened at Create : Exception in getPartitions()\n\tat com.xxx.yyy.kafka.connect.eventhub.CustomSourceConnector.start(CustomSourceConnector.java:102)\n\tat org.apache.kafka.connect.runtime.WorkerConnector.doStart(WorkerConnector.java:111)\n\tat org.apache.kafka.connect.runtime.WorkerConnector.start(WorkerConnector.java:136)\n\tat org.apache.kafka.connect.runtime.WorkerConnector.transitionTo(WorkerConnector.java:196)\n\tat org.apache.kafka.connect.runtime.Worker.startConnector(Worker.java:242)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.startConnector(DistributedHerder.java:908)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.processConnectorConfigUpdates(DistributedHerder.java:345)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.tick(DistributedHerder.java:317)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.run(DistributedHerder.java:219)\n\tat java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)\n\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\n\tat java.base/java.lang.Thread.run(Thread.java:834)\n"
    },
    "tasks": [
        {
            "id": 0,
            "state": "RUNNING",
            "worker_id": "XXX.XX.XX.XX:8083"
        },
        {
            "id": 1,
            "state": "RUNNING",
            "worker_id": "XXX.XX.XX.XX:8083"
        }
    ],
    "type": "source"
}
</code>```

I understand that the tasks and connectors are generally decoupled. However i would like to know if there is any way of gracefully shutting down the tasks if the connector has errored out during the Conenctor configuration update.

答:
As of now there is no way to force fail tasks when the connector fails.

The solution I found so far is to catch any exceptions in the source connector and then instead of raising an exception in the source connector, allow the taskConfigs method run and reinitialize the tasks. We would need to allow the tasks to fail, so as a result we can have the connectors in RUNNING state, but the tasks as FAILED.
This will be in line with the example shared by  Iskuskov Alexander above

https://issues.apache.org/jira/browse/KAFKA-9639

Body:
I am building a Custom Kafka Source connector. This connector is up and running. I use the rest API to update the connector configuration settings (Source endpoint and connection key for instance). I use the below Rest API

PUT /connectors/{name}/config

Due to some issue the (wrong key for instance) the API does not succeed and the Connector fails

The API output is as below. Note that connector is in failed state, but the tasks are still running. In fact they are still 'connected' to the old endpoint and connection key instead of gracefully terminating the task.

{
    "name": "CustomSrcConnector_V1",
    "connector": {
        "state": "FAILED",
        "worker_id": "XXX.XX.XX.XX:8083",
        "trace": "org.apache.kafka.connect.errors.ConnectException: Exception happened at Create : Exception in getPartitions()\n\tat com.xxx.yyy.kafka.connect.eventhub.CustomSourceConnector.start(CustomSourceConnector.java:102)\n\tat org.apache.kafka.connect.runtime.WorkerConnector.doStart(WorkerConnector.java:111)\n\tat org.apache.kafka.connect.runtime.WorkerConnector.start(WorkerConnector.java:136)\n\tat org.apache.kafka.connect.runtime.WorkerConnector.transitionTo(WorkerConnector.java:196)\n\tat org.apache.kafka.connect.runtime.Worker.startConnector(Worker.java:242)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.startConnector(DistributedHerder.java:908)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.processConnectorConfigUpdates(DistributedHerder.java:345)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.tick(DistributedHerder.java:317)\n\tat org.apache.kafka.connect.runtime.distributed.DistributedHerder.run(DistributedHerder.java:219)\n\tat java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)\n\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\n\tat java.base/java.lang.Thread.run(Thread.java:834)\n"
    },
    "tasks": [
        {
            "id": 0,
            "state": "RUNNING",
            "worker_id": "XXX.XX.XX.XX:8083"
        },
        {
            "id": 1,
            "state": "RUNNING",
            "worker_id": "XXX.XX.XX.XX:8083"
        }
    ],
    "type": "source"
}

I understand that the tasks and connectors are generally decoupled. However i would like to know if there is any way of gracefully shutting down the tasks if the connector has errored out during the Conenctor configuration update.


问:
What is the meaning of : "Events are received on the UI thread and read on the main loop thread"?
Recently I've been doing Android development with the book Beginning Android Games. It contains the following code:

```<code>public class KeyboardHandler implements OnKeyListener {
    boolean[] pressedKeys = new boolean[128];
    Pool<KeyEvent> keyEventPool;
    List<KeyEvent> keyEventsBuffer = new ArrayList<KeyEvent>();
    List<KeyEvent> keyEvents = new ArrayList<KeyEvent>();
    public KeyboardHandler(View view) {
        PoolObjectFactory<KeyEvent> factory = new PoolObjectFactory<KeyEvent>() {
            public KeyEvent createObject() {
                return new KeyEvent();
            }
        };
        keyEventPool = new Pool<KeyEvent>(factory, 100);
        view.setOnKeyListener(this);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
    }
    public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
        if (event.getAction() == android.view.KeyEvent.ACTION_MULTIPLE)
            return false;

        synchronized (this) {
            KeyEvent keyEvent = keyEventPool.newObject();
            keyEvent.keyCode = keyCode;
            keyEvent.keyChar = (char) event.getUnicodeChar();
            if (event.getAction() == android.view.KeyEvent.ACTION_DOWN) {
                keyEvent.type = KeyEvent.KEY_DOWN;
                if(keyCode > 0 && keyCode < 127)
                    pressedKeys[keyCode] = true;
            }
            if (event.getAction() == android.view.KeyEvent.ACTION_UP) {
                keyEvent.type = KeyEvent.KEY_UP;
                if(keyCode > 0 && keyCode < 127)
                    pressedKeys[keyCode] = false;
            }
            keyEventsBuffer.add(keyEvent);
        }
        return false;
    }
</code>```

Once again I was a bit confused on why synchronized was necessary, and the book states:
"Remember
that the events are received on the UI thread and read on the main loop thread, so we
have to make sure none of our members are accessed in parallel. "
First of all, I thought the UI thread was the same as the main thread(or main loop thread, is there a difference?) Say the UI thread is executing this code, therefore also receiving the events(since this class implements  OnClickListener). Say the main loop, the while(!userquit) loop, runs on a seperate thread. How are the events read by the main loop thread? Also, shouldn't the main loop run on the UI thread? Is my notion about Event Handling correct? When a keyEvent occurs, the thread executing KeyboardHandler has the code onKey() executed. How are events received on the UI thread, but read on the Main Loop thread? Shouldn't events be recieved and handled on the same thread?

答:
In Android, you cannot access User-Interface components outside of the main thread. It prevents all sort of errors with multi-threading. To access a UI component, either way, you can use the context.runOnUiThread method which allows you to run your commands on the UI thread, just as the name suggests.

Another way would be using the synchronized keyword, which, just as explained in this answer, allows two threads to read and write to each other. That way, the synchronized keyword allows non-UI threads to still interact with UI components.

Body:
Recently I've been doing Android development with the book Beginning Android Games. It contains the following code:

public class KeyboardHandler implements OnKeyListener {
    boolean[] pressedKeys = new boolean[128];
    Pool<KeyEvent> keyEventPool;
    List<KeyEvent> keyEventsBuffer = new ArrayList<KeyEvent>();
    List<KeyEvent> keyEvents = new ArrayList<KeyEvent>();
    public KeyboardHandler(View view) {
        PoolObjectFactory<KeyEvent> factory = new PoolObjectFactory<KeyEvent>() {
            public KeyEvent createObject() {
                return new KeyEvent();
            }
        };
        keyEventPool = new Pool<KeyEvent>(factory, 100);
        view.setOnKeyListener(this);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
    }
    public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
        if (event.getAction() == android.view.KeyEvent.ACTION_MULTIPLE)
            return false;

        synchronized (this) {
            KeyEvent keyEvent = keyEventPool.newObject();
            keyEvent.keyCode = keyCode;
            keyEvent.keyChar = (char) event.getUnicodeChar();
            if (event.getAction() == android.view.KeyEvent.ACTION_DOWN) {
                keyEvent.type = KeyEvent.KEY_DOWN;
                if(keyCode > 0 && keyCode < 127)
                    pressedKeys[keyCode] = true;
            }
            if (event.getAction() == android.view.KeyEvent.ACTION_UP) {
                keyEvent.type = KeyEvent.KEY_UP;
                if(keyCode > 0 && keyCode < 127)
                    pressedKeys[keyCode] = false;
            }
            keyEventsBuffer.add(keyEvent);
        }
        return false;
    }

Once again I was a bit confused on why synchronized was necessary, and the book states:
"Remember
that the events are received on the UI thread and read on the main loop thread, so we
have to make sure none of our members are accessed in parallel. "
First of all, I thought the UI thread was the same as the main thread(or main loop thread, is there a difference?) Say the UI thread is executing this code, therefore also receiving the events(since this class implements  OnClickListener). Say the main loop, the while(!userquit) loop, runs on a seperate thread. How are the events read by the main loop thread? Also, shouldn't the main loop run on the UI thread? Is my notion about Event Handling correct? When a keyEvent occurs, the thread executing KeyboardHandler has the code onKey() executed. How are events received on the UI thread, but read on the Main Loop thread? Shouldn't events be recieved and handled on the same thread?


问:
yaml key value pair with dollar syntax
I saw a code which is present in a Spring boot application's yaml file

```<code>task:
  follow: ${name:Rohit}
</code>```

I know task.follow is the key but didn't understand ${name:Rohit}. What does it refer to and how to use it.

答: It means that the key task.follow should take the value from Environment Property name, but if it was not defined while your spring boot app starts up, then it will take the default value Robit.

Title: yaml key value pair with dollar syntax

Body:
I saw a code which is present in a Spring boot application's yaml file

task:
  follow: ${name:Rohit}

I know task.follow is the key but didn't understand ${name:Rohit}. What does it refer to and how to use it.


问:
I am getting time limit error in the competition platform for my code
I am trying to solve this problem in the online coding platform(question given below) with the below code. The competition platform shows time limit error.

QUESTION:

Tahir and Mamta are woking in a project in TCS. Tahir being a problem solver came up with an interesting problem for his friend Mamta.

Problem consists of a string of length N and contains only small case alphabets.

It will be followed by Q queries, in which each query will contain an integer P (1<=P<=N) denoting a position within the string.

Mamta's task is to find the alphabet present at that location and determine the number of occurrence of same alphabet preceding the given location P.

Mamta is busy with her office work. Therefore, she asked you to help her.

Constraints

1 <= N <= 500000

S consisting of small case alphabets

1 <= Q <= 10000

1 <= P <= N

Input Format
First line contains an integer N, denoting the length of string.

Second line contains string S itself consists of small case alphabets only ('a' - 'z').

Third line contains an integer Q denoting number of queries that will be asked.

Next Q lines contains an integer P (1 <= P <= N) for which you need to find the number occurrence of character present at the Pth location preceeding P.

Output
For each query, print an integer denoting the answer on single line.

Time Limit

1

My code:

```<code>n=int(input())
a=input()[:n]
for i in range(int(input())):
    p=int(input())
    print(a[:p-1].count(a[p-1]))
</code>```

Sample Input,Output:

Example 1

Input

9

abacsddaa

2

9

3

Output

3

1

Explanation

Here Q = 2

For P=9, character at 9th location is 'a'. Number of occurrences of 'a' before P i.e., 9 is three.

Similarly for P=3, 3rd character is 'a'. Number of occurrences of 'a' before P. i.e., 3 is one.

I'm new to Python so please help me with the error.

答:
Your solution's complexity is O(n2) and it causes the time limit error.
You should use the prefix sum array algorithm. Take a look at this link and define a prefix sum array for every alphabet.

Body:
I am trying to solve this problem in the online coding platform(question given below) with the below code. The competition platform shows time limit error.

QUESTION:

Tahir and Mamta are woking in a project in TCS. Tahir being a problem solver came up with an interesting problem for his friend Mamta.

Problem consists of a string of length N and contains only small case alphabets.

It will be followed by Q queries, in which each query will contain an integer P (1<=P<=N) denoting a position within the string.

Mamta's task is to find the alphabet present at that location and determine the number of occurrence of same alphabet preceding the given location P.

Mamta is busy with her office work. Therefore, she asked you to help her.

Constraints

1 <= N <= 500000

S consisting of small case alphabets

1 <= Q <= 10000

1 <= P <= N

Input Format
First line contains an integer N, denoting the length of string.

Second line contains string S itself consists of small case alphabets only ('a' - 'z').

Third line contains an integer Q denoting number of queries that will be asked.

Next Q lines contains an integer P (1 <= P <= N) for which you need to find the number occurrence of character present at the Pth location preceeding P.

Output
For each query, print an integer denoting the answer on single line.

Time Limit

1

My code:

n=int(input())
a=input()[:n]
for i in range(int(input())):
    p=int(input())
    print(a[:p-1].count(a[p-1]))

Sample Input,Output:

Example 1

Input

9

abacsddaa

2

9

3

Output

3

1

Explanation

Here Q = 2

For P=9, character at 9th location is 'a'. Number of occurrences of 'a' before P i.e., 9 is three.

Similarly for P=3, 3rd character is 'a'. Number of occurrences of 'a' before P. i.e., 3 is one.

I'm new to Python so please help me with the error.


问:
Azure Application Gateway + WAF: turn down on CRON

Objective

I'm going to use Azure Application Gateway. I'm expecting it would be triggered few times a day (integration with external tools), so I'm expecting it to be very cheap. Though from pricing details I have to use Medium, because only Medium supports WAF.

Issue

I can't find a good way to start and stop App Gateway & WAF based on CRON. Because of that instead of paying < 1$ / month I have to pay 100$/month for the environment.

Question

What is the good way to start/stop App Gateway + WAF based on CRON and pay on per-minute basis as promised?

答:
If you know when you will receive the calls (like a set time range each day) you could use Azure Functions with a timer job and a Managed Identity to spin up and then spin down an App Gateway.   Azure Functions supports PowerShell so all the automation could be down in that pattern.

Generally speaking, most customers do not treat App Gateways with WAF as dynamic scale to zero resources.  Typically they are tied to DNS entries (fqdn) and therefore need to be up most of the time.


问:
How to divide total days output by individual year in python so that total days doesn't effect one particular year
Iam currently working on analyzing the delay in the response to a request made to each department. Format of data is as below:

```<code>Department     RequestDate     ResponseDate
Electronics    2019-05-01      2019-09-19
Babyshop       2018-08-02      2019-09-30
Grocery        2016-01-01      2018-01-01
Pharmacy       2015-03-01      2018-03-01
</code>```

What iam trying to accomplish is divide total days into respective years. The expected output is as below:

```<code>Department     RequestDate     ResponseDate   2015  2016  2017  2018  2019    TotalDays
Electronics    2019-05-01      2019-09-19      0      0    0     0     149     149
Babyshop       2018-08-02      2019-09-30      0      0    0     152   272     424
Grocery        2016-01-01      2018-01-01      0      365  365   1     0       731
Pharmacy       2015-03-01      2018-03-01      306    365  365   60    0       1096
</code>```

currently my workflow is in excel and it is tidious. Is there any way to make use of python functions.

答:
Since I don't have enough reputation to comment here is an answer.

So  my idea to make this frame would use DateTime and pandas. Supposing your data is on a csv file: 'yourfile.csv':

```<code>import pandas as pd
from datetime import datetime
import time

your_data = pd.read_csv('yourfile.csv')

def take_columns(date):
    '''
    Transform the columns into datetime type
    '''
    date = datetime(*(time.strptime(date, '%Y-%m-%d')[:6]))
    return date

def count_year(start, end):
    '''
    Returns a dict, with the years as keys, and the
    days of that year as value
    '''
    yearsDict = {}
    delta = end-start
    while delta.days>0:
        if end.year > start.year:
            new_year = datetime(start.year+1,1,1,0,0)
            days_year = new_year - start
            yearsDict[start.year] = yearsDict.get(start.year, days_year.days)
            start = new_year
            delta = end - new_year
        elif end.year == start.year:
            new_year = datetime(start.year,1,1,0,0)
        if delta.days<365:
            yearsDict[new_year.year] = yearsDict.get(new_year.year, delta.days)
            break
    return yearsDict

your_data = your_data.set_index(['Department']) #set the index of the DataFrame
new_columns = set() #to add the new columns with the years

#here we transform the columns into datetime format
your_data['RequestDate'] = your_data['RequestDate'].apply(lambda x: take_columns(str(x)))
your_data['ResponseDate'] = your_data['ResponseDate'].apply(lambda x: take_columns(str(x)))

#now we're gonna read the RequestDate column to make a set with the years
#the set is to avoid repeat the years
your_data['RequestDate'].apply(lambda x: new_columns.add(x.year))

#and create the columns
for column_name in range(min(new_columns), max(new_columns)+1):
    your_data[column_name] = 0

your_data['TotalDays'] = your_data['ResponseDate'] - your_data['RequestDate'] #this is for the 'TotalDays' column

#and finally we add the values on the years
for row in your_data.index:
    years = count_year(your_data.loc[row]['RequestDate'],your_data.loc[row]['ResponseDate'])
    for year in years:
        your_data.at[row,year] = years[year]
</code>```

Now you can export the result('your_data') to a file for example:

```<code>your_data.to_csv('your_new_file.csv')
</code>```

don't know if is the best way but it worked.

Body:
Iam currently working on analyzing the delay in the response to a request made to each department. Format of data is as below:

Department     RequestDate     ResponseDate
Electronics    2019-05-01      2019-09-19
Babyshop       2018-08-02      2019-09-30
Grocery        2016-01-01      2018-01-01
Pharmacy       2015-03-01      2018-03-01

What iam trying to accomplish is divide total days into respective years. The expected output is as below:

Department     RequestDate     ResponseDate   2015  2016  2017  2018  2019    TotalDays
Electronics    2019-05-01      2019-09-19      0      0    0     0     149     149
Babyshop       2018-08-02      2019-09-30      0      0    0     152   272     424
Grocery        2016-01-01      2018-01-01      0      365  365   1     0       731
Pharmacy       2015-03-01      2018-03-01      306    365  365   60    0       1096

currently my workflow is in excel and it is tidious. Is there any way to make use of python functions.

Body:
Since I don't have enough reputation to comment here is an answer.

So  my idea to make this frame would use DateTime and pandas. Supposing your data is on a csv file: 'yourfile.csv':

import pandas as pd
from datetime import datetime
import time

your_data = pd.read_csv('yourfile.csv')

def take_columns(date):
    '''
    Transform the columns into datetime type
    '''
    date = datetime(*(time.strptime(date, '%Y-%m-%d')[:6]))
    return date

def count_year(start, end):
    '''
    Returns a dict, with the years as keys, and the
    days of that year as value
    '''
    yearsDict = {}
    delta = end-start
    while delta.days>0:
        if end.year > start.year:
            new_year = datetime(start.year+1,1,1,0,0)
            days_year = new_year - start
            yearsDict[start.year] = yearsDict.get(start.year, days_year.days)
            start = new_year
            delta = end - new_year
        elif end.year == start.year:
            new_year = datetime(start.year,1,1,0,0)
        if delta.days<365:
            yearsDict[new_year.year] = yearsDict.get(new_year.year, delta.days)
            break
    return yearsDict

your_data = your_data.set_index(['Department']) #set the index of the DataFrame
new_columns = set() #to add the new columns with the years

#here we transform the columns into datetime format
your_data['RequestDate'] = your_data['RequestDate'].apply(lambda x: take_columns(str(x)))
your_data['ResponseDate'] = your_data['ResponseDate'].apply(lambda x: take_columns(str(x)))

#now we're gonna read the RequestDate column to make a set with the years
#the set is to avoid repeat the years
your_data['RequestDate'].apply(lambda x: new_columns.add(x.year))

#and create the columns
for column_name in range(min(new_columns), max(new_columns)+1):
    your_data[column_name] = 0

your_data['TotalDays'] = your_data['ResponseDate'] - your_data['RequestDate'] #this is for the 'TotalDays' column

#and finally we add the values on the years
for row in your_data.index:
    years = count_year(your_data.loc[row]['RequestDate'],your_data.loc[row]['ResponseDate'])
    for year in years:
        your_data.at[row,year] = years[year]

Now you can export the result('your_data') to a file for example:

your_data.to_csv('your_new_file.csv')

don't know if is the best way but it worked.


问:
Plugin project :firebase_core_web not found
I try to connect Android project to Firebase but I get this error as I added the following to pubsec.yaml:

```<code>firebase_auth: ^0.16.0
cloud_firestore: ^0.13.5
</code>```

when I gradle run and it is not working

```<code>Plugin project :firebase_core_web not found. Please update settings.gradle.
Plugin project :firebase_auth_web not found. Please update settings.gradle.
Plugin project :cloud_firestore_web not found. Please update settings.gradle.
</code>```

Is there any solution for it

答:
Please add this in flutter app -> android -> settings.gradle

```<code>def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()

    def plugins = new Properties()

    def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
    if (pluginsFile.exists()) {

        pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
    }

    plugins.each { name, path ->
        def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
        include ":$name"
        project(":$name").projectDir = pluginDirectory
    }
</code>```

Body:
I try to connect Android project to Firebase but I get this error as I added the following to pubsec.yaml:

firebase_auth: ^0.16.0
cloud_firestore: ^0.13.5

when I gradle run and it is not working

Plugin project :firebase_core_web not found. Please update settings.gradle.
Plugin project :firebase_auth_web not found. Please update settings.gradle.
Plugin project :cloud_firestore_web not found. Please update settings.gradle.

Is there any solution for it

Body:
Please add this in flutter app -> android -> settings.gradle

def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()

    def plugins = new Properties()

    def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
    if (pluginsFile.exists()) {

        pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
    }

    plugins.each { name, path ->
        def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
        include ":$name"
        project(":$name").projectDir = pluginDirectory
    }


问:
Laravel flatten and pluck from multidimensional collection
I have to retrieve just an array of id from the given collection, something like [10,54,61,21,etc].
I've tried flatten, pluck, but nothing seems to work apart from a foreach which is something I would like to remove at this step.

```<code>// Model
class Children extends Eloquent {
    public function directChildrens(){
        return $this->hasMany('App\Children','father_id','id')->select('id','father_id');
    }

    public function childrens(){
        return $this->directChildrens()->with('childrens');
    }
}

// Controller
return $children->childrens()->get();
</code>```

As expected it works fine. Here a result:

```<code>[{
"id": 10,
"father_id": 2,
"childrens": [
    {
        "id": 54,
        "father_id": 10,
        "childrens": [
            {
                "id": 61,
                "father_id": 54,
                "childrens": []
            }
        ]
    },
    {
        "id": 21,
        "father_id": 10,
        "childrens": []
    }
]
}]
</code>```

How can I perform a pluck('id') of this collection in order to get [10,54,61,21] ?

答:
A recursive solution right here, requires to declare an additional method though:

function extractIds($obj)
{
    $result = [];

    if (isset($obj['id'])) {
        $result[] = $obj['id'];
    }

    if (isset($obj['children'])) {
        return array_merge($result, ...array_map('extractIds', $obj['children']));
    }

    return $result;
}
```

<p>The method will securely check for the <code>id</code> property as well as the <code>childrens</code> property before recursing into it. <em>(By the way, the word <code>children</code> is already the plural form, no need for an additional <code>s</code> at the end. So be aware I removed it in my example.)</em></p>

<p>Using this, we can utilize a Laravel collection to easily chain the required transformation calls:</p>

<pre class="lang-php prettyprint-override"><code>$result = collect($array)
    ->map('extractIds')
    ->flatten()
    ->toArray();
</code>```

Body:
I have to retrieve just an array of id from the given collection, something like [10,54,61,21,etc].
I've tried flatten, pluck, but nothing seems to work apart from a foreach which is something I would like to remove at this step.

// Model
class Children extends Eloquent {
    public function directChildrens(){
        return $this->hasMany('App\Children','father_id','id')->select('id','father_id');
    }

    public function childrens(){
        return $this->directChildrens()->with('childrens');
    }
}

// Controller
return $children->childrens()->get();

As expected it works fine. Here a result:

[{
"id": 10,
"father_id": 2,
"childrens": [
    {
        "id": 54,
        "father_id": 10,
        "childrens": [
            {
                "id": 61,
                "father_id": 54,
                "childrens": []
            }
        ]
    },
    {
        "id": 21,
        "father_id": 10,
        "childrens": []
    }
]
}]

How can I perform a pluck('id') of this collection in order to get [10,54,61,21] ?

Body:
A recursive solution right here, requires to declare an additional method though:

function extractIds($obj)
{
    $result = [];

    if (isset($obj['id'])) {
        $result[] = $obj['id'];
    }

    if (isset($obj['children'])) {
        return array_merge($result, ...array_map('extractIds', $obj['children']));
    }

    return $result;
}

The method will securely check for the id property as well as the childrens property before recursing into it. (By the way, the word children is already the plural form, no need for an additional s at the end. So be aware I removed it in my example.)

Using this, we can utilize a Laravel collection to easily chain the required transformation calls:

$result = collect($array)
    ->map('extractIds')
    ->flatten()
    ->toArray();


问:
Swift Unzipping zip file and find xml file from base64 data from Gmail API
This question is regarding a DMARC report viewer app in iOS 13 using SwiftUI and Gmail API. The reports are mailed to our admin email id by google in xml format which will be zipped. So basically it is a zip attachment. So here, GMail API is used to access those specific mail using filter and got all the base64 encoded data from API. Also decoded it to Data type data. That far is OK. Next part is where data of zip file in byte format is decompressed and extract xml file inside in String type. Then I need to parse XML. I think I can figure out parsing with XMLParser.

Question: how to decompress zip file in Data type and get xml file from it as String type?

```<code>INPUT: String in Base64 format from GMail API fetch (A zip file attachment with only 1 xml file inside)
OUTPUT: String in XML format
PLATFORM: iOS 13/Swift 5.2/SwiftUI/Xcode 11.4
ACTION:

(INPUT)
base64: String | Decode -> Data
attachment.zip: Data | Decompress -> [Data]
ListOfFiles: [Data] | FirstIndex -> Data
dmarc.xml: Data | ContentOfXML -> String
(OUTPUT)
</code>```

Update: I have tried an external package called Zip and it also failed.

```<code>let path = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let url = path.appendingPathComponent(messageId+".zip")
do {
    try data.write(to: url)
} catch {
    print("Error while writing: "+error.localizedDescription)
}
do {
    let unzipDirectory = try Zip.quickUnzipFile(url)
    print(unzipDirectory)
} catch let error as NSError {
    print("Error while unzipping: "+error.localizedDescription)
}
</code>```

This code resulted in following error

```<code>Error while unzipping: The operation couldn’t be completed. (Zip.ZipError error 1.)
</code>```

答:
Finally I found it. As it is mentioned in Ref 1,The email bodies are encoded in 7-bit US-ASCII data. So this is why the base64 decoding did not work.

As defined in the rfc1341:

An encoding type of 7BIT requires that the body is already in a
  seven-bit mail- ready representation. This is the default value --
  that is, "Content-Transfer-Encoding: 7BIT" is assumed if the
  Content-Transfer-Encoding header field is not present.

The whole code worked after adding the following.

```<code>let edata: String = result.data.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
</code>```

As it is mentioned in Ref 2, it just need character replacement on '-' with '+' and '_' with '/' inside base64 data received from gmail api.

```<code>func getAttachedData(messageId: String, attachmentId: String) {
    decode(self.urlBase+messageId+"/attachments/"+attachmentId+"?"+self.urlKey) { (result: Attachment) in
        let edata: String = result.data.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
        if let data = Data(base64Encoded: edata, options: .ignoreUnknownCharacters) {
            let filemanager = FileManager.default
            let path = try! filemanager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            let url = path.appendingPathComponent(messageId+".zip")
            do {
                try data.write(to: url)
            } catch {
                print("Error while writing: "+error.localizedDescription)
            }
            do {
                let unzipDirectory = try Zip.quickUnzipFile(url)
                print("Unzipped")
                do {
                    let filelist = try filemanager.contentsOfDirectory(at: unzipDirectory, includingPropertiesForKeys: [], options: [])

                    for filename in filelist {
                        print(filename.lastPathComponent)
                        print(filename.relativeString)
                        do {
                            let text = try String(contentsOf: filename, encoding: .utf8)
                            print(text)
                            DispatchQueue.main.async {
                                self.attachments.append(text)
                            }
                        } catch let error as NSError {
                            print("Error: \(error.localizedDescription)")
                        }
                    }
                } catch let error {
                    print("Error: \(error.localizedDescription)")
                }
            } catch let error as NSError {
                print("Error while unzipping: "+error.localizedDescription)
            }
        }
    }
}
</code>```

Ref 1: https://stackoverflow.com/a/58590759/2382813

Ref 2: https://stackoverflow.com/a/24986452/2382813

Body:
This question is regarding a DMARC report viewer app in iOS 13 using SwiftUI and Gmail API. The reports are mailed to our admin email id by google in xml format which will be zipped. So basically it is a zip attachment. So here, GMail API is used to access those specific mail using filter and got all the base64 encoded data from API. Also decoded it to Data type data. That far is OK. Next part is where data of zip file in byte format is decompressed and extract xml file inside in String type. Then I need to parse XML. I think I can figure out parsing with XMLParser.

Question: how to decompress zip file in Data type and get xml file from it as String type?

INPUT: String in Base64 format from GMail API fetch (A zip file attachment with only 1 xml file inside)
OUTPUT: String in XML format
PLATFORM: iOS 13/Swift 5.2/SwiftUI/Xcode 11.4
ACTION:

(INPUT)
base64: String | Decode -> Data
attachment.zip: Data | Decompress -> [Data]
ListOfFiles: [Data] | FirstIndex -> Data
dmarc.xml: Data | ContentOfXML -> String
(OUTPUT)

Update: I have tried an external package called Zip and it also failed.

let path = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let url = path.appendingPathComponent(messageId+".zip")
do {
    try data.write(to: url)
} catch {
    print("Error while writing: "+error.localizedDescription)
}
do {
    let unzipDirectory = try Zip.quickUnzipFile(url)
    print(unzipDirectory)
} catch let error as NSError {
    print("Error while unzipping: "+error.localizedDescription)
}

This code resulted in following error

Error while unzipping: The operation couldn’t be completed. (Zip.ZipError error 1.)

Body:
Finally I found it. As it is mentioned in Ref 1,The email bodies are encoded in 7-bit US-ASCII data. So this is why the base64 decoding did not work.

As defined in the rfc1341:

An encoding type of 7BIT requires that the body is already in a
  seven-bit mail- ready representation. This is the default value --
  that is, "Content-Transfer-Encoding: 7BIT" is assumed if the
  Content-Transfer-Encoding header field is not present.

The whole code worked after adding the following.

let edata: String = result.data.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")

As it is mentioned in Ref 2, it just need character replacement on '-' with '+' and '_' with '/' inside base64 data received from gmail api.

func getAttachedData(messageId: String, attachmentId: String) {
    decode(self.urlBase+messageId+"/attachments/"+attachmentId+"?"+self.urlKey) { (result: Attachment) in
        let edata: String = result.data.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
        if let data = Data(base64Encoded: edata, options: .ignoreUnknownCharacters) {
            let filemanager = FileManager.default
            let path = try! filemanager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            let url = path.appendingPathComponent(messageId+".zip")
            do {
                try data.write(to: url)
            } catch {
                print("Error while writing: "+error.localizedDescription)
            }
            do {
                let unzipDirectory = try Zip.quickUnzipFile(url)
                print("Unzipped")
                do {
                    let filelist = try filemanager.contentsOfDirectory(at: unzipDirectory, includingPropertiesForKeys: [], options: [])

                    for filename in filelist {
                        print(filename.lastPathComponent)
                        print(filename.relativeString)
                        do {
                            let text = try String(contentsOf: filename, encoding: .utf8)
                            print(text)
                            DispatchQueue.main.async {
                                self.attachments.append(text)
                            }
                        } catch let error as NSError {
                            print("Error: \(error.localizedDescription)")
                        }
                    }
                } catch let error {
                    print("Error: \(error.localizedDescription)")
                }
            } catch let error as NSError {
                print("Error while unzipping: "+error.localizedDescription)
            }
        }
    }
}

Ref 1: https://stackoverflow.com/a/58590759/2382813

Ref 2: https://stackoverflow.com/a/24986452/2382813


问:
How to make an alterable Xamarin.Form Xaml Page?
I'd like to realize a Xaml Page in Xamarin.Form which can be modified by a user input. For example if the user click on a button, the app displays a Date Picker, and if the user click on another button the app removes the Date Picker and displays a Text entry at the exact same place.
I've tried to use the 'IsVisible' attribute but it doesn't work as I expected (the xaml object is still there but is just invisible, so I can't replace it).

Any suggestions ?

答:
You can remove a child.

Like this:

Children.Remove or Children.RemoveAt

Reference:

https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.layout-1.children?view=xamarin-forms