问:
html5: how to avoid two divs partially overlapp?
I am using this template:
w3schools template

to design a simple online shop. It shall be divided into three vertical areas: left, middle and right. The left area is a kind of preview, which shows an image of a selected product. The middle area contains pictures of products: Whenever a product is "selected"  from this middle area - through mouse over (on a desktop) , this product shall be shown in the left "preview" area. The right area shall contain a table of all selected products.

Now I have the problem that the left and the middle area partially overlapp on a desktop laptop (the right area is not ready yet). I wouuld like to avoid this partiall overlapping. How can I achive this? Below is my css and the html:

* { /*   @see https://www.w3schools.com/css/css_rwd_grid.asp */
  box-sizing: border-box; /*  makes sure that the padding and the border are included in the total width and height of the elements. */
}

/* For mobile phones: Always Design for Mobile First!*/
[class*="col-"] {
  float: left;
  padding: 15px;
  width: 100%;
}

.productImage  > *{
   display :block;
}

 .productImage{
  float:left;
 }

@media only screen and (min-width: 600px) {   /* For tablets: */
  .col-s-1 {width: 8.33%;}
  .col-s-2 {width: 16.66%;}
  .col-s-3 {width: 25%;}
  .col-s-4 {width: 33.33%;}
  .col-s-5 {width: 41.66%;}
  .col-s-6 {width: 50%;}
  .col-s-7 {width: 58.33%;}
  .col-s-8 {width: 66.66%;}
  .col-s-9 {width: 75%;}
  .col-s-10 {width: 83.33%;}
  .col-s-11 {width: 91.66%;}
  .col-s-12 {width: 100%;}

}

@media only screen and (min-width: 768px) {   /* For desktop: */
  .col-1 {width: 8.33%;}
  .col-2 {width: 16.66%;}
  .col-3 {width: 25%;}
  .col-4 {width: 33.33%;}
  .col-5 {width: 41.66%;}
  .col-6 {width: 50%;}
  .col-7 {width: 58.33%;}
  .col-8 {width: 66.66%;}
  .col-9 {width: 75%;}
  .col-10 {width: 83.33%;}
  .col-11 {width: 91.66%;}
  .col-12 {width: 100%;}

 .tableImage{
  height:250px;
  width:250px;
  padding: 5px;
 }

 .productImage:hover{
  background-color:#ddd;
 }
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

.aside {
  background-color: #33b5e5;
  padding: 15px;
  color: #ffffff;
  text-align: center;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

/* Style the footer */
.footer {
  background-color: #f1f1f1;
  padding: 10px;
  text-align: center;
}

.chosenProductDetailsImage{  /** style for the product's detailed image */
 height:550px;
 width:400px;
 padding: 10px;
 background-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- https://www.w3schools.com/css/css_rwd_viewport.asp  -->
  <link rel="stylesheet" href="css/styles.css">
  <script src="js/onlineshop.js"></script>
  <title>On-line shop</title>
 </head>
 <!-- Header -->
 <body>
       <div class="row">
      <div id="leftDiv" class="col-3 col-s-3">
   <img alt="" id="chosenProductDetailsImageId" class="chosenProductDetailsImage" src=""/>
      </div>
   <div class="col-7 col-s-9">
   <div class ="productImage">
    <img src="images/NA823E08M-H11@6.jpg"  alt= "product NA823E08M" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NA823E08M-H11@6"  onclick="setAddedToCart(this)"  name="addToCart" value="Summer light skirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">12,45 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/A0F21S00I-K11@7.jpg"  alt= "product A0F21S00I" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="A0F21S00I-K11@7"  onclick="setAddedToCart(this)"  name="addToCart" value="Summer jeans light"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">13,99 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/NA823F0VN-E11@7.jpg"  alt= "product NA823F0VN" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NA823F0VN-E11@7" onclick="setAddedToCart(this)" name="addToCart" value="Light Body Skirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">8,00 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/AGA21S008-K11@5.jpg"  alt= "product AGA21S008" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="AGA21S008-K11@5" onclick="setAddedToCart(this)" name="addToCart" value="Summer jeans classic"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">7,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/NX323F11F-E11@7.jpg"  alt= "product NX323F11F" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NX323F11F-E11@7"  onclick="setAddedToCart(this)"  name="addToCart" value="Pijamma light"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">16,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/ARC21S002-C11@10.jpg"  alt= "product ARC21S002-C11@10" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="ARC21S002-C11@10" onclick="setAddedToCart(this)" name = "addToCart" value = "Blue jeans classic"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">26,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/OU523H01C-E11@7.jpg"  alt= "product OU523H01C" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="OU523H01C-E11@7" onclick="setAddedToCart(this)" name = "addToCart" value = "Summer T-shirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">24,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/IR221S001-K11@2.jpg"  alt= "product IR221S001-K11@2" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="IR221S001-K11@2" onclick="setAddedToCart(this)" name = "addToCart" value = "Blue jeans patched"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">27,99 €</span></span>
   </div>
  </div>
  <div class="col-2 col-s-12">
      <div class="aside">
        <h2>What?</h2>
        <p>Chania is a city on the island of Crete.</p>
        <h2>Where?</h2>
        <p>Crete is a Greek island in the Mediterranean Sea.</p>
        <h2>How?</h2>
        <p>You can reach Chania airport from all over Europe.</p>
      </div>
    </div> <!--  class = "col-3 col-s-12" -->
 </div> <!--  class="row" -->
 <div class="footer">
    <p>Footer</p>
 </div>
 </body>
</html></code>```

答:
Change Media Query CSS Order & Change width Here .chosenProductDetailsImage 100%

* { /*   @see https://www.w3schools.com/css/css_rwd_grid.asp */
  box-sizing: border-box; /*  makes sure that the padding and the border are included in the total width and height of the elements. */
}

/* For mobile phones: Always Design for Mobile First!*/
[class*="col-"] {
  float: left;
  padding: 15px;
  width: 100%;
}

.productImage  > *{
   display :block;
}

 .productImage{
  float:left;
 }

@media only screen and (min-width: 768px) {   /* For desktop: */
  .col-1 {width: 8.33%;}
  .col-2 {width: 16.66%;}
  .col-3 {width: 25%;}
  .col-4 {width: 33.33%;}
  .col-5 {width: 41.66%;}
  .col-6 {width: 50%;}
  .col-7 {width: 58.33%;}
  .col-8 {width: 66.66%;}
  .col-9 {width: 75%;}
  .col-10 {width: 83.33%;}
  .col-11 {width: 91.66%;}
  .col-12 {width: 100%;}

 .tableImage{
  height:250px;
  width:250px;
  padding: 5px;
 }

 .productImage:hover{
  background-color:#ddd;
 }
}
@media only screen and (min-width: 600px) {   /* For tablets: */
  .col-s-1 {width: 8.33%;}
  .col-s-2 {width: 16.66%;}
  .col-s-3 {width: 25%;}
  .col-s-4 {width: 33.33%;}
  .col-s-5 {width: 41.66%;}
  .col-s-6 {width: 50%;}
  .col-s-7 {width: 58.33%;}
  .col-s-8 {width: 66.66%;}
  .col-s-9 {width: 75%;}
  .col-s-10 {width: 83.33%;}
  .col-s-11 {width: 91.66%;}
  .col-s-12 {width: 100%;}

}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

.aside {
  background-color: #33b5e5;
  padding: 15px;
  color: #ffffff;
  text-align: center;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

/* Style the footer */
.footer {
  background-color: #f1f1f1;
  padding: 10px;
  text-align: center;
}

.chosenProductDetailsImage{  /** style for the product's detailed image */
 height:550px;
 width:100%;
 padding: 10px;
 background-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- https://www.w3schools.com/css/css_rwd_viewport.asp  -->
  <link rel="stylesheet" href="css/styles.css">
  <script src="js/onlineshop.js"></script>
  <title>On-line shop</title>
 </head>
 <!-- Header -->
 <body>
       <div class="row">
      <div id="leftDiv" class="col-3 col-s-3">
   <img alt="" id="chosenProductDetailsImageId" class="chosenProductDetailsImage" src=""/>
      </div>
   <div class="col-7 col-s-9">
   <div class ="productImage">
    <img src="images/NA823E08M-H11@6.jpg"  alt= "product NA823E08M" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NA823E08M-H11@6"  onclick="setAddedToCart(this)"  name="addToCart" value="Summer light skirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">12,45 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/A0F21S00I-K11@7.jpg"  alt= "product A0F21S00I" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="A0F21S00I-K11@7"  onclick="setAddedToCart(this)"  name="addToCart" value="Summer jeans light"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">13,99 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/NA823F0VN-E11@7.jpg"  alt= "product NA823F0VN" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NA823F0VN-E11@7" onclick="setAddedToCart(this)" name="addToCart" value="Light Body Skirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">8,00 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/AGA21S008-K11@5.jpg"  alt= "product AGA21S008" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="AGA21S008-K11@5" onclick="setAddedToCart(this)" name="addToCart" value="Summer jeans classic"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">7,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/NX323F11F-E11@7.jpg"  alt= "product NX323F11F" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NX323F11F-E11@7"  onclick="setAddedToCart(this)"  name="addToCart" value="Pijamma light"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">16,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/ARC21S002-C11@10.jpg"  alt= "product ARC21S002-C11@10" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="ARC21S002-C11@10" onclick="setAddedToCart(this)" name = "addToCart" value = "Blue jeans classic"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">26,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/OU523H01C-E11@7.jpg"  alt= "product OU523H01C" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="OU523H01C-E11@7" onclick="setAddedToCart(this)" name = "addToCart" value = "Summer T-shirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">24,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/IR221S001-K11@2.jpg"  alt= "product IR221S001-K11@2" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="IR221S001-K11@2" onclick="setAddedToCart(this)" name = "addToCart" value = "Blue jeans patched"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">27,99 €</span></span>
   </div>
  </div>
  <div class="col-2 col-s-12">
      <div class="aside">
        <h2>What?</h2>
        <p>Chania is a city on the island of Crete.</p>
        <h2>Where?</h2>
        <p>Crete is a Greek island in the Mediterranean Sea.</p>
        <h2>How?</h2>
        <p>You can reach Chania airport from all over Europe.</p>
      </div>
    </div> <!--  class = "col-3 col-s-12" -->
 </div> <!--  class="row" -->
 <div class="footer">
    <p>Footer</p>
 </div>
 </body>
</html></code>```

Body:
I am using this template:
w3schools template

to design a simple online shop. It shall be divided into three vertical areas: left, middle and right. The left area is a kind of preview, which shows an image of a selected product. The middle area contains pictures of products: Whenever a product is "selected"  from this middle area - through mouse over (on a desktop) , this product shall be shown in the left "preview" area. The right area shall contain a table of all selected products.

Now I have the problem that the left and the middle area partially overlapp on a desktop laptop (the right area is not ready yet). I wouuld like to avoid this partiall overlapping. How can I achive this? Below is my css and the html:

* { /*   @see https://www.w3schools.com/css/css_rwd_grid.asp */
  box-sizing: border-box; /*  makes sure that the padding and the border are included in the total width and height of the elements. */
}

/* For mobile phones: Always Design for Mobile First!*/
[class*="col-"] {
  float: left;
  padding: 15px;
  width: 100%;
}

.productImage  > *{
   display :block;
}

 .productImage{
  float:left;
 }

@media only screen and (min-width: 600px) {   /* For tablets: */
  .col-s-1 {width: 8.33%;}
  .col-s-2 {width: 16.66%;}
  .col-s-3 {width: 25%;}
  .col-s-4 {width: 33.33%;}
  .col-s-5 {width: 41.66%;}
  .col-s-6 {width: 50%;}
  .col-s-7 {width: 58.33%;}
  .col-s-8 {width: 66.66%;}
  .col-s-9 {width: 75%;}
  .col-s-10 {width: 83.33%;}
  .col-s-11 {width: 91.66%;}
  .col-s-12 {width: 100%;}

}

@media only screen and (min-width: 768px) {   /* For desktop: */
  .col-1 {width: 8.33%;}
  .col-2 {width: 16.66%;}
  .col-3 {width: 25%;}
  .col-4 {width: 33.33%;}
  .col-5 {width: 41.66%;}
  .col-6 {width: 50%;}
  .col-7 {width: 58.33%;}
  .col-8 {width: 66.66%;}
  .col-9 {width: 75%;}
  .col-10 {width: 83.33%;}
  .col-11 {width: 91.66%;}
  .col-12 {width: 100%;}

 .tableImage{
  height:250px;
  width:250px;
  padding: 5px;
 }

 .productImage:hover{
  background-color:#ddd;
 }
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

.aside {
  background-color: #33b5e5;
  padding: 15px;
  color: #ffffff;
  text-align: center;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

/* Style the footer */
.footer {
  background-color: #f1f1f1;
  padding: 10px;
  text-align: center;
}

.chosenProductDetailsImage{  /** style for the product's detailed image */
 height:550px;
 width:400px;
 padding: 10px;
 background-color: white;
}

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css/styles.css">

  <title>On-line shop</title>

    <input type="checkbox" id="NA823E08M-H11@6"  onclick="setAddedToCart(this)"  name="addToCart" value="Summer light skirt"/>
    Add to Cart
    ab 12,45 €

    <input type="checkbox" id="A0F21S00I-K11@7"  onclick="setAddedToCart(this)"  name="addToCart" value="Summer jeans light"/>
    Add to Cart
    ab 13,99 €

    <input type="checkbox" id="NA823F0VN-E11@7" onclick="setAddedToCart(this)" name="addToCart" value="Light Body Skirt"/>
    Add to Cart
    ab 8,00 €

    <input type="checkbox" id="AGA21S008-K11@5" onclick="setAddedToCart(this)" name="addToCart" value="Summer jeans classic"/>
    Add to Cart
    ab 7,99 €

    <input type="checkbox" id="NX323F11F-E11@7"  onclick="setAddedToCart(this)"  name="addToCart" value="Pijamma light"/>
    Add to Cart
    ab 16,99 €

    <input type="checkbox" id="ARC21S002-C11@10" onclick="setAddedToCart(this)" name = "addToCart" value = "Blue jeans classic"/>
    Add to Cart
    ab 26,99 €

    <input type="checkbox" id="OU523H01C-E11@7" onclick="setAddedToCart(this)" name = "addToCart" value = "Summer T-shirt"/>
    Add to Cart
    ab 24,99 €

    <input type="checkbox" id="IR221S001-K11@2" onclick="setAddedToCart(this)" name = "addToCart" value = "Blue jeans patched"/>
    Add to Cart
    ab 27,99 €

What?

Chania is a city on the island of Crete.

Where?

Crete is a Greek island in the Mediterranean Sea.

How?

You can reach Chania airport from all over Europe.

Footer

Body:
Change Media Query CSS Order & Change width Here .chosenProductDetailsImage 100%

* { /*   @see https://www.w3schools.com/css/css_rwd_grid.asp */
  box-sizing: border-box; /*  makes sure that the padding and the border are included in the total width and height of the elements. */
}

/* For mobile phones: Always Design for Mobile First!*/
[class*="col-"] {
  float: left;
  padding: 15px;
  width: 100%;
}

.productImage  > *{
   display :block;
}

 .productImage{
  float:left;
 }

@media only screen and (min-width: 768px) {   /* For desktop: */
  .col-1 {width: 8.33%;}
  .col-2 {width: 16.66%;}
  .col-3 {width: 25%;}
  .col-4 {width: 33.33%;}
  .col-5 {width: 41.66%;}
  .col-6 {width: 50%;}
  .col-7 {width: 58.33%;}
  .col-8 {width: 66.66%;}
  .col-9 {width: 75%;}
  .col-10 {width: 83.33%;}
  .col-11 {width: 91.66%;}
  .col-12 {width: 100%;}

 .tableImage{
  height:250px;
  width:250px;
  padding: 5px;
 }

 .productImage:hover{
  background-color:#ddd;
 }
}
@media only screen and (min-width: 600px) {   /* For tablets: */
  .col-s-1 {width: 8.33%;}
  .col-s-2 {width: 16.66%;}
  .col-s-3 {width: 25%;}
  .col-s-4 {width: 33.33%;}
  .col-s-5 {width: 41.66%;}
  .col-s-6 {width: 50%;}
  .col-s-7 {width: 58.33%;}
  .col-s-8 {width: 66.66%;}
  .col-s-9 {width: 75%;}
  .col-s-10 {width: 83.33%;}
  .col-s-11 {width: 91.66%;}
  .col-s-12 {width: 100%;}

}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

.aside {
  background-color: #33b5e5;
  padding: 15px;
  color: #ffffff;
  text-align: center;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

/* Style the footer */
.footer {
  background-color: #f1f1f1;
  padding: 10px;
  text-align: center;
}

.chosenProductDetailsImage{  /** style for the product's detailed image */
 height:550px;
 width:100%;
 padding: 10px;
 background-color: white;
}

<!DOCTYPE html>
<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- https://www.w3schools.com/css/css_rwd_viewport.asp  -->
  <link rel="stylesheet" href="css/styles.css">
  <script src="js/onlineshop.js"></script>
  <title>On-line shop</title>
 </head>
 <!-- Header -->
 <body>
       <div class="row">
      <div id="leftDiv" class="col-3 col-s-3">
   <img alt="" id="chosenProductDetailsImageId" class="chosenProductDetailsImage" src=""/>
      </div>
   <div class="col-7 col-s-9">
   <div class ="productImage">
    <img src="images/NA823E08M-H11@6.jpg"  alt= "product NA823E08M" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NA823E08M-H11@6"  onclick="setAddedToCart(this)"  name="addToCart" value="Summer light skirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">12,45 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/A0F21S00I-K11@7.jpg"  alt= "product A0F21S00I" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="A0F21S00I-K11@7"  onclick="setAddedToCart(this)"  name="addToCart" value="Summer jeans light"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">13,99 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/NA823F0VN-E11@7.jpg"  alt= "product NA823F0VN" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NA823F0VN-E11@7" onclick="setAddedToCart(this)" name="addToCart" value="Light Body Skirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">8,00 €</span></span>
   </div>
   <div class ="productImage">
    <img src="images/AGA21S008-K11@5.jpg"  alt= "product AGA21S008" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="AGA21S008-K11@5" onclick="setAddedToCart(this)" name="addToCart" value="Summer jeans classic"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">7,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/NX323F11F-E11@7.jpg"  alt= "product NX323F11F" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="NX323F11F-E11@7"  onclick="setAddedToCart(this)"  name="addToCart" value="Pijamma light"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">16,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/ARC21S002-C11@10.jpg"  alt= "product ARC21S002-C11@10" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="ARC21S002-C11@10" onclick="setAddedToCart(this)" name = "addToCart" value = "Blue jeans classic"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">26,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/OU523H01C-E11@7.jpg"  alt= "product OU523H01C" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="OU523H01C-E11@7" onclick="setAddedToCart(this)" name = "addToCart" value = "Summer T-shirt"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">24,99 €</span></span>
   </div>
   <div class="productImage">
    <img src="images/IR221S001-K11@2.jpg"  alt= "product IR221S001-K11@2" class="tableImage" onmouseout = "hideDetailImage();" onmouseover="showDetailImage(this)"/>
    <input type="checkbox" id="IR221S001-K11@2" onclick="setAddedToCart(this)" name = "addToCart" value = "Blue jeans patched"/>
    <span class="addToCartSpan">Add to Cart</span>
    <span class="priceAb">ab <span class="price">27,99 €</span></span>
   </div>
  </div>
  <div class="col-2 col-s-12">
      <div class="aside">
        <h2>What?</h2>
        <p>Chania is a city on the island of Crete.</p>
        <h2>Where?</h2>
        <p>Crete is a Greek island in the Mediterranean Sea.</p>
        <h2>How?</h2>
        <p>You can reach Chania airport from all over Europe.</p>
      </div>
    </div> <!--  class = "col-3 col-s-12" -->
 </div> <!--  class="row" -->
 <div class="footer">
    <p>Footer</p>
 </div>
 </body>
</html>


来源: stackexchange

问:
how to dynamically change dropdown menu in html from django template
I create a dictionary in django views.py like this:

```<code>tmp={"K1":['V1','V2'],"K2":['V3','V4']}
</code>```

and in my html page,I create two dropdown menu.

menu D1 can select key from dictionary (K1/K2) in html:

```<code><select name="D1">
   {% for key, value in tmp.items %}
       <option value="{{key}}">{{key}}</option>
   {% endfor %}
</select>
</code>```

now I want create menu D2 dynamically change with D1 select,for example, if I select K1 in D1,dropdown menu D2 will show V1 V2 and when I change to K2 in D1,menu D2 will show V3 V4,I suddenly don't know how to do it,can any one help me? very thanks!

答:
For this use vanilla JavaScript or jQuery if you feel more comfortable with it. Add event listener on the first dropdown. You can prepare elements for example using jQuery:

```<code>var first_els = $("<option value="K1">V1</option><option value="K1">V2</option>");
var second_els = $("<option value="K2">V3</option><option value="K2">V4</option>");

function callback(){
    var value = this.value;
    if (value === "K1"){
      dropdown.append(second_els);
}
    else{
     dropdown.append(first_els);
}

}
</code>```

callback function is the function that is beeing called when something will be changed in dropdown 1. Of course you have to do more, like clear current elements in DOM or just fetch dropdown. But I hope this example gave you idea how to solve your problem

ContentLicense: CC BY-SA 4.0

Body:
I create a dictionary in django views.py like this:

tmp={"K1":['V1','V2'],"K2":['V3','V4']}

and in my html page,I create two dropdown menu.

menu D1 can select key from dictionary (K1/K2) in html:

<select name="D1">
   {% for key, value in tmp.items %}
       <option value="{{key}}">{{key}}</option>
   {% endfor %}
</select>

now I want create menu D2 dynamically change with D1 select,for example, if I select K1 in D1,dropdown menu D2 will show V1 V2 and when I change to K2 in D1,menu D2 will show V3 V4,I suddenly don't know how to do it,can any one help me? very thanks!

Body:
For this use vanilla JavaScript or jQuery if you feel more comfortable with it. Add event listener on the first dropdown. You can prepare elements for example using jQuery:

var first_els = $("<option value="K1">V1</option><option value="K1">V2</option>");
var second_els = $("<option value="K2">V3</option><option value="K2">V4</option>");

function callback(){
    var value = this.value;
    if (value === "K1"){
      dropdown.append(second_els);
}
    else{
     dropdown.append(first_els);
}

}

callback function is the function that is beeing called when something will be changed in dropdown 1. Of course you have to do more, like clear current elements in DOM or just fetch dropdown. But I hope this example gave you idea how to solve your problem


问:
How to run a block of code after each @test, no matter if the test is @Disabled or not?
Basically I would like to add an entry to my Extent report for "Skipped Tests". I understand I can use @AfterEach, however I see that the @AfterEach code block does not get executed for @Disabled Test in Junit5.

I tried using TestWatcher interface and overrided the method testDisabled like below:

```<code>package utils;

import java.util.Optional;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

public class MyTestWatcher implements TestWatcher {
                public static String testStatus;
                public static String testCaseName;
    @Override
    public void testAborted(ExtensionContext Context, Throwable throwable) {
                testStatus = "Aborted";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Aborted: " + Context.getDisplayName());
                }

    @Override
    public void testDisabled(ExtensionContext Context, Optional<String> optional) {
                testStatus = "Skipped";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Skipped: " + Context.getDisplayName());
                }

    @Override
    public void testFailed(ExtensionContext Context, Throwable throwable) {
                testStatus = "Failed";
                testCaseName = Context.getDisplayName();
               System.out.println("Test Failed: " + Context.getDisplayName());
}

    @Override
    public void testSuccessful(ExtensionContext Context) {
                testStatus = "Passed";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Passed: " + Context.getDisplayName());
    }

}
</code>```

Based on the 'testStatus' and 'testCaseName' variables, which are set in the testDisabled() method above, I would like to run a block of code from my test class, to add an entry to my Extent report saying which test case was skipped.

答:
I was able to add reporting for Skipped Tests by initializing the Extent Report from the MyTestWatcher class. Even though the ExtentReport object was already initialized in my test class, when I again try to initialize (which would end up creating another HTML file report), I added the below code to my ExtentManager class:

```<code>public static ExtentReports GetExtent(String env){
        **if (extent != null)
          return extent; //avoid creating new instance of html file**
        extent = new ExtentReports();
        extent.attachReporter(getHtmlReporter());
        extent.setSystemInfo("Environment",env);
        extent.setAnalysisStrategy(AnalysisStrategy.SUITE);
        return extent;
</code>```

And my updated code in MyTestWatcher class looks like below:

```<code>package utils;

import java.util.Optional;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;

public class MyTestWatcher implements TestWatcher {
                public static String testCaseName;
                public static ExtentReports extent;
                public static ExtentTest report;

    static
                {
                extent = utils.ExtentReportManager.GetExtent(System.getProperty("env"));
                report = extent.createTest("Skipped Tests", "Tests which are skipped are displayed here.");
                }
    @Override
    public void testAborted(ExtensionContext Context, Throwable throwable) {
                testCaseName = Context.getDisplayName();
                System.out.println("Test Aborted: " + Context.getDisplayName());
                }

    @Override
    public void testDisabled(ExtensionContext Context, Optional<String> optional) {
                testCaseName = Context.getDisplayName();
                System.out.println("Test Skipped: " + Context.getDisplayName());
                report.createNode(testCaseName).log(Status.SKIP, "This test is marked as @DISABLED");
                }

    @Override
    public void testFailed(ExtensionContext Context, Throwable throwable) {
                testCaseName = Context.getDisplayName();
               System.out.println("Test Failed: " + Context.getDisplayName());
                }

    @Override
    public void testSuccessful(ExtensionContext Context) {
                testCaseName = Context.getDisplayName();
                System.out.println("Test Passed: " + Context.getDisplayName());
    }

}
</code>```

Body:
Basically I would like to add an entry to my Extent report for "Skipped Tests". I understand I can use @AfterEach, however I see that the @AfterEach code block does not get executed for @Disabled Test in Junit5.

I tried using TestWatcher interface and overrided the method testDisabled like below:

package utils;

import java.util.Optional;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

public class MyTestWatcher implements TestWatcher {
                public static String testStatus;
                public static String testCaseName;
    @Override
    public void testAborted(ExtensionContext Context, Throwable throwable) {
                testStatus = "Aborted";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Aborted: " + Context.getDisplayName());
                }

    @Override
    public void testDisabled(ExtensionContext Context, Optional<String> optional) {
                testStatus = "Skipped";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Skipped: " + Context.getDisplayName());
                }

    @Override
    public void testFailed(ExtensionContext Context, Throwable throwable) {
                testStatus = "Failed";
                testCaseName = Context.getDisplayName();
               System.out.println("Test Failed: " + Context.getDisplayName());
}

    @Override
    public void testSuccessful(ExtensionContext Context) {
                testStatus = "Passed";
                testCaseName = Context.getDisplayName();
                System.out.println("Test Passed: " + Context.getDisplayName());
    }

}

Based on the 'testStatus' and 'testCaseName' variables, which are set in the testDisabled() method above, I would like to run a block of code from my test class, to add an entry to my Extent report saying which test case was skipped.

Body:
I was able to add reporting for Skipped Tests by initializing the Extent Report from the MyTestWatcher class. Even though the ExtentReport object was already initialized in my test class, when I again try to initialize (which would end up creating another HTML file report), I added the below code to my ExtentManager class:

public static ExtentReports GetExtent(String env){
        **if (extent != null)
          return extent; //avoid creating new instance of html file**
        extent = new ExtentReports();
        extent.attachReporter(getHtmlReporter());
        extent.setSystemInfo("Environment",env);
        extent.setAnalysisStrategy(AnalysisStrategy.SUITE);
        return extent;

And my updated code in MyTestWatcher class looks like below:

package utils;

import java.util.Optional;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;

public class MyTestWatcher implements TestWatcher {
                public static String testCaseName;
                public static ExtentReports extent;
                public static ExtentTest report;

    static
                {
                extent = utils.ExtentReportManager.GetExtent(System.getProperty("env"));
                report = extent.createTest("Skipped Tests", "Tests which are skipped are displayed here.");
                }
    @Override
    public void testAborted(ExtensionContext Context, Throwable throwable) {
                testCaseName = Context.getDisplayName();
                System.out.println("Test Aborted: " + Context.getDisplayName());
                }

    @Override
    public void testDisabled(ExtensionContext Context, Optional<String> optional) {
                testCaseName = Context.getDisplayName();
                System.out.println("Test Skipped: " + Context.getDisplayName());
                report.createNode(testCaseName).log(Status.SKIP, "This test is marked as @DISABLED");
                }

    @Override
    public void testFailed(ExtensionContext Context, Throwable throwable) {
                testCaseName = Context.getDisplayName();
               System.out.println("Test Failed: " + Context.getDisplayName());
                }

    @Override
    public void testSuccessful(ExtensionContext Context) {
                testCaseName = Context.getDisplayName();
                System.out.println("Test Passed: " + Context.getDisplayName());
    }

}


问:
How to transfer data from one file to another?
I am having two files such as,

employee-rates-controller.ts:

```<code>private load() {

return this.entityService
      .load(this.$scope.projectRevisionUid)
      .then(resp => {
        localStorage.removeItem('employeerates');
        this.$scope.employeeRates = resp.employeeRates;
        return this.refreshCostRate(...resp.employeeRates)
          .then(() =>
            localStorage.setItem(
              'employeerates',
              JSON.stringify(this.$scope.employeeRates)
            )
          )
      .then(() => this.refreshBillRate(...resp.employeeRates))
      .then(() => resp.employeeRates.forEach(erm => this.calculate(erm)))
      .then(() => DatepickerUtil.reinitializeDatepickers(this.$scope));
      })

}
</code>```

And in another file,

getEmployeeRates.ts:

```<code>  const employeerates = JSON.parse(
    localStorage.getItem('employeerates')
  );

  if (employeerates && employeerates.length != null) {
    employeerates.forEach((element: any) => {
      if (
        this.employee.getUid() === element.user.personUid &&
        element.internalRate
      ) {
        this.cost_rate_uom = element.internalRate * this.uom_factor;
        this.cost_rate_per_hour =
          this.cost_rate_uom / this.uom_factor;
        this.cost_rate.setValue(this.ap4_cost_rate_per_hour);
      }
    });
  }
</code>```

Here you can see,

In first ts file,

```<code>localStorage.setItem('employeerates',JSON.stringify(this.$scope.employeeRates))
</code>```

And in second ts file receiving the data,

```<code>const employeerates = JSON.parse(localStorage.getItem('employeerates'));
</code>```

I couldn't not find any problem if i add very few employees but when i keep on adding employee which means storing them into localstorage, i am getting the error at certain point of time when the data size was huge and it blocks the entire process.

The error was,

QuotaExceededError: Failed to execute 'setItem' on 'Storage': Setting
  the value of 'employeerates' exceeded the quota.

So i would like to get some good solution in transferring any large data from one file to another without using the localstorage..

As the application is made in Angularjs and Typescript combination, i couldn't find out right solution as i am new to this scenario.

Edit:

Instead of first TS file, i am also able to get the value in this file.

employeeratemodel.ts:

```<code>export class EmployeeRateModel {
public uid: string;
.
.
.
public internalRate: number; // Getting the value here
}
</code>```

How to fetch this value inside the second ts getEmployeeRates.ts: file..

My try:

```<code>import { EmployeeRateModel } from '../component/employee-rates/model/employee-rate.model';

constructor() {
    const data = new EmployeeRateModel();
    console.log(data) // {}  // Gives empty object.. I need to fetch the internalRate from it..
  }
</code>```

Here if i get the data then it will be ease for me to get the internalRate which is needed for calculation, but as everything returns empty, this also fails for me..

Kindly help me to fix it in appropriate way, stucked for long..

答:
use IndexedDB, it is a large-scale, NoSQL storage system. It lets you store just about anything in the user's browser and it has a huge limit based on the client computer approx 20% of total storage.

NPM Package Angular IndexedDB

Body:
I am having two files such as,

employee-rates-controller.ts:

private load() {

return this.entityService
      .load(this.$scope.projectRevisionUid)
      .then(resp => {
        localStorage.removeItem('employeerates');
        this.$scope.employeeRates = resp.employeeRates;
        return this.refreshCostRate(...resp.employeeRates)
          .then(() =>
            localStorage.setItem(
              'employeerates',
              JSON.stringify(this.$scope.employeeRates)
            )
          )
      .then(() => this.refreshBillRate(...resp.employeeRates))
      .then(() => resp.employeeRates.forEach(erm => this.calculate(erm)))
      .then(() => DatepickerUtil.reinitializeDatepickers(this.$scope));
      })

}

And in another file,

getEmployeeRates.ts:

  const employeerates = JSON.parse(
    localStorage.getItem('employeerates')
  );

  if (employeerates && employeerates.length != null) {
    employeerates.forEach((element: any) => {
      if (
        this.employee.getUid() === element.user.personUid &&
        element.internalRate
      ) {
        this.cost_rate_uom = element.internalRate * this.uom_factor;
        this.cost_rate_per_hour =
          this.cost_rate_uom / this.uom_factor;
        this.cost_rate.setValue(this.ap4_cost_rate_per_hour);
      }
    });
  }

Here you can see,

In first ts file,

localStorage.setItem('employeerates',JSON.stringify(this.$scope.employeeRates))

And in second ts file receiving the data,

const employeerates = JSON.parse(localStorage.getItem('employeerates'));

I couldn't not find any problem if i add very few employees but when i keep on adding employee which means storing them into localstorage, i am getting the error at certain point of time when the data size was huge and it blocks the entire process.

The error was,

QuotaExceededError: Failed to execute 'setItem' on 'Storage': Setting
  the value of 'employeerates' exceeded the quota.

So i would like to get some good solution in transferring any large data from one file to another without using the localstorage..

As the application is made in Angularjs and Typescript combination, i couldn't find out right solution as i am new to this scenario.

Edit:

Instead of first TS file, i am also able to get the value in this file.

employeeratemodel.ts:

export class EmployeeRateModel {
public uid: string;
.
.
.
public internalRate: number; // Getting the value here
}

How to fetch this value inside the second ts getEmployeeRates.ts: file..

My try:

import { EmployeeRateModel } from '../component/employee-rates/model/employee-rate.model';

constructor() {
    const data = new EmployeeRateModel();
    console.log(data) // {}  // Gives empty object.. I need to fetch the internalRate from it..
  }

Here if i get the data then it will be ease for me to get the internalRate which is needed for calculation, but as everything returns empty, this also fails for me..

Kindly help me to fix it in appropriate way, stucked for long..


问:
Unable to escape the escape quotes when assigning the string to variable
I have a bash command to run for which I am assigning it to a variable.
The command to be run is:

```<code>papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
</code>```

I am able to print it in python3, as:

```<code>>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
</code>```

However, when I assign the same value to the variable:

```<code>a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
</code>```

I get the following:

```<code>'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''
</code>```

Notice the \ in the output.

I expect to achieve the desired result(which is done in the print statement) using variable assigning.

答:
Both strings are exactly the same. You can observe it if you run both commands on an IDE, or via terminal using python script.py

```<code>print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
print(a)
</code>```

The output will be

```<code>papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
</code>```

It's just that Python added an extra backslash around the single quotes because we have double quotes in the string as well, and the backslash escapes the single quotes to provide a printable representation of the string

```<code>>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
>>> print(a)
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a
'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''
</code>```

Essentially the escaped string is the repr representation of the string

From the docs: https://docs.python.org/3/library/functions.html#repr

repr(object)

  Return a string containing a printable representation of an object

Body:
I have a bash command to run for which I am assigning it to a variable.
The command to be run is:

papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'

I am able to print it in python3, as:

>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'

However, when I assign the same value to the variable:

a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')

I get the following:

'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''

Notice the \ in the output.

I expect to achieve the desired result(which is done in the print statement) using variable assigning.

Body:
Both strings are exactly the same. You can observe it if you run both commands on an IDE, or via terminal using python script.py

print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
print(a)

The output will be

papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'

It's just that Python added an extra backslash around the single quotes because we have double quotes in the string as well, and the backslash escapes the single quotes to provide a printable representation of the string

>>> print("papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}'))
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a= "papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{}'".format('{"aviral":"srivastava"}')
>>> print(a)
papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y '{"aviral":"srivastava"}'
>>> a
'papermill athena-py/params_to_dict.ipynb athena-py/output_params_to_dict.ipynb -y \'{"aviral":"srivastava"}\''

Essentially the escaped string is the repr representation of the string

From the docs: https://docs.python.org/3/library/functions.html#repr

repr(object)

  Return a string containing a printable representation of an object


问:
Calling or communicating with docker container on one machine from other application not in docker container and in another machine
I have my docker container in one machine running say Machine A. I have another machine B which consists of a flask server. I would like to call/communicate with the docker container in machine A from my flask server in Machine B. I am not running my flask server inside any docker container. I am actually very new to docker so I am not sure whether we are able to achieve it or not.</p>

答:
I am not sure what you want to do with your docker container from the flask server, but I am assuming that it would be an API or some service running in the docker container which you want to use in the flask server. You can do so by using the IP of machine A on which docker container is running, also, you will need to bind your docker container's port to the host machine's ( machine A) port. So that whenever you try to reach the host machine on that specific port, you will be calling the containers port instead.
If you want to execute a command in the running container then there are 2 ways to do so, first, you can SSH to the container, second you can SSH to the host machine and then use docker exec. But since you are trying to communicate from a flask server, I think that this might not be the case.


问:
Efficient method to append only the new rows from pandas dataframe to a table in database
Suppose I have a table X in MySQL as follows

```<code>A   B
1   2
3   4
5   6
</code>```

and I have a dataframe df as follows

```<code>A   B
1   2
5   6
7   8
9  10
</code>```

I want to append to X only new rows from df (rows that are in df but not in X).  The results should be:

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

Note that sorting does not matter for me.  Currently, what I can do are

```<code>1. Read table X and store in a dataframe called dfx
2. Concat df and dfx
3. Drop duplicate rows
4. Insert the results back to the table X with to_sql(if_exist='replace')
</code>```

However, I think this is not a good practice particularly when the table X is very large.  May I have your suggestions for the better way?  Thank you

答:
If your indices are unique (or one of the columns, say A), you could

make a list of indices (or the unique column) from the dataframe,

query MySQL with the list and find the ones that do not exist in the table,

subset the dataframe based on the new indices or column values, and insert.

You will have to use something like sqlalchemy for (2).  (3) can be done easily by using DataFrame.query; e.g. df.query("A == @list_of_new_values"), where list_of_new_values is a python list with the new values for column A.

Body:
Suppose I have a table X in MySQL as follows

A   B
1   2
3   4
5   6

and I have a dataframe df as follows

A   B
1   2
5   6
7   8
9  10

I want to append to X only new rows from df (rows that are in df but not in X).  The results should be:

A   B
1   2
3   4
5   6
7   8
9  10

Note that sorting does not matter for me.  Currently, what I can do are

1. Read table X and store in a dataframe called dfx
2. Concat df and dfx
3. Drop duplicate rows
4. Insert the results back to the table X with to_sql(if_exist='replace')

However, I think this is not a good practice particularly when the table X is very large.  May I have your suggestions for the better way?  Thank you


问:
Unicode characters on ZPL printer
I have the task of re-designing a system to print shipping labels, using a networked Zebra GK420T. I have been able to send ZPL print jobs to it perfectly fine, but I cannot seem to get it to print unicode characters, such as cyrillic letters. I have downloaded the lucida sans unicode font to the printer using the Seagull Scientific drivers and I am using the following ZPL code to test:

```<code>^XA
^LH100,150
^CI28
^FT0,0^A@N,50,50,R:LUCIDASR.FNT^CI28^FDTesting 1 2 3^FS
^FT0,50^A@N,50,50,R:LUCIDASR.FNT^CI28^FDДо свидания^FS
^FT0,100^B3^FDAAA001^FS
^XZ
</code>```

It will print the 'Testing 1 2 3' and the barcode, but it leaves a blank space instead of the cyrillic characters.

I also tried using the Zebra swiss unicode font and now it prints the russian characters as question marks:

```<code>^XA
^LH100,150
^CWT,E:TT0003M_.FNT
^CFT,30,30
^CI28
^FT0,0^FDTesting 1 2 3^FS
^FT0,50^FDДо свидания^FS
^FT0,100^B3^FDAAA001^FS
^XZ
</code>```

Am I doing something wrong like not escaping characters or something or is it a problem with the printer?

答:
As others have noted, make sure to use ^CI28 (Change International Font/Encoding) and ^FH (Field Hexadecimal Indicator) and escape any non-ascii utf8 characters with an underscore and their hex value.

However another answer included code to format the utf8 string using a gigantic switch-case block. Here is the method I use for encoding to utf8, it should be able to format any valid utf8 byte array.

To get the byte array from a string use Encoding.UTF8.GetBytes(content).

// From the wikipedia page on utf8 encoding - https://en.wikipedia.org/wiki/UTF-8
    private const int _Last1ByteCodePointByte1 = 0x7F;
    private const int _First2ByteCodePointByte1 = 0xC0;
    private const int _Last2ByteCodePointByte1 = 0xDF;
    private const int _Last3ByteCodePointByte1 = 0xEF;
    private const int _Last4ByteCodePointByte1 = 0xF7;
    private const int _FirstMultiByteCodePointByte2 = 0x80;
    private const int _LastMultiByteCodePointByte2 = 0xBF;
    private const char _ZplMultiByteEscapeCharacter = '_';

///
/// Encodes a sequence of utf8 bytes for printing with the ZPL language, this means escaping multi-byte characters with an underscore ('_') followed by the hex code
/// for each byte in the multi-byte characters.
///
/// <param name="utf8Bytes">The bytes that make up the entire string, including bytes that need to be encoded and bytes that can be printed as-is.</param>
/// <returns>A string for printing with the ZPL language. Ie all multi-byte characters escaped with an underscore ('_') followed by the hex code for each byte.</returns>
/// <throws><see cref="ArgumentException"/> when <paramref name="utf8Bytes"/> isn't a valid utf8 encoding of a string.</throws>
/// <remarks>
/// Plan is to figure out how many bytes this character (code point) takes up, and if it's a 1 byte character, just use the character, but otherwise since it's a multi-byte
/// character then use an underscore ('_') followed by the hex encoded byte and each other byte in this code point will also be encoded. If we start the loop but have bytes
/// remaining in the current code point we know to hex encode this byte and continue.
/// </remarks>
private static string EncodeUtf8BytesForZPLIIPrinting(byte[] utf8Bytes)
{
    var contentWithMultiByteCharsEscaped = new List<char>();

    var multiByteCodePoint = new List<char>();
    var remainingBytesInCurrentCodePoint = 0;
    string errorMessage = null;

    foreach (byte utf8Byte in utf8Bytes)
    {
        if (remainingBytesInCurrentCodePoint > 0)
        {
            if (utf8Byte < _FirstMultiByteCodePointByte2 || utf8Byte > _LastMultiByteCodePointByte2)
            {
                errorMessage = $"The byte {utf8Byte.ToString("X2")} is not a valid as the second or later byte of a multi-byte utf8 character (codepoint).";
                break;
            }

            multiByteCodePoint.Add(_ZplMultiByteEscapeCharacter);
            AddHexValuesToListFromByte(multiByteCodePoint, utf8Byte);
            remainingBytesInCurrentCodePoint--;
            continue; // continue since we've dealt with this byte and don't want to flow on.
        }

        if (multiByteCodePoint.Any())
        {
            foreach (char c in multiByteCodePoint) contentWithMultiByteCharsEscaped.Add(c);
            multiByteCodePoint.Clear();
            // flow on to loop to see what to do with the current byte.
        }

        if (utf8Byte <= _Last1ByteCodePointByte1)
        {
            // 1 byte - no escaping
            contentWithMultiByteCharsEscaped.Add((char)utf8Byte);
        }
        else if (utf8Byte >= _First2ByteCodePointByte1 && utf8Byte <= _Last2ByteCodePointByte1)
        {
            // 2 bytes
            multiByteCodePoint.Add(_ZplMultiByteEscapeCharacter);
            AddHexValuesToListFromByte(multiByteCodePoint, utf8Byte);
            remainingBytesInCurrentCodePoint = 1;
        }
        else if (utf8Byte <= _Last3ByteCodePointByte1)
        {
            // 3 bytes
            multiByteCodePoint.Add(_ZplMultiByteEscapeCharacter);
            AddHexValuesToListFromByte(multiByteCodePoint, utf8Byte);
            remainingBytesInCurrentCodePoint = 2;
        }
        else if (utf8Byte <= _Last4ByteCodePointByte1)
        {
            // 4 bytes
            multiByteCodePoint.Add(_ZplMultiByteEscapeCharacter);
            AddHexValuesToListFromByte(multiByteCodePoint, utf8Byte);
            remainingBytesInCurrentCodePoint = 3;
        }
        else
        {
            errorMessage = $"The byte {utf8Byte.ToString("X2")} is not a valid as the first byte of a utf8 character.";
            break;
        }
    }

    // if the last char was multiByte add it now.
    if (multiByteCodePoint.Any())
    {
        foreach (var c in multiByteCodePoint) contentWithMultiByteCharsEscaped.Add(c);
        multiByteCodePoint.Clear();
    }

    if (remainingBytesInCurrentCodePoint != 0 && errorMessage == null)
    {
        errorMessage = $"The last character didn't have enough bytes to finish the codepoint. It was a multi-byte character that needed {remainingBytesInCurrentCodePoint}" +
            $" more byte{(remainingBytesInCurrentCodePoint == 1 ? null : "s")}.";
    }

    if (errorMessage != null)
    {
        throw new ArgumentException($"The byte array was not a valid byte array for a utf8 string: {errorMessage}", nameof(utf8Bytes));
    }

    return new string(contentWithMultiByteCharsEscaped.ToArray());

    void AddHexValuesToListFromByte(List<char> list, byte @byte)
    {
        // A byte is <= 255 so will always fit in a 2-digit hex number, hence the 2 in "X2". The X means hex.
        foreach (char c in @byte.ToString("X2"))
        {
            list.Add(c);
        }
    }
}
```

Title: Unicode characters on ZPL printer

Body:
I have the task of re-designing a system to print shipping labels, using a networked Zebra GK420T. I have been able to send ZPL print jobs to it perfectly fine, but I cannot seem to get it to print unicode characters, such as cyrillic letters. I have downloaded the lucida sans unicode font to the printer using the Seagull Scientific drivers and I am using the following ZPL code to test:

^XA
^LH100,150
^CI28
^FT0,0^A@N,50,50,R:LUCIDASR.FNT^CI28^FDTesting 1 2 3^FS
^FT0,50^A@N,50,50,R:LUCIDASR.FNT^CI28^FDДо свидания^FS
^FT0,100^B3^FDAAA001^FS
^XZ

It will print the 'Testing 1 2 3' and the barcode, but it leaves a blank space instead of the cyrillic characters.

I also tried using the Zebra swiss unicode font and now it prints the russian characters as question marks:

^XA
^LH100,150
^CWT,E:TT0003M_.FNT
^CFT,30,30
^CI28
^FT0,0^FDTesting 1 2 3^FS
^FT0,50^FDДо свидания^FS
^FT0,100^B3^FDAAA001^FS
^XZ

Am I doing something wrong like not escaping characters or something or is it a problem with the printer?

Body:
As others have noted, make sure to use ^CI28 (Change International Font/Encoding) and ^FH (Field Hexadecimal Indicator) and escape any non-ascii utf8 characters with an underscore and their hex value.

However another answer included code to format the utf8 string using a gigantic switch-case block. Here is the method I use for encoding to utf8, it should be able to format any valid utf8 byte array.

To get the byte array from a string use Encoding.UTF8.GetBytes(content).

// From the wikipedia page on utf8 encoding - https://en.wikipedia.org/wiki/UTF-8
    private const int _Last1ByteCodePointByte1 = 0x7F;
    private const int _First2ByteCodePointByte1 = 0xC0;
    private const int _Last2ByteCodePointByte1 = 0xDF;
    private const int _Last3ByteCodePointByte1 = 0xEF;
    private const int _Last4ByteCodePointByte1 = 0xF7;
    private const int _FirstMultiByteCodePointByte2 = 0x80;
    private const int _LastMultiByteCodePointByte2 = 0xBF;
    private const char _ZplMultiByteEscapeCharacter = '_';

/// <summary>
/// Encodes a sequence of utf8 bytes for printing with the ZPL language, this means escaping multi-byte characters with an underscore ('_') followed by the hex code
/// for each byte in the multi-byte characters.
/// </summary>
/// <param name="utf8Bytes">The bytes that make up the entire string, including bytes that need to be encoded and bytes that can be printed as-is.</param>
/// <returns>A string for printing with the ZPL language. Ie all multi-byte characters escaped with an underscore ('_') followed by the hex code for each byte.</returns>
/// <throws><see cref="ArgumentException"/> when <paramref name="utf8Bytes"/> isn't a valid utf8 encoding of a string.</throws>
/// <remarks>
/// Plan is to figure out how many bytes this character (code point) takes up, and if it's a 1 byte character, just use the character, but otherwise since it's a multi-byte
/// character then use an underscore ('_') followed by the hex encoded byte and each other byte in this code point will also be encoded. If we start the loop but have bytes
/// remaining in the current code point we know to hex encode this byte and continue.
/// </remarks>
private static string EncodeUtf8BytesForZPLIIPrinting(byte[] utf8Bytes)
{
    var contentWithMultiByteCharsEscaped = new List<char>();

    var multiByteCodePoint = new List<char>();
    var remainingBytesInCurrentCodePoint = 0;
    string errorMessage = null;

    foreach (byte utf8Byte in utf8Bytes)
    {
        if (remainingBytesInCurrentCodePoint > 0)
        {
            if (utf8Byte < _FirstMultiByteCodePointByte2 || utf8Byte > _LastMultiByteCodePointByte2)
            {
                errorMessage = $"The byte {utf8Byte.ToString("X2")} is not a valid as the second or later byte of a multi-byte utf8 character (codepoint).";
                break;
            }

            multiByteCodePoint.Add(_ZplMultiByteEscapeCharacter);
            AddHexValuesToListFromByte(multiByteCodePoint, utf8Byte);
            remainingBytesInCurrentCodePoint--;
            continue; // continue since we've dealt with this byte and don't want to flow on.
        }

        if (multiByteCodePoint.Any())
        {
            foreach (char c in multiByteCodePoint) contentWithMultiByteCharsEscaped.Add(c);
            multiByteCodePoint.Clear();
            // flow on to loop to see what to do with the current byte.
        }

        if (utf8Byte <= _Last1ByteCodePointByte1)
        {
            // 1 byte - no escaping
            contentWithMultiByteCharsEscaped.Add((char)utf8Byte);
        }
        else if (utf8Byte >= _First2ByteCodePointByte1 && utf8Byte <= _Last2ByteCodePointByte1)
        {
            // 2 bytes
            multiByteCodePoint.Add(_ZplMultiByteEscapeCharacter);
            AddHexValuesToListFromByte(multiByteCodePoint, utf8Byte);
            remainingBytesInCurrentCodePoint = 1;
        }
        else if (utf8Byte <= _Last3ByteCodePointByte1)
        {
            // 3 bytes
            multiByteCodePoint.Add(_ZplMultiByteEscapeCharacter);
            AddHexValuesToListFromByte(multiByteCodePoint, utf8Byte);
            remainingBytesInCurrentCodePoint = 2;
        }
        else if (utf8Byte <= _Last4ByteCodePointByte1)
        {
            // 4 bytes
            multiByteCodePoint.Add(_ZplMultiByteEscapeCharacter);
            AddHexValuesToListFromByte(multiByteCodePoint, utf8Byte);
            remainingBytesInCurrentCodePoint = 3;
        }
        else
        {
            errorMessage = $"The byte {utf8Byte.ToString("X2")} is not a valid as the first byte of a utf8 character.";
            break;
        }
    }

    // if the last char was multiByte add it now.
    if (multiByteCodePoint.Any())
    {
        foreach (var c in multiByteCodePoint) contentWithMultiByteCharsEscaped.Add(c);
        multiByteCodePoint.Clear();
    }

    if (remainingBytesInCurrentCodePoint != 0 && errorMessage == null)
    {
        errorMessage = $"The last character didn't have enough bytes to finish the codepoint. It was a multi-byte character that needed {remainingBytesInCurrentCodePoint}" +
            $" more byte{(remainingBytesInCurrentCodePoint == 1 ? null : "s")}.";
    }

    if (errorMessage != null)
    {
        throw new ArgumentException($"The byte array was not a valid byte array for a utf8 string: {errorMessage}", nameof(utf8Bytes));
    }

    return new string(contentWithMultiByteCharsEscaped.ToArray());

    void AddHexValuesToListFromByte(List<char> list, byte @byte)
    {
        // A byte is <= 255 so will always fit in a 2-digit hex number, hence the 2 in "X2". The X means hex.
        foreach (char c in @byte.ToString("X2"))
        {
            list.Add(c);
        }
    }
}


问:
Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'
I am implementing AudioVisualizer and I am trying to calculate time of audio but I am getting below error

Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'

Here is my code:

```<code> var lowPassReslts: Double = 0.0
 var lowPassReslts1: Double = 0.0

 let ALPHA: Float = 1.05

 let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
 lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts //HERE i am getting error which i mention above

 let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
 lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1 //HERE i am getting error
</code>```

This above code have converted from Objective-C. This code works perfect in Objective-C but it is not working in Swift. Can anyone please tell me how to solve this error?

答: You need to make same data type for both like both are double or both are float.</p>

Body:
I am implementing AudioVisualizer and I am trying to calculate time of audio but I am getting below error

Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'

Here is my code:

 var lowPassReslts: Double = 0.0
 var lowPassReslts1: Double = 0.0

 let ALPHA: Float = 1.05

 let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
 lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts //HERE i am getting error which i mention above

 let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
 lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1 //HERE i am getting error

This above code have converted from Objective-C. This code works perfect in Objective-C but it is not working in Swift. Can anyone please tell me how to solve this error?


问:
Displaying custom Select field in Dokan Vendor Dashboard
This is question have already been asked here How Add Custom Meta Fields to Dokan in New Product

But no one answered that question. What I am trying to achieve is following:

Need to display custom field in Dokan Vendor Dashboard, plugin author have answer with this "You have to customize Dokan plugin to add an extra field on the product upload form. Please open dokan-lite/templates/products/new-product.php and in this file, you have to add an extra field. As we do not provide support to customize our plugin for that reason, I am unable to provide more specific instruction :)"

I have created custom field already using Fields Factory Plugin and it's displaying fine in Add Single Product page.

But I am unable to add that field in Dokan Plugin screenshot below for the location.

答:
By default, it is not possible but you can modify the Dokan product upload form to add custom taxonomies. You can override dokan-lite/templates/products folder via child theme and then edit the necessary file :)

Now the rest of the process needs to be done by you. However, After adding the input filed you have to save the value of the field. On that place you have to use do_action( 'dokan_new_product_added', $product_id, $post_data ); this hook to save the field data.

When you will edit the product that time you have to use do_action( 'dokan_product_updated', $post_id ); to re-save.

ContentLicense: CC BY-SA 3.0


问:
How to update all columns in dataset except one column(CustName)
Im working on account rights management but i need to update all columns in a table in sql database from datagridview inputs except for one specific column. Thankyou! </p>

```
ID | custName | Active | Group

1  | Wanglu Lu|   1    |   1
2  | Levis Bel|   0    |   2
```

```<code>Dim comm As New SqlCommand
Dim dbread As SqlDataReader
Dim adptr As New SqlDataAdapter
Dim dt As New DataTable
Dim ds As New DataSet
Dim myBuilder As SqlCommandBuilder

Private Sub lbldgvUserID_TextChanged(sender As Object, e As EventArgs) Handles lbldgvUserID.TextChanged
    Try
        conn.Open()
        With comm
            .Connection = conn
            .CommandText = "SELECT ID,custName,Active,Group FROM tbl_customer WHERE ID= '" + lblUserID.Text + "'"
        End With
        adptr.SelectCommand = comm
        'dt.Clear()
        ds.Clear()
        adptr.Fill(ds, "tbl_customer")
        dgvPermissions.DataSource = ds.Tables("tbl_custorer").Rows(0)
    Catch ex As Exception
        MsgBox(ex.Message)
        conn.Close()
        End With
    End Try

    Dim builder As SqlCommandBuilder = New SqlCommandBuilder(adptr)

    adptr.Update(ds, "tbl_customer")
    MsgBox("Customer info successfuly updated!", MsgBoxStyle.Information)
</code>```

答:
You can do update column name after getting the result in a dataset. Here is a snippet. </p>

```<code>        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Rows.Add(25, "Indocin");
        table.Columns["Dosage"].ColumnName = "Dosage1";
</code>```

Body:
Im working on account rights management but i need to update all columns in a table in sql database from datagridview inputs except for one specific column. Thankyou!

ID | custName | Active | Group

1  | Wanglu Lu|   1    |   1
2  | Levis Bel|   0    |   2

Dim comm As New SqlCommand
Dim dbread As SqlDataReader
Dim adptr As New SqlDataAdapter
Dim dt As New DataTable
Dim ds As New DataSet
Dim myBuilder As SqlCommandBuilder

Private Sub lbldgvUserID_TextChanged(sender As Object, e As EventArgs) Handles lbldgvUserID.TextChanged
    Try
        conn.Open()
        With comm
            .Connection = conn
            .CommandText = "SELECT ID,custName,Active,Group FROM tbl_customer WHERE ID= '" + lblUserID.Text + "'"
        End With
        adptr.SelectCommand = comm
        'dt.Clear()
        ds.Clear()
        adptr.Fill(ds, "tbl_customer")
        dgvPermissions.DataSource = ds.Tables("tbl_custorer").Rows(0)
    Catch ex As Exception
        MsgBox(ex.Message)
        conn.Close()
        End With
    End Try

    Dim builder As SqlCommandBuilder = New SqlCommandBuilder(adptr)

    adptr.Update(ds, "tbl_customer")
    MsgBox("Customer info successfuly updated!", MsgBoxStyle.Information)

Body:
You can do update column name after getting the result in a dataset. Here is a snippet.

        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Rows.Add(25, "Indocin");
        table.Columns["Dosage"].ColumnName = "Dosage1";


问:
XMLHttpRequest Returns 404 Even Though File Exists
This is what the file structure for my project looks like. Voice, Text and Template are folders.

I run python app.py, and when I go to localhost http://0.0.0.0:8080/ I can see the index.html page with content piped in by app.py.

There's text in index.html that's piped in from voice.txt, and if I view voice.txt in my text editor I can see that a loop in app.py is successfully appending more text to it every 20 seconds.

The issue I'm having is trying to get the updated voice.txt text into the body of index.html. I'm trying to do this with XMLHttpRequest. Here's the relevant code from the  tag in index.html:

```<code>function UpdateText() {
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200) {
        // Code goes here
        document.getElementById("main").innerHTML = this.responseText;
        console.log(statusText);
        console.log(responseText);
    }
};

xhttp.open("GET", "../Text/voice.txt", true);
xhttp.send();

};
</code>```

When I run that index.html displays properly, but when it tries to update the text I get the following error message in Terminal:

```<code>127.0.0.1:64013 - - [28/May/2019 00:55:10] "HTTP/1.1 GET /Text/voice.txt" - 404 Not Found
</code>```

I could be wrong but at this point I'm fairly sure that the filepath in xhttp.open() should actually be a URL (this is the first time I'm using XMLHttpRequest and every tutorial I've seen just has the filename and nothing else), in which case I'm not sure how I'd link to voice.txt. I'm using the web.py library for this, here's the relevant section of app.py:

```<code>urls = (
"/", "index",
)

indexpath = "/Users/[USERNAME]/torch/torch-rnn/voice/Template/"
render = web.template.render(indexpath)

class index(object):
def GET(self):
    the_voice = open(voicepath, "r+").read()
    return render.index(the_voice)

if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
</code>```

I feel like the solution probably involves changing something in either the urls or render variables, but I've been going around in circles with this for hours and I'm out of ideas.

What I've Tried

First thought I had was to throw a dummy file called also called voice.txt into the Template folder next to index.html then change the filepath in the XMLHttpRequest to reflect that, but I still got the same error message.

答:
Your web server only knows about a single URL "/" and will return it when asked as 'https://:8080/'. That's all you've listed as possible values in your urls =() bit.

So, your attempt to get, via web interface, anything else will fail. If you want to have the webserver retrieve your voice.txt file, you need to include it, or something which will match it, in urls, and have that class then get and send on the voice.txt file. (Note that files themselves aren't in a Text folder, they could be anywhere, as described by myDirectory.)

For example,

```<code>urls = ( "/", "index",
         "/Text/(.*)", "get_file")

class get_file(object):
    def GET(self, filename):
        the_file = open(myDirectory + '/' + filename, "r").read()
        return the_file
</code>```

might do what you want (or give you some ideas). By using the regular expression in urls, any http get like '/Text/foo', '/Text/voice.txt', '/Text/ant_eater.jpg' will attempt to read the file ('foo', 'voice.txt', 'ant_eater.jpg') in the directory described by myDirectory, and return that file to the user.

If you're serving different types of files (as with my example) you should also set headers for the content type, but that's a different question.

Body:
This is what the file structure for my project looks like. Voice, Text and Template are folders.

I run python app.py, and when I go to localhost http://0.0.0.0:8080/ I can see the index.html page with content piped in by app.py.

There's text in index.html that's piped in from voice.txt, and if I view voice.txt in my text editor I can see that a loop in app.py is successfully appending more text to it every 20 seconds.

The issue I'm having is trying to get the updated voice.txt text into the body of index.html. I'm trying to do this with XMLHttpRequest. Here's the relevant code from the  tag in index.html:

function UpdateText() {
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200) {
        // Code goes here
        document.getElementById("main").innerHTML = this.responseText;
        console.log(statusText);
        console.log(responseText);
    }
};

xhttp.open("GET", "../Text/voice.txt", true);
xhttp.send();

};

When I run that index.html displays properly, but when it tries to update the text I get the following error message in Terminal:

127.0.0.1:64013 - - [28/May/2019 00:55:10] "HTTP/1.1 GET /Text/voice.txt" - 404 Not Found

I could be wrong but at this point I'm fairly sure that the filepath in xhttp.open() should actually be a URL (this is the first time I'm using XMLHttpRequest and every tutorial I've seen just has the filename and nothing else), in which case I'm not sure how I'd link to voice.txt. I'm using the web.py library for this, here's the relevant section of app.py:

urls = (
"/", "index",
)

indexpath = "/Users/[USERNAME]/torch/torch-rnn/voice/Template/"
render = web.template.render(indexpath)

class index(object):
def GET(self):
    the_voice = open(voicepath, "r+").read()
    return render.index(the_voice)

if __name__ == "__main__":
app = web.application(urls, globals())
app.run()

I feel like the solution probably involves changing something in either the urls or render variables, but I've been going around in circles with this for hours and I'm out of ideas.

What I've Tried

First thought I had was to throw a dummy file called also called voice.txt into the Template folder next to index.html then change the filepath in the XMLHttpRequest to reflect that, but I still got the same error message.

Body:
Your web server only knows about a single URL "/" and will return it when asked as 'https://:8080/'. That's all you've listed as possible values in your urls =() bit.

So, your attempt to get, via web interface, anything else will fail. If you want to have the webserver retrieve your voice.txt file, you need to include it, or something which will match it, in urls, and have that class then get and send on the voice.txt file. (Note that files themselves aren't in a Text folder, they could be anywhere, as described by myDirectory.)

For example,

urls = ( "/", "index",
         "/Text/(.*)", "get_file")

class get_file(object):
    def GET(self, filename):
        the_file = open(myDirectory + '/' + filename, "r").read()
        return the_file

might do what you want (or give you some ideas). By using the regular expression in urls, any http get like '/Text/foo', '/Text/voice.txt', '/Text/ant_eater.jpg' will attempt to read the file ('foo', 'voice.txt', 'ant_eater.jpg') in the directory described by myDirectory, and return that file to the user.

If you're serving different types of files (as with my example) you should also set headers for the content type, but that's a different question.


问:
Translate git-log old commiter timestamp to strict ISO 8601 timestamp
I am responsible for deploying an application and as part of the deployment process, I need to get the latest committer timestamp in strict ISO 8601 format and place it in the database. For recent versions of git, it's fairly straight forward:

```<code>$ git log --pretty=format:'%cI' -n1
2019-05-29T10:24:58+04:00
</code>```

But unfortunately, I have a few older instances where the switch %cI does not exist in the installed git. So to get close to the ISO 8601, I use %ci instead, resulting in:

```<code>$ git log --pretty=format:%ci -n1
2019-05-29 10:24:58 +0400
</code>```

We will eventually upgrade the machines to a later version of operating system, and consequently a more modern version of git. Newer versions of git has this in the man page:

```<code>   •   %ci: committer date, ISO 8601-like format

   •   %cI: committer date, strict ISO 8601 format
</code>```

But in the meantime, I want to massage this ISO 8601-like string on the older machines to the strict ISO 8601 format above. I wrote a bad looking one-liner to do this and it seems to work:

```<code>$ git log --pretty=format:'%ci' -n1 | sed -e 's/ /T/1' -e 's/ //1' -e 's/.\{22\}/&:/1'
2019-05-29T10:24:58+04:00
</code>```

Simply, it replaces the first space with a T, the second space with nothing and inserts a colon : at the 22nd character position. How do I do this better? I tried looking up ways to do this with the date command; no luck.

答:
you mean something like this?</p>

```<code>date -d "$(git log --pretty=format:%ci -n1)" --iso-8601=seconds
</code>```

Body:
I am responsible for deploying an application and as part of the deployment process, I need to get the latest committer timestamp in strict ISO 8601 format and place it in the database. For recent versions of git, it's fairly straight forward:

$ git log --pretty=format:'%cI' -n1
2019-05-29T10:24:58+04:00

But unfortunately, I have a few older instances where the switch %cI does not exist in the installed git. So to get close to the ISO 8601, I use %ci instead, resulting in:

$ git log --pretty=format:%ci -n1
2019-05-29 10:24:58 +0400

We will eventually upgrade the machines to a later version of operating system, and consequently a more modern version of git. Newer versions of git has this in the man page:

   •   %ci: committer date, ISO 8601-like format

   •   %cI: committer date, strict ISO 8601 format

But in the meantime, I want to massage this ISO 8601-like string on the older machines to the strict ISO 8601 format above. I wrote a bad looking one-liner to do this and it seems to work:

$ git log --pretty=format:'%ci' -n1 | sed -e 's/ /T/1' -e 's/ //1' -e 's/.\{22\}/&:/1'
2019-05-29T10:24:58+04:00

Simply, it replaces the first space with a T, the second space with nothing and inserts a colon : at the 22nd character position. How do I do this better? I tried looking up ways to do this with the date command; no luck.

Body:
you mean something like this?

date -d "$(git log --pretty=format:%ci -n1)" --iso-8601=seconds


问:
create multidimensional json array from a json in php
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.

Here is my data any code. Thanks in advance

My json data

```<code>$val = [
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p1'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p2'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p3'
    },
    {
     'city':'xx',
     'zone':'ww',
     'person_on_zone':'p1'
    },
  ]
</code>```

My expectation is

```<code>[
 {
  'city':'xx',
  'zone':'yy',
  'person_info':{
                  'person_on_zone':'p1',
                  'person_on_zone':'p2',
                  'person_on_zone':'p3',
                }
 },
 {
  'city':'xx',
  'zone':'ww',
  'person_info':{
                  'person_on_zone':'p1'
                }
 },
]
</code>```

Here I tried

```<code>foreach ($val as $v) {
    $new_array['city'] = $v['city'];
    $new_array['zone'] = $v['zone'];
    foreach ($val as $v2) {
        $new_array['person_info'] = $v['person_on_zone'];
    }
}
json_encode($new_array);
</code>```

答:
I think you make a mistake around composing the json. I tried with your code and i found following is the correct way to do.. Remember single quote(') is not  valid in json string that is being used to define key value pair in php

```<code>// I think your code has json string and i convert it into array of objects(stdClass)
// and if your code has array then keep you code intact but need to change the notation of
// objects to associative array.

// first thing first decode json string
$values =  json_decode('[
{ "city":"xx",
  "zone":"yy",
  "person_on_zone":"p1"
},
{
 "city":"xx",
 "zone":"yy",
 "person_on_zone":"p2"
},
{
 "city":"xx",
 "zone":"yy",
 "person_on_zone":"p3"
},
{
 "city":"xx",
 "zone":"ww",
 "person_on_zone":"p1"
}]');

// Now declare new values as array
$new_values = [];
// walk through each object
foreach ($values as $v){
    // $v becomes an object of stdClass here
    // $data is a temporary array
    $data['city'] = $v->city;
    $data['zone'] = $v->zone;
    $data['person_info'] = [];
    foreach ($values as $v2){
        if(!in_array($data['person_info'],['person_on_zone' => $v2->person_on_zone]))
        {
            // compare if zones are same or not
            if($v->zone == $v2->zone)
            {
                // push to the array instead of assiging
                array_push($data['person_info'], ['person_on_zone' => $v2->person_on_zone]);
            }
        }

    }
    // make array unique
    $data['person_info'] = array_map("unserialize", array_unique(array_map("serialize", $data['person_info'])));
    array_push($new_values, $data);
}
// make array unique in mutidimensional array
$new_values = array_map("unserialize", array_unique(array_map("serialize", $new_values)));
echo '```';
print_r($new_values);
echo '```';
</code>```

Body:
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.

Here is my data any code. Thanks in advance

My json data

$val = [
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p1'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p2'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p3'
    },
    {
     'city':'xx',
     'zone':'ww',
     'person_on_zone':'p1'
    },
  ]

My expectation is

[
 {
  'city':'xx',
  'zone':'yy',
  'person_info':{
                  'person_on_zone':'p1',
                  'person_on_zone':'p2',
                  'person_on_zone':'p3',
                }
 },
 {
  'city':'xx',
  'zone':'ww',
  'person_info':{
                  'person_on_zone':'p1'
                }
 },
]

Here I tried

foreach ($val as $v) {
    $new_array['city'] = $v['city'];
    $new_array['zone'] = $v['zone'];
    foreach ($val as $v2) {
        $new_array['person_info'] = $v['person_on_zone'];
    }
}
json_encode($new_array);

Body:
I think you make a mistake around composing the json. I tried with your code and i found following is the correct way to do.. Remember single quote(') is not  valid in json string that is being used to define key value pair in php

// I think your code has json string and i convert it into array of objects(stdClass)
// and if your code has array then keep you code intact but need to change the notation of
// objects to associative array.

// first thing first decode json string
$values =  json_decode('[
{ "city":"xx",
  "zone":"yy",
  "person_on_zone":"p1"
},
{
 "city":"xx",
 "zone":"yy",
 "person_on_zone":"p2"
},
{
 "city":"xx",
 "zone":"yy",
 "person_on_zone":"p3"
},
{
 "city":"xx",
 "zone":"ww",
 "person_on_zone":"p1"
}]');

// Now declare new values as array
$new_values = [];
// walk through each object
foreach ($values as $v){
    // $v becomes an object of stdClass here
    // $data is a temporary array
    $data['city'] = $v->city;
    $data['zone'] = $v->zone;
    $data['person_info'] = [];
    foreach ($values as $v2){
        if(!in_array($data['person_info'],['person_on_zone' => $v2->person_on_zone]))
        {
            // compare if zones are same or not
            if($v->zone == $v2->zone)
            {
                // push to the array instead of assiging
                array_push($data['person_info'], ['person_on_zone' => $v2->person_on_zone]);
            }
        }

    }
    // make array unique
    $data['person_info'] = array_map("unserialize", array_unique(array_map("serialize", $data['person_info'])));
    array_push($new_values, $data);
}
// make array unique in mutidimensional array
$new_values = array_map("unserialize", array_unique(array_map("serialize", $new_values)));
echo '<pre>';
print_r($new_values);
echo '</pre>';


问:
How can i open a form always in Edit mode , for a particular model
I have a model say 'my.attendance' , also have a form view for this which contains some attendance details.What i need is when i open this form view it should always open in Edit mode.So i can directly enter the attendance without clicking Edit button each time.</p>

答:
You have to extend the ViewManager to achieve this.</p>

```<code>odoo.define('my_module.view_manager', function (require) {
"use strict";

var ViewManager = require('web.ViewManager');

ViewManager.include({

    custom_events: {

        execute_action: function(event) {
            var data = event.data;
            this.do_execute_action(data.action_data, data.env, data.on_closed)
                .then(data.on_success, data.on_fail);
        },
        search: function(event) {
            var d = event.data;
            _.extend(this.env, this._process_search_data(d.domains, d.contexts, d.groupbys));
            this.active_view.controller.reload(_.extend({offset: 0}, this.env));
        },
        switch_view: function(event) {
            if ('res_id' in event.data) {
                this.env.currentId = event.data.res_id;
            }
            var options = {};
            console.log(event.data)
            if (event.data.view_type === 'form' && !this.env.currentId) {
                options.mode = 'edit';
            } else if (event.data.mode) {
                options.mode = event.data.mode;
            }

            // Extra added code
            if (event.data.model){
                if (event.data.model == 'my.model'){  // Checking the particular model.
                    options.mode = 'edit';
                }
            }

            this.switch_mode(event.data.view_type, options);
        },
        env_updated: function(event) {
            _.extend(this.env, event.data);
        },
        push_state: function(event) {
            this.do_push_state(event.data);
        },
        get_controller_context: '_onGetControllerContext',
        switch_to_previous_view: '_onSwitchToPreviousView',
    },

 });
});
</code>```

Body:
You have to extend the ViewManager to achieve this.

odoo.define('my_module.view_manager', function (require) {
"use strict";

var ViewManager = require('web.ViewManager');

ViewManager.include({

    custom_events: {

        execute_action: function(event) {
            var data = event.data;
            this.do_execute_action(data.action_data, data.env, data.on_closed)
                .then(data.on_success, data.on_fail);
        },
        search: function(event) {
            var d = event.data;
            _.extend(this.env, this._process_search_data(d.domains, d.contexts, d.groupbys));
            this.active_view.controller.reload(_.extend({offset: 0}, this.env));
        },
        switch_view: function(event) {
            if ('res_id' in event.data) {
                this.env.currentId = event.data.res_id;
            }
            var options = {};
            console.log(event.data)
            if (event.data.view_type === 'form' && !this.env.currentId) {
                options.mode = 'edit';
            } else if (event.data.mode) {
                options.mode = event.data.mode;
            }

            // Extra added code
            if (event.data.model){
                if (event.data.model == 'my.model'){  // Checking the particular model.
                    options.mode = 'edit';
                }
            }

            this.switch_mode(event.data.view_type, options);
        },
        env_updated: function(event) {
            _.extend(this.env, event.data);
        },
        push_state: function(event) {
            this.do_push_state(event.data);
        },
        get_controller_context: '_onGetControllerContext',
        switch_to_previous_view: '_onSwitchToPreviousView',
    },

 });
});


问:
determine jpeg filesize without actually saving the jpeg
I have an image in PNG or BMP format. I would like to find out the filesize of that image after compressing it to a jpeg without saving the jpeg.

Up to now I did it the following way:

```<code>frameNormal.Save("temp.jpg", ImageFormat.Jpeg);
tempFile = new FileInfo("temp.jpg");
filesizeJPG = tempFile.Length;
</code>```

But because of the slow disk access, the program takes too long.
Is there a way to calculate the filesize of the newly created jpeg? Like converting the PNG in memory and read the size...

Any help is very much appreciated :-)

答:
You can write the image data to a Stream instead of supplying a filename:

```<code>using (MemoryStream mem = new MemoryStream())
{
    frameNormal.Save(mem, ImageFormat.Jpeg);
    filesizeJPG = mem.Length;
}
</code>```

Body:
I have an image in PNG or BMP format. I would like to find out the filesize of that image after compressing it to a jpeg without saving the jpeg.

Up to now I did it the following way:

frameNormal.Save("temp.jpg", ImageFormat.Jpeg);
tempFile = new FileInfo("temp.jpg");
filesizeJPG = tempFile.Length;

But because of the slow disk access, the program takes too long.
Is there a way to calculate the filesize of the newly created jpeg? Like converting the PNG in memory and read the size...

Any help is very much appreciated :-)

Body:
You can write the image data to a Stream instead of supplying a filename:

using (MemoryStream mem = new MemoryStream())
{
    frameNormal.Save(mem, ImageFormat.Jpeg);
    filesizeJPG = mem.Length;
}


问:
.split() sequence doesn't work more than one time
I'm trying to solve a problem where I need to clear text (to get rid off of all punctuation and spaces) and get it to the same register.

```<code>with open("moby_01.txt") as infile, open("moby_01_clean_3.txt", "w") as outfile:
    for line in infile:
        line.lower
        ...
        cleaned_words = line.split("-")
        cleaned_words = "\n".join(cleaned_words)
        cleaned_words = line.strip().split()
        cleaned_words = "\n".join(cleaned_words)
        outfile.write(cleaned_words)
</code>```

I expect the output of program be list of words as they are in text but by one in line. But it turns out in for loop only last three lines itirates and output is list of words with punctuation:

```<code>Call
me
Ishmael.
Some
years
ago--never
mind
how
long
precisely--having
...
</code>```

答:
You might want to change this. You are using the line again here.

```<code>cleaned_words = line.strip().split()

</code>```

to

```<code>cleaned_words = cleaned_words.strip().split()
</code>```

Body:
I'm trying to solve a problem where I need to clear text (to get rid off of all punctuation and spaces) and get it to the same register.

with open("moby_01.txt") as infile, open("moby_01_clean_3.txt", "w") as outfile:
    for line in infile:
        line.lower
        ...
        cleaned_words = line.split("-")
        cleaned_words = "\n".join(cleaned_words)
        cleaned_words = line.strip().split()
        cleaned_words = "\n".join(cleaned_words)
        outfile.write(cleaned_words)

I expect the output of program be list of words as they are in text but by one in line. But it turns out in for loop only last three lines itirates and output is list of words with punctuation:

Call
me
Ishmael.
Some
years
ago--never
mind
how
long
precisely--having
...

Body:
You might want to change this. You are using the line again here.

cleaned_words = line.strip().split()

to

cleaned_words = cleaned_words.strip().split()


答:
An option would be gather the data into 'long' format and unite the 'Year/Month' column with 'key' to create the 'Period'

```<code>library(tidyverse)
library(zoo)
gather(df1, key, val, -`Year/Month`) %>%
     unite(Period, key, `Year/Month`, sep="-") %>%
     mutate(Period = as.yearmon(Period, '%b-%Y')) %>%
     arrange(Period)
#    Period val
#1 Apr 2012 201
#2 May 2012 203
#3 Jun 2012 208
#4 Apr 2013 220
#5 May 2013 221
#6 Jun 2013 222
</code>```

data

```<code>df1 <- structure(list(`Year/Month` = 2012:2013, APR = c(201L, 220L),
    MAY = c(203L, 221L), JUN = c(208L, 222L)), class = "data.frame",
 row.names = c(NA, -2L))
</code>```

Title: Making a time series data

Body:
I have a dataframe of time series observations like below

 Year/Month APR MAY JUN.......MAR
    2012     201 203 208...   2016
    2013     220 221 222......2018
    2014      ....................
     .        .
     .        .
     .        .
    2019      230 235 237      240

I need the data to be like this

 Period      Value
Apr-2012      .
May-2012      .
Jun-2012      .
.
.
.
.
.
Apr-2013
May-2013
Jun-2013
.
.
.
Jan-2019
Feb-2019
Mar-2019       .

Body:
An option would be gather the data into 'long' format and unite the 'Year/Month' column with 'key' to create the 'Period'

library(tidyverse)
library(zoo)
gather(df1, key, val, -`Year/Month`) %>%
     unite(Period, key, `Year/Month`, sep="-") %>%
     mutate(Period = as.yearmon(Period, '%b-%Y')) %>%
     arrange(Period)
#    Period val
#1 Apr 2012 201
#2 May 2012 203
#3 Jun 2012 208
#4 Apr 2013 220
#5 May 2013 221
#6 Jun 2013 222

data

df1 <- structure(list(`Year/Month` = 2012:2013, APR = c(201L, 220L),
    MAY = c(203L, 221L), JUN = c(208L, 222L)), class = "data.frame",
 row.names = c(NA, -2L))