问:
How do you make an image span the width of eBay's description field exactly? (No horizontal scrolling)
eBay listings have a description field with 5000 character limit. It allows some html tags and the style attribute, but a lot of functionality is disabled.

When I insert an image that is too wide, eBay adds horizontal scrolling, which is a terrible user experience. I want an image that automatically resizes to the available width without triggering horizontal scrolling.

It seems the most widely used, and officially recommended method of resizing to different screens, is changing the viewport using the meta tag as described here.

Unfortunately this also changes the text size, and doesn't give the option to only scale one image and not others. Is this the only method? Or is there another way?

Or am I just using the meta tag wrong? (I put <meta name="viewport" content="width=device-width, initial-scale=1"> on the first line and wrote the rest of the description under it.)

答:
This is the old code I've used for a template in the past. Using containers and remotely hosted CSS I was able to constrain images to the container wrapped around the whole template.

Unfortunately, as you know, eBay is a bit rubbish when it comes to responsive CSS, so this doesn't work well when under 1400px (I think).

I think you may be able to add some responsive media queries in order to stack this properly. However, this was created before the days of good responsive design I'm afraid.

CSS

```<code>@charset "utf-8";
/* CSS Document */

body {
background:#ffffff;
/*background-image:url(http://www.unbmedia.co.uk/Clients/UNB09029/bg.jpg);*/
background-position:center;
background-repeat:repeat-y;
}

/* Constrain Page Size */
.pagewidth {
    width:954px;
    text-align: centre;
    left: 0;
    margin:auto;
}

.pageminwidth {
    text-align: left;
    left: 0;
}

/* Footer Links with Country Names */
#sFooter {
    text-align:center;
    font-size:10px;
}

/* Ebay Footer Links */
span.ebay{
    text-align:center;
}

#title{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    font-size:24px;
    background:#548101;
    color:#FFF;
    padding:20px;
    color:#777;
    font-size:14px;
    padding:3px;
    font-family: serif;
    letter-spacing: 0.5px;
    font-weight: 100;
    transition: all 0.3s;
}

#left-men-tit{
    background: #18213E;

    color:white;
    font-size:14px;
    padding:3px;
    font-family: serif;
    letter-spacing: 0.5px;
    font-weight: 100;
    transition: all 0.3s;
    padding:10px;

}

#left-men{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#548101;
    font-size:14px;
    padding-left:12px;
    padding-top:3px;
    padding-bottom:3px;

}

#desc-title-list{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#548101;
    font-size:12px;
}

#desc-desc-list{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;   color:#000000;
    font-size:12px;
}

#product-desc-title{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;   color:#fff;
    font-size:12px;
    background-color:#548101;
    padding:10px;

}

#product-desc{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#000000;
    font-size:12px;
    padding-left:5px;
}

td#product-desc{
    border:thin;
    border-color:#000;
}
table#desc{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    vertical-align:text-top;
}

#Main{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    vertical-align:top;
}

#main-holder{
    font-size:0px;
}

/* Category Links */
a:link{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#777;
    font-size:12px;
    padding:3px;
    text-decoration:none;
    font-weight:bold;
}

a:visited{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#777;
    font-size:12px;
    padding:3px;
    text-decoration:none;
    font-weight:bold;
}

a:hover{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color: #18213E;
    font-size:12px;
    /*background:#024873;*/
    text-decoration:none;
    padding:3px;
    font-weight:bold;
    padding-left: 7px;
}

a:active{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#548101;
    font-size:12px;
    /*background:#024873;*/
    text-decoration:none;
    padding:3px;
    font-weight:bold;
}

div#EBdescription{
    font-size:0px;
}

/*** NEW LISTING TEMPLATE CSS ***/
.container{ width: 100%; max-width: 1100px; margin:auto;}
.ebayList-MainCol{float: right; width: 79%;}
.ebayList-LeftCol{float: right; width: 21%; margin-top: 162px;}
.ebayList-LeftCol h3{display: block; width: 87%; padding: 10px; margin: 0 0px 0 0; background: #18213E; color: white;
font-size: 16px; font-weight: 100; border: 1px solid black; width: 200px;}
.ebayList-LeftCol ul{ border: 1px solid #CCC; padding: 10px; margin: 0 10px 0 0; }
.ebayList-LeftCol li:before { content: ">"; padding-left: 5px; padding-right: 5px; margin-left: 0px; font-size: 14px;}
    .ebayList-LeftCol li{ list-style: none; font-size: 14px; font-weight: 100; color:#777; padding: 10px 0;}
        .ebayList-LeftCol li a:link{font-weight: 100; color:#777!important; font-family: serif; font-size: 14px; letter-spacing: 0.5px; transition: all 0.3s;}
        .ebayList-LeftCol li a:hover{transition: all 0.3s;}
.ebayList-Header img{ width: 100%;}
.ebayList-ProductImage{width: 100%; text-align: center;}
    .ebayList-ProductImage img{width: 100%; margin: auto; position: relative; text-align: center;}
    .ebayList-ProductImage h1{ text-align: center; font-weight: 100; letter-spacing: 1px; font-size: 26px; color: #18213E; max-width: 900px; width: 100%; margin: 50px auto; }
.ebayList-Summary--Wrapper{float: left;}
  .ebayList-Summary { width: 50%; float: left;}
.ebayList-Summary h2{ font-weight: 100; font-size: 16px; margin-top: 30px; border-bottom: 1px solid #ccc;padding-bottom: 10px;}
    .ebayList-Summary p{ font-weight: 100; font-size: 14px; line-height: 22px;}
.ebayList-Spec { width: 48%; float: left; margin-bottom: 20px; margin-top: 0px; padding-left: 2%}
.ebayList-Spec h2{font-weight: 100; font-size: 16px; margin-top: 30px; border-bottom: 1px solid #ccc;padding-bottom: 10px;}
    .ebayList-Spec dl{ width: 100%;}
        .ebayList-Spec dt{ width: 30%; float: left; font-weight: bold; margin: 0; font-size: 14px; margin-bottom: 5px;}
        .ebayList-Spec dd{ width: 70%; float: left; margin: 0; font-size: 14px; margin-bottom: 5px;}
.ebayList-Shipping-Returns { float: left; width: 50%; text-align: left; margin-bottom: 50px;}
    .ebayList-Shipping-Returns img{width:98%;}
    .ebayList-Shipping-Returns + .ebayList-Shipping-Returns{text-align: right;}
.ebayList-footer{float: left;}
    .ebayList-footer img{ width: 100%;}

@media (max-width:1000px) {
    .ebayList-LeftCol{ display: none; }
    .ebayList-MainCol{ width: 100%; }
}
@media (max-width:700px) {
    .ebayList-Spec{ width: 100%; padding-left: 0;}
    .ebayList-Summary{ width: 100%; }
    .ebayList-Shipping-Returns{ width: 100%; }
}
</code>```

Listing Description:

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://remote.littens.co.uk/listing.css" type="text/css">
<div class="container">
  <div class="ebayList-Header"><img src="https://remote.littens.co.uk/header.png" alt=""></div>
  <div class="ebayList-MainCol">
    <div class="ebayList-ProductImage">
      <h1>CHILDREN'S CHARACTER DESIGN BEANBAG BEAN BAG SEAT FILLED JUNIOR KIDS TODDLER</h1>
      <img src="https://i.ebayimg.com/00/s/OTIxWDEyMjg=/z/tagAAOSw-vlViACO/$_57.JPG?set_id=880000500F">
    </div>
    <div class="ebayList-Summary--Wrapper">
      <div class="ebayList-Summary">
        <h2>Product Summary</h2>
        <p>These are official novelty character licensed beanbags. These are filled to a perfect volume of 3 cubic ft, giving it an ideal structure and cushioning for the children to sit and enjoy. These would make an ideal piece of soft furniture in
          a child’s room. All our products are fully compliant to the UK Furniture and Furnishings Regulations.</p>
        <p>Please select the design you require from the drop down menu at the top.</p>
      </div>
      <div class="ebayList-Spec">
        <h2>Specification</h2>
        <dl>
          <dt>Product</dt>
          <dd>Beanbag</dd>
          <dt>Brand</dt>
          <dd>Assort</dd>
          <dt>Version</dt>
          <dd>Kids</dd>
          <dt>Colour</dt>
          <dd>Assort</dd>
          <dt>Size</dt>
          <dd>3 Cubic Feet</dd>
          <dt>Dimensions</dt>
          <dd>50x50x50cm</dd>
          <dt>Includes</dt>
          <dd>Beanbag & Filling</dd>
          <dt>Material</dt>
          <dd>100% Cotton / Polystyrene Bead</dd>
          <dt>Washable</dt>
          <dd>Cover Machine Washable</dd>
          <dt>Suitability</dt>
          <dd>Over 3 Years Of Age</dd>
        </dl>
      </div>
    </div>
    <div class="ebayList-Shipping-Returns">
      <img src="https://remote.littens.co.uk/postage-info.png" alt="">
    </div>
    <div class="ebayList-Shipping-Returns">
      <img src="https://remote.littens.co.uk/returns-policy.png" alt="">
    </div>
  </div>
  <div class="ebayList-LeftCol">
    <h3>Shop Categories</h3>
    <ul>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Duvets-/_i.html?_fsub=2&_sid=167663432&_trksid=p4634.c0.m322">Duvets</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Pillows-/_i.html?_fsub=9&_lns=2&_sid=167663432&_trksid=p4634.c0.m322">Pillows</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Mattress-Toppers-/_i.html?_fsub=1442372012&_lns=2&_sid=167663432&_trksid=p4634.c0.m322">Mattress Toppers</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Curtains-/_i.html?_fsub=3367499012&_sid=167663432&_trksid=p4634.c0.m322">Curtains</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Duvet-Cover-Sets-/_i.html?_fsub=7&_sid=167663432&_trksid=p4634.c0.m322">Duvet Covers Sets</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Cushion-Covers-/_i.html?_fsub=10617545012&_sid=167663432&_trksid=p4634.c0.m322">Cushion Covers</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Bedding-Bundle-Sets-/_i.html?_fsub=3&_sid=167663432&_trksid=p4634.c0.m322">Bedding Bundle Sets</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Childrens-Room-/_i.html?_fsub=8&_sid=167663432&_trksid=p4634.c0.m322">Childrens Room</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Nursery-Baby-/_i.html?_fsub=1066056012&_sid=167663432&_trksid=p4634.c0.m322">Nursery & Baby</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Livingroom-/_i.html?_fsub=1269320012&_sid=167663432&_trksid=p4634.c0.m322">Livingroom</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Bed-Linen-/_i.html?_fsub=1442373012&_sid=167663432&_trksid=p4634.c0.m322">Bed Linen</a></li>
      <li><a href="Bedspreads / Throws">Bedspreads / Throws</a></li>
    </ul>
  </div>
  <div class="ebayList-footer">
    <img src="https://remote.littens.co.uk/footer.png" alt="footer">
  </div>
</div>
</code>```

Body:
This is the old code I've used for a template in the past. Using containers and remotely hosted CSS I was able to constrain images to the container wrapped around the whole template.

Unfortunately, as you know, eBay is a bit rubbish when it comes to responsive CSS, so this doesn't work well when under 1400px (I think).

I think you may be able to add some responsive media queries in order to stack this properly. However, this was created before the days of good responsive design I'm afraid.

CSS

@charset "utf-8";
/* CSS Document */

body {
background:#ffffff;
/*background-image:url(http://www.unbmedia.co.uk/Clients/UNB09029/bg.jpg);*/
background-position:center;
background-repeat:repeat-y;
}

/* Constrain Page Size */
.pagewidth {
    width:954px;
    text-align: centre;
    left: 0;
    margin:auto;
}

.pageminwidth {
    text-align: left;
    left: 0;
}

/* Footer Links with Country Names */
#sFooter {
    text-align:center;
    font-size:10px;
}

/* Ebay Footer Links */
span.ebay{
    text-align:center;
}

#title{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    font-size:24px;
    background:#548101;
    color:#FFF;
    padding:20px;
    color:#777;
    font-size:14px;
    padding:3px;
    font-family: serif;
    letter-spacing: 0.5px;
    font-weight: 100;
    transition: all 0.3s;
}

#left-men-tit{
    background: #18213E;

    color:white;
    font-size:14px;
    padding:3px;
    font-family: serif;
    letter-spacing: 0.5px;
    font-weight: 100;
    transition: all 0.3s;
    padding:10px;

}

#left-men{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#548101;
    font-size:14px;
    padding-left:12px;
    padding-top:3px;
    padding-bottom:3px;

}

#desc-title-list{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#548101;
    font-size:12px;
}

#desc-desc-list{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;   color:#000000;
    font-size:12px;
}

#product-desc-title{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;   color:#fff;
    font-size:12px;
    background-color:#548101;
    padding:10px;

}

#product-desc{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#000000;
    font-size:12px;
    padding-left:5px;
}

td#product-desc{
    border:thin;
    border-color:#000;
}
table#desc{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    vertical-align:text-top;
}

#Main{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    vertical-align:top;
}

#main-holder{
    font-size:0px;
}

/* Category Links */
a:link{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#777;
    font-size:12px;
    padding:3px;
    text-decoration:none;
    font-weight:bold;
}

a:visited{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#777;
    font-size:12px;
    padding:3px;
    text-decoration:none;
    font-weight:bold;
}

a:hover{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color: #18213E;
    font-size:12px;
    /*background:#024873;*/
    text-decoration:none;
    padding:3px;
    font-weight:bold;
    padding-left: 7px;
}

a:active{
    font:Arial, Helvetica, sans-serif;
    font-family:Arial, Helvetica, sans-serif;
    color:#548101;
    font-size:12px;
    /*background:#024873;*/
    text-decoration:none;
    padding:3px;
    font-weight:bold;
}

div#EBdescription{
    font-size:0px;
}

/*** NEW LISTING TEMPLATE CSS ***/
.container{ width: 100%; max-width: 1100px; margin:auto;}
.ebayList-MainCol{float: right; width: 79%;}
.ebayList-LeftCol{float: right; width: 21%; margin-top: 162px;}
.ebayList-LeftCol h3{display: block; width: 87%; padding: 10px; margin: 0 0px 0 0; background: #18213E; color: white;
font-size: 16px; font-weight: 100; border: 1px solid black; width: 200px;}
.ebayList-LeftCol ul{ border: 1px solid #CCC; padding: 10px; margin: 0 10px 0 0; }
.ebayList-LeftCol li:before { content: ">"; padding-left: 5px; padding-right: 5px; margin-left: 0px; font-size: 14px;}
    .ebayList-LeftCol li{ list-style: none; font-size: 14px; font-weight: 100; color:#777; padding: 10px 0;}
        .ebayList-LeftCol li a:link{font-weight: 100; color:#777!important; font-family: serif; font-size: 14px; letter-spacing: 0.5px; transition: all 0.3s;}
        .ebayList-LeftCol li a:hover{transition: all 0.3s;}
.ebayList-Header img{ width: 100%;}
.ebayList-ProductImage{width: 100%; text-align: center;}
    .ebayList-ProductImage img{width: 100%; margin: auto; position: relative; text-align: center;}
    .ebayList-ProductImage h1{ text-align: center; font-weight: 100; letter-spacing: 1px; font-size: 26px; color: #18213E; max-width: 900px; width: 100%; margin: 50px auto; }
.ebayList-Summary--Wrapper{float: left;}
  .ebayList-Summary { width: 50%; float: left;}
.ebayList-Summary h2{ font-weight: 100; font-size: 16px; margin-top: 30px; border-bottom: 1px solid #ccc;padding-bottom: 10px;}
    .ebayList-Summary p{ font-weight: 100; font-size: 14px; line-height: 22px;}
.ebayList-Spec { width: 48%; float: left; margin-bottom: 20px; margin-top: 0px; padding-left: 2%}
.ebayList-Spec h2{font-weight: 100; font-size: 16px; margin-top: 30px; border-bottom: 1px solid #ccc;padding-bottom: 10px;}
    .ebayList-Spec dl{ width: 100%;}
        .ebayList-Spec dt{ width: 30%; float: left; font-weight: bold; margin: 0; font-size: 14px; margin-bottom: 5px;}
        .ebayList-Spec dd{ width: 70%; float: left; margin: 0; font-size: 14px; margin-bottom: 5px;}
.ebayList-Shipping-Returns { float: left; width: 50%; text-align: left; margin-bottom: 50px;}
    .ebayList-Shipping-Returns img{width:98%;}
    .ebayList-Shipping-Returns + .ebayList-Shipping-Returns{text-align: right;}
.ebayList-footer{float: left;}
    .ebayList-footer img{ width: 100%;}

@media (max-width:1000px) {
    .ebayList-LeftCol{ display: none; }
    .ebayList-MainCol{ width: 100%; }
}
@media (max-width:700px) {
    .ebayList-Spec{ width: 100%; padding-left: 0;}
    .ebayList-Summary{ width: 100%; }
    .ebayList-Shipping-Returns{ width: 100%; }
}

Listing Description:

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://remote.littens.co.uk/listing.css" type="text/css">
<div class="container">
  <div class="ebayList-Header"><img src="https://remote.littens.co.uk/header.png" alt=""></div>
  <div class="ebayList-MainCol">
    <div class="ebayList-ProductImage">
      <h1>CHILDREN'S CHARACTER DESIGN BEANBAG BEAN BAG SEAT FILLED JUNIOR KIDS TODDLER</h1>
      <img src="https://i.ebayimg.com/00/s/OTIxWDEyMjg=/z/tagAAOSw-vlViACO/$_57.JPG?set_id=880000500F">
    </div>
    <div class="ebayList-Summary--Wrapper">
      <div class="ebayList-Summary">
        <h2>Product Summary</h2>
        <p>These are official novelty character licensed beanbags. These are filled to a perfect volume of 3 cubic ft, giving it an ideal structure and cushioning for the children to sit and enjoy. These would make an ideal piece of soft furniture in
          a child’s room. All our products are fully compliant to the UK Furniture and Furnishings Regulations.</p>
        <p>Please select the design you require from the drop down menu at the top.</p>
      </div>
      <div class="ebayList-Spec">
        <h2>Specification</h2>
        <dl>
          <dt>Product</dt>
          <dd>Beanbag</dd>
          <dt>Brand</dt>
          <dd>Assort</dd>
          <dt>Version</dt>
          <dd>Kids</dd>
          <dt>Colour</dt>
          <dd>Assort</dd>
          <dt>Size</dt>
          <dd>3 Cubic Feet</dd>
          <dt>Dimensions</dt>
          <dd>50x50x50cm</dd>
          <dt>Includes</dt>
          <dd>Beanbag &amp; Filling</dd>
          <dt>Material</dt>
          <dd>100% Cotton / Polystyrene Bead</dd>
          <dt>Washable</dt>
          <dd>Cover Machine Washable</dd>
          <dt>Suitability</dt>
          <dd>Over 3 Years Of Age</dd>
        </dl>
      </div>
    </div>
    <div class="ebayList-Shipping-Returns">
      <img src="https://remote.littens.co.uk/postage-info.png" alt="">
    </div>
    <div class="ebayList-Shipping-Returns">
      <img src="https://remote.littens.co.uk/returns-policy.png" alt="">
    </div>
  </div>
  <div class="ebayList-LeftCol">
    <h3>Shop Categories</h3>
    <ul>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Duvets-/_i.html?_fsub=2&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Duvets</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Pillows-/_i.html?_fsub=9&amp;_lns=2&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Pillows</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Mattress-Toppers-/_i.html?_fsub=1442372012&amp;_lns=2&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Mattress Toppers</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Curtains-/_i.html?_fsub=3367499012&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Curtains</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Duvet-Cover-Sets-/_i.html?_fsub=7&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Duvet Covers Sets</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Cushion-Covers-/_i.html?_fsub=10617545012&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Cushion Covers</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Bedding-Bundle-Sets-/_i.html?_fsub=3&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Bedding Bundle Sets</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Childrens-Room-/_i.html?_fsub=8&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Childrens Room</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Nursery-Baby-/_i.html?_fsub=1066056012&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Nursery &amp; Baby</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Livingroom-/_i.html?_fsub=1269320012&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Livingroom</a></li>
      <li><a href="http://stores.ebay.co.uk/Littens-Co/Bed-Linen-/_i.html?_fsub=1442373012&amp;_sid=167663432&amp;_trksid=p4634.c0.m322">Bed Linen</a></li>
      <li><a href="Bedspreads / Throws">Bedspreads / Throws</a></li>
    </ul>
  </div>
  <div class="ebayList-footer">
    <img src="https://remote.littens.co.uk/footer.png" alt="footer">
  </div>
</div>


来源: stackexchange

问:
stuck on Unity 3D Package Manager Error when trying to open any Unity project
I have been facing this error for 5 months.

I have tried everything to fix it. Nothing's working. I have driven myself to near insanity trying to fix this problem.

Everything i try to boot up a Unity Project, this error shows up:

i hate this image so much

PLEASE. IF YOU HAVE A SOLUTION, TELL ME.

答:
have you tried the following?

Firewall White-listing of the editor program:

Go to windows firewall -> Advanced Settings -> Inbound rules - > Create new Rule-> type: program -> Complete path to the unity editor -> Allow Connections -> Give it a name -> Save.

Setting Environmental variables:

HTTP_PROXY, HTTPS_PROXY and UNITY_NOPROXY=localhost,127.0.0.1

Even if you already have a rule for Unity explicitly recreate it!

I hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Download artifacts in Release Pipeline
I get an error 'There is not enough space on the disk' during download artifacts from CloudVault.
Is it possible to increase the size of memory for artifacts that can be downloaded by task 'Download Artifacts - CloudVault' in Release pipeline?
If not, are there simple ways to download a few different subfolders from CloudVault?</p>

答:
It seems there is no enough space on the disk where need to download the artifact. You need to check the disk space and clean the space on the machine, to make sure there is enough space to get the artifact.

Also, if you want to download a few different subfolders of pipeline artifacts using Download Pipeline Artifacts task from earlier stages in this pipeline, or from another pipeline, you could try Matching Patterns:

Title: Download artifacts in Release Pipeline


问:
Compiling Java program in terminal causes log error
I am trying to compile a Java program in the terminal:

Long version containing all the imports:

```<code>javac -classpath bin:$OSPL_HOME/jar/dcpssaj5.jar:$OSPL_HOME/jar/dcpssaj5-sources.jar:$OSPL_HOME/jar/dcpssaj-osgi-bundle.jar:$OSPL_HOME/jar/dcpssaj-sources.jar:$OSPL_HOME/jar/dcpssaj.jar:$OSPL_HOME/jar/osplconf.jar:$OSPL_HOME/jar/tooling_common.jar:$OSPL_HOME/jar/dcpsprotobuf.jar:$OSPL_HOME/jar/cmdataadapter.jar:$OSPL_HOME/jar/cmapi.jar:$OSPL_HOME/jar/ddsface.jar:Libraries/httpclient-4.5.12.jar:Libraries/jersey-client-1.19.4.jar:Libraries/jersey-client-1.19.jar:Libraries/jersey-core-1.19.4.jar:Libraries/json-simple-1.1.1.jar:Libraries/json-simple-3.1.0.jar:Libraries/jsr311-api-1.1.1.jar:Libraries/mqtt-client-0.0.6.jar:Libraries/paho-mqtt-client-1.13.0.jar -sourcepath src/ src/afarcloud/Main/afarcloud_main.java
</code>```

Without all the imports:

```<code>javac -classpath bin:(jar_files) -sourcepath src/ src/afarcloud/Main/afarcloud_main.java
</code>```

I have added what I thought would be all the necessaries jars, however I get the following error related to a logger when I try to run the code on my Ubuntu computer:

```<code>src/afarcloud/Log/UtilLog.java:3: error: package org.apache.log4j does not exist
import org.apache.log4j.Logger;
                       ^
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                   ^
  symbol:   class Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                                ^
  symbol:   variable Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:10: error: cannot find symbol
        log = Logger.getLogger(clase);
              ^
  symbol:   variable Logger
  location: class UtilLog
4 errors
</code>```

What confuses me is that there is no folder called "Log" under src/afarcloud, so I am pretty confused about how to proceed... Any help is highly appreciated, thank you.

答:
Looks that you're missing import statement. As a conclusion, all Logger Objects cannot be find and any new instances cant be created.

Try to use import org.apache.log4j.Logger;.

Or import via CLI. https://logging.apache.org/log4j/2.x/download.html

Body:
I am trying to compile a Java program in the terminal:

Long version containing all the imports:

javac -classpath bin:$OSPL_HOME/jar/dcpssaj5.jar:$OSPL_HOME/jar/dcpssaj5-sources.jar:$OSPL_HOME/jar/dcpssaj-osgi-bundle.jar:$OSPL_HOME/jar/dcpssaj-sources.jar:$OSPL_HOME/jar/dcpssaj.jar:$OSPL_HOME/jar/osplconf.jar:$OSPL_HOME/jar/tooling_common.jar:$OSPL_HOME/jar/dcpsprotobuf.jar:$OSPL_HOME/jar/cmdataadapter.jar:$OSPL_HOME/jar/cmapi.jar:$OSPL_HOME/jar/ddsface.jar:Libraries/httpclient-4.5.12.jar:Libraries/jersey-client-1.19.4.jar:Libraries/jersey-client-1.19.jar:Libraries/jersey-core-1.19.4.jar:Libraries/json-simple-1.1.1.jar:Libraries/json-simple-3.1.0.jar:Libraries/jsr311-api-1.1.1.jar:Libraries/mqtt-client-0.0.6.jar:Libraries/paho-mqtt-client-1.13.0.jar -sourcepath src/ src/afarcloud/Main/afarcloud_main.java

Without all the imports:

javac -classpath bin:(jar_files) -sourcepath src/ src/afarcloud/Main/afarcloud_main.java

I have added what I thought would be all the necessaries jars, however I get the following error related to a logger when I try to run the code on my Ubuntu computer:

src/afarcloud/Log/UtilLog.java:3: error: package org.apache.log4j does not exist
import org.apache.log4j.Logger;
                       ^
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                   ^
  symbol:   class Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                                ^
  symbol:   variable Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:10: error: cannot find symbol
        log = Logger.getLogger(clase);
              ^
  symbol:   variable Logger
  location: class UtilLog
4 errors

What confuses me is that there is no folder called "Log" under src/afarcloud, so I am pretty confused about how to proceed... Any help is highly appreciated, thank you.


问:
CredSSP Encryption Oracle Remediation Error
Hello we are using Azure Virtural Machine. Now We cannot remote into the server due to the following error message. Would like to get suggestion on the error since we don't have the support plan and the live agent suggest me to ask here.

Thanks all.

Error Message Image

答:
This issue can be resolved, just use this below command
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters" /f /v AllowEncryptionOracle /t REG_DWORD /d 2</p>


问:
Why does not the background color get applied from props using state for a styled component div using react and typescript?
i want the background color of the styled component div to change to grey when state active is true using react and typescript.

below is my code,

```<code>function Parent() {
    const [active, setActive] = useState(false);
    return (
        <Wrapper>
            <StyledDiv active={active}>
                Element whose background should change
            </StyledDiv>
        </Wrapper>
    );
}

const StyledDiv = styled.div<{ active?: boolean }>`
    ${({ active }) =>
        active &&
        `background-color: ${(props: any) => props.grey}`};
`;
</code>```

From the above code background color doesnt change to grey if accessed from props.

What works?

```<code>const StyledDiv = styled.div<{ active?: boolean }>`
    ${({ active }) =>
        active &&
        'background-color:grey'};
`;

           OR
 const StyledDiv = styled.div<{ active?: boolean }>`
     background-color: ${(props: any) => props.grey};
`;
</code>```

I am not sure whats wrong with this. could someone help me fix this. i want to use props to change background color based on active state.

thanks.

答:
You should be using the active prop that is defined as part of the props of the StyledDiv styled component, to dynamically set the div's background-color,

```<code> const StyledDiv = styled.div<{ active?: boolean }>`
     background-color: ${({ active }) => active ? 'blue' : 'grey'};
`;
</code>```

Body:
i want the background color of the styled component div to change to grey when state active is true using react and typescript.

below is my code,

function Parent() {
    const [active, setActive] = useState(false);
    return (
        <Wrapper>

        </Wrapper>
    );
}

const StyledDiv = styled.div<{ active?: boolean }>`
    ${({ active }) =>
        active &&
        `background-color: ${(props: any) => props.grey}`};
`;

From the above code background color doesnt change to grey if accessed from props.

What works?

const StyledDiv = styled.div<{ active?: boolean }>`
    ${({ active }) =>
        active &&
        'background-color:grey'};
`;

           OR
 const StyledDiv = styled.div<{ active?: boolean }>`
     background-color: ${(props: any) => props.grey};
`;

I am not sure whats wrong with this. could someone help me fix this. i want to use props to change background color based on active state.

thanks.

Body:
You should be using the active prop that is defined as part of the props of the StyledDiv styled component, to dynamically set the div's background-color,

 const StyledDiv = styled.div<{ active?: boolean }>`
     background-color: ${({ active }) => active ? 'blue' : 'grey'};
`;


问:
hive syntax error near unexpected token `('
My Hive query has been throwing an error:

syntax error near unexpected token `('

I am not sure where the error occurs in the query below.

Can you help me out?

```<code>select
    A.dataA, B.dataB, count(A.nid), count(B.nid)
from
    (select
        nid, sum(dataA_count) as dataA
    from
        table_view
    group by nid) A
        LEFT JOIN
    (select
        nid, sum(dataB_count) as dataB
    from
        table_others
    group by nid) B ON A.nid = B.nid
group by A.dataA , B.dataB;
</code>```

答: I have gone through many posts but i didn't realize the my beeline terminal is logged off and i am trying in normal terminal</p>

ContentLicense: CC BY-SA 3.0

Body:
My Hive query has been throwing an error:

syntax error near unexpected token `('

I am not sure where the error occurs in the query below.

Can you help me out?

select
    A.dataA, B.dataB, count(A.nid), count(B.nid)
from
    (select
        nid, sum(dataA_count) as dataA
    from
        table_view
    group by nid) A
        LEFT JOIN
    (select
        nid, sum(dataB_count) as dataB
    from
        table_others
    group by nid) B ON A.nid = B.nid
group by A.dataA , B.dataB;


问:
Laravel & VueJS CORS Issue when trying to authenticate the user, even with the Cors middleware
I'm trying to make an authentication gateway for my project and I keep on getting a cors error like this:

cors error in browser console

I am using Laravel for the gateway and Vue.js for the front end. I have made a cors middleware like shown in this video

Here's my login function in Laravel

```<code>public function login(Request $request){
    $loginCreds = $request->validate([
       'email' => 'required|string',
       'password' => 'required|string'
    ]);

    if(!auth()->attempt( $loginCreds )){
        return response()->json(['message'=>'Invalid login credentials.']);
    }

    $at = auth()->user()->createToken('authToken')->accessToken;

    return response()->json(['user'=>Auth::user(), 'access_token' => $at]);
}
</code>```

And here's my call I make from the front end

```<code>        submitLogin() {
            let params = new URLSearchParams();
            params.append('email', this.email);
            params.append('password', this.password);
            axios({
                method: 'post',
                url: 'http://localhost:3000/api/auth/login',
                data: params
            })
                .then(res => {
                    console.log(res);
                }).catch(err => console.log(err));
        }
</code>```

That setup gives me the error but if I do the same call but I have the following in my login function it doesn't give me the error

```<code>public function login(Request $request)
{
    return \GuzzleHttp\json_encode('ok');
}
</code>```

I don't know what to do, any help is appreciated, thank you in advance!

[Edit]

My Cors middleware

```<code>namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");
        //ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
        ];
        if ($request->getMethod() == "OPTIONS"){
            //The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return response()->json('OK',200,$headers);
        }
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;
    }
}
</code>```

And Kernel.php

```<code><?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}
</code>```

I use Laravel v7.14.1 and Laravel Passport for authentication

答:
[Edit]

Try to Update the header returned in app/Http/Middleware/Cors.php

```<code><?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
   public function handle($request, Closure $next)
   {
     return $next($request)
       ->header(‘Access-Control-Allow-Origin’, ‘*’)
       ->header(‘Access-Control-Allow-Methods’, ‘GET, POST, PUT, DELETE, OPTIONS’)
       ->header(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type, X-Token-Auth, Authorization’);
   }
}
</code>```

Source : Medium

[Alternative]

I'm using fruitcake/laravel-cors package, you may give it a try

Setup steps

1. Installation

Require the fruitcake/laravel-cors package in your composer.json and update your dependencies:

```<code>composer require fruitcake/laravel-cors
</code>```

2. Publish Configuration

Publish the config to copy the file to your own config: config/cors.php

```<code>php artisan vendor:publish --tag="cors"
</code>```

3. Usage

3.1 Global usage

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

```<code>protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];
</code>```

3.2 ONLY for API Routes usage

To allow CORS for your API routes, add the HandleCors middleware in the $middlewareGroups property of app/Http/Kernel.php class:

```<code>protected $middlewareGroups = [
     'web' => [
          // ...
     ],

     'api' => [
          // ...
          \Fruitcake\Cors\HandleCors::class,
     ],
];
</code>```

Repo link

Hope it helps

Body:
I'm trying to make an authentication gateway for my project and I keep on getting a cors error like this:

cors error in browser console

I am using Laravel for the gateway and Vue.js for the front end. I have made a cors middleware like shown in this video

Here's my login function in Laravel

public function login(Request $request){
    $loginCreds = $request->validate([
       'email' => 'required|string',
       'password' => 'required|string'
    ]);

    if(!auth()->attempt( $loginCreds )){
        return response()->json(['message'=>'Invalid login credentials.']);
    }

    $at = auth()->user()->createToken('authToken')->accessToken;

    return response()->json(['user'=>Auth::user(), 'access_token' => $at]);
}

And here's my call I make from the front end

        submitLogin() {
            let params = new URLSearchParams();
            params.append('email', this.email);
            params.append('password', this.password);
            axios({
                method: 'post',
                url: 'http://localhost:3000/api/auth/login',
                data: params
            })
                .then(res => {
                    console.log(res);
                }).catch(err => console.log(err));
        }

That setup gives me the error but if I do the same call but I have the following in my login function it doesn't give me the error

public function login(Request $request)
{
    return \GuzzleHttp\json_encode('ok');
}

I don't know what to do, any help is appreciated, thank you in advance!

[Edit]

My Cors middleware

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");
        //ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
        ];
        if ($request->getMethod() == "OPTIONS"){
            //The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return response()->json('OK',200,$headers);
        }
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;
    }
}

And Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}

I use Laravel v7.14.1 and Laravel Passport for authentication

Body:
[Edit]

Try to Update the header returned in app/Http/Middleware/Cors.php

<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
   public function handle($request, Closure $next)
   {
     return $next($request)
       ->header(‘Access-Control-Allow-Origin’, ‘*’)
       ->header(‘Access-Control-Allow-Methods’, ‘GET, POST, PUT, DELETE, OPTIONS’)
       ->header(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type, X-Token-Auth, Authorization’);
   }
}

Source : Medium

[Alternative]

I'm using fruitcake/laravel-cors package, you may give it a try

Setup steps

1. Installation

Require the fruitcake/laravel-cors package in your composer.json and update your dependencies:

composer require fruitcake/laravel-cors

2. Publish Configuration

Publish the config to copy the file to your own config: config/cors.php

php artisan vendor:publish --tag="cors"

3. Usage

3.1 Global usage

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];

3.2 ONLY for API Routes usage

To allow CORS for your API routes, add the HandleCors middleware in the $middlewareGroups property of app/Http/Kernel.php class:

protected $middlewareGroups = [
     'web' => [
          // ...
     ],

     'api' => [
          // ...
          \Fruitcake\Cors\HandleCors::class,
     ],
];

Repo link

Hope it helps


问:
Maven Build successful but my test case didnt run in eclipse
I created a simple Maven project in Eclipse to add and subtract 2 numbers -

wen i Run as Maven build - build successful but my test case didnt run.

Below is the console output:

below is my Pom.xml:

Can any please help ...

Thanks

答: Firstly make sure you didn't click on 'Skip Tests' radio button, then check your test location. </p>


问:
Can I use ASP.NET MVC3 exclusively as a RESTful Web Service?
I'm building a READ ONLY sencha-touch app for our local church.

We use Vimeo to host all of our videos, and I'd like to integrate our Vimeo vids as well as our RSS feed into our web app.

The rest of the "content" in the app will be static "info" as well as a contact form.

My question is, is it kosher to ONLY use ASP.NET MVC3 (minus the "V") to drive the JSON to our web app?

答:
Yes, this works great. Just return a JsonResult.

Here is an example I am using in production:

```<code> public partial class StudentController : BaseController {
    public StudentController(RESTContext portalContext)
        : base(portalContext) { }

    [HttpGet, Url("organizations/{organizationId?}/students")]
    public virtual JsonResult List(Guid? organizationId) {
        if (organizationId != RESTContext.OrganizationId)
            throw new HttpNotAuthorizedException();

        var query = RESTContext.GetQuery<IQuery<StudentCasesReport>>()
            .Where(x => x.OrganizationId, organizationId)
            .OrderBy(x => x.LastName, SortOrder.Ascending);
        var cases = query.Execute(IsolationLevel.ReadUncommitted);

        return Json(cases, JsonRequestBehavior.AllowGet);
    }

    [HttpGet, Url("organizations/{organizationId?}/students/{studentId?}")]
    public virtual JsonResult Get(Guid? organizationId, Guid? studentId) {
        if (studentId.IsNull())
            throw new HttpNotFoundExecption();

        if (organizationId != RESTContext.OrganizationId)
            throw new HttpNotModifiedException();

        var query = RESTContext.GetQuery<IQuery<StudentCasesReport>>()
            .Where(x => x.OrganizationId, organizationId)
            .Where(x => x.StudentCaseId, studentId)
            .OrderBy(x => x.LastName, SortOrder.Ascending);
        var cases = query.Execute(IsolationLevel.ReadUncommitted).FirstOrDefault();

        if (cases.IsNull())
            throw new HttpNotFoundExecption();

        return Json(cases, JsonRequestBehavior.AllowGet);
    }
}
</code>```

Body:
Yes, this works great. Just return a JsonResult.

Here is an example I am using in production:

 public partial class StudentController : BaseController {
    public StudentController(RESTContext portalContext)
        : base(portalContext) { }

    [HttpGet, Url("organizations/{organizationId?}/students")]
    public virtual JsonResult List(Guid? organizationId) {
        if (organizationId != RESTContext.OrganizationId)
            throw new HttpNotAuthorizedException();

        var query = RESTContext.GetQuery<IQuery<StudentCasesReport>>()
            .Where(x => x.OrganizationId, organizationId)
            .OrderBy(x => x.LastName, SortOrder.Ascending);
        var cases = query.Execute(IsolationLevel.ReadUncommitted);

        return Json(cases, JsonRequestBehavior.AllowGet);
    }

    [HttpGet, Url("organizations/{organizationId?}/students/{studentId?}")]
    public virtual JsonResult Get(Guid? organizationId, Guid? studentId) {
        if (studentId.IsNull())
            throw new HttpNotFoundExecption();

        if (organizationId != RESTContext.OrganizationId)
            throw new HttpNotModifiedException();

        var query = RESTContext.GetQuery<IQuery<StudentCasesReport>>()
            .Where(x => x.OrganizationId, organizationId)
            .Where(x => x.StudentCaseId, studentId)
            .OrderBy(x => x.LastName, SortOrder.Ascending);
        var cases = query.Execute(IsolationLevel.ReadUncommitted).FirstOrDefault();

        if (cases.IsNull())
            throw new HttpNotFoundExecption();

        return Json(cases, JsonRequestBehavior.AllowGet);
    }
}


问:
How to test a JSONP method in a service - Angular
I am making a simple email subscription application for which I have written tests and things went fine as for now.

In order to make things simple, I wish to explain the exact part where I am facing the issue.

my-service.ts :

```<code>export class MyService {

  mailChimpEndpoint =
    'https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp';

  constructor(private _http: HttpClient) {}

  submitForm(email: string){

        const params = new HttpParams()

        .set('EMAIL', email)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')

        const mailChimpUrl = this.mailChimpEndpoint + params.toString();

        return this._http.jsonp<MailChimpResponse>(mailChimpUrl, 'c')
  }

}
</code>```

The above is a simple method in a service that calls an api

Link to the service file: https://stackblitz.com/edit/angular-testing-imniaf?file=app%2Fmy-service.ts

Now I am trying to write a test case for the above method submitForm in

my-service.spec.ts

```<code>  it('check subscribeEmail function has been called in service', (done: DoneFn) => {
    const service = TestBed.get(MyService);
    service.submitForm('test@gmail.com').subscribe(
        response => {
            expect(response).toEqual(mockServiceData);
        }
    )

    const reqMock = httpTestingController.expectOne(request => request.url === mailChimpEndpoint);
    expect(reqMock.request.method).toBe('GET');
    reqMock.flush(mockServiceData);
  });
</code>```

Link to this spec file: https://stackblitz.com/edit/angular-testing-imniaf?file=app%2Fmy-service.spec.ts

This is where I am getting stucked and the above code throws the error as,

Error: Expected one matching request for criteria "Match by function:
  ", found none.

The complete working stackblitz link:

https://stackblitz.com/edit/angular-testing-ajoov8

Please help me to pass this test as success.

答:
HttpClient should be a spy, then you can assert it.

TestBed.configureTestingModule({
  // add this to the definition of the testing module
  providers: [{
    provide: HttpClient,
    useValue: {
      jsonp: jasmine.createSpy('httpClient.jsonp'),
    }
  }]
})
```

<p>and then in the test</p>

<pre class="lang-js prettyprint-override"><code>  it('check subscribeEmail function has been called in service', (done: DoneFn) => {
    const service = TestBed.get(MyService);
    const httpClient = TestBed.get(HttpClient);

    const expected: any = Symbol();
    (httpClient.jsonp as any).and.returnValue(expected);

    const actual = service.submitForm('test@gmail.com');
    expect(actual).toBe(expected);
    expect(httpClient.jsonp).toHaveBeenCalledWith(provideValueHere, 'c');
  });
</code>```

and now your test should be like that:

import { HttpClient } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';

import { MyService } from './my-service';

describe('MyService', () => {
  beforeEach(() => TestBed.configureTestingModule({
      providers: [
        MyService,
        {
          provide: HttpClient,
          useValue: {
            jsonp: jasmine.createSpy('httpClient.jsonp'),
          }
        }
      ]
    }).compileComponents());

  it('check subscribeEmail function has been called in service', () => {
    const httpClient = TestBed.get(HttpClient);
    const service = TestBed.get(MyService);

    const expected: any = Symbol();
    (httpClient.jsonp as any).and.returnValue(expected);

    const actual = service.submitForm('test@gmail.com');
    expect(actual).toBe(expected);
    expect(httpClient.jsonp).toHaveBeenCalledWith('https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&ampEMAIL=test@gmail.com&subscribe=Subscribe&b_aaa7182511d7bd278fb9d510d_01681f1b55=', 'c');
  });
});
```

Body:
I am making a simple email subscription application for which I have written tests and things went fine as for now.

In order to make things simple, I wish to explain the exact part where I am facing the issue.

my-service.ts :

export class MyService {

  mailChimpEndpoint =
    'https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp';

  constructor(private _http: HttpClient) {}

  submitForm(email: string){

        const params = new HttpParams()

        .set('EMAIL', email)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')

        const mailChimpUrl = this.mailChimpEndpoint + params.toString();

        return this._http.jsonp<MailChimpResponse>(mailChimpUrl, 'c')
  }

}

The above is a simple method in a service that calls an api

Link to the service file: https://stackblitz.com/edit/angular-testing-imniaf?file=app%2Fmy-service.ts

Now I am trying to write a test case for the above method submitForm in

my-service.spec.ts

  it('check subscribeEmail function has been called in service', (done: DoneFn) => {
    const service = TestBed.get(MyService);
    service.submitForm('test@gmail.com').subscribe(
        response => {
            expect(response).toEqual(mockServiceData);
        }
    )

    const reqMock = httpTestingController.expectOne(request => request.url === mailChimpEndpoint);
    expect(reqMock.request.method).toBe('GET');
    reqMock.flush(mockServiceData);
  });

Link to this spec file: https://stackblitz.com/edit/angular-testing-imniaf?file=app%2Fmy-service.spec.ts

This is where I am getting stucked and the above code throws the error as,

Error: Expected one matching request for criteria "Match by function:
  ", found none.

The complete working stackblitz link:

https://stackblitz.com/edit/angular-testing-ajoov8

Please help me to pass this test as success.

Body:
HttpClient should be a spy, then you can assert it.

TestBed.configureTestingModule({
  // add this to the definition of the testing module
  providers: [{
    provide: HttpClient,
    useValue: {
      jsonp: jasmine.createSpy('httpClient.jsonp'),
    }
  }]
})

and then in the test

  it('check subscribeEmail function has been called in service', (done: DoneFn) => {
    const service = TestBed.get(MyService);
    const httpClient = TestBed.get(HttpClient);

    const expected: any = Symbol();
    (httpClient.jsonp as any).and.returnValue(expected);

    const actual = service.submitForm('test@gmail.com');
    expect(actual).toBe(expected);
    expect(httpClient.jsonp).toHaveBeenCalledWith(provideValueHere, 'c');
  });

and now your test should be like that:

import { HttpClient } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';

import { MyService } from './my-service';

describe('MyService', () => {
  beforeEach(() => TestBed.configureTestingModule({
      providers: [
        MyService,
        {
          provide: HttpClient,
          useValue: {
            jsonp: jasmine.createSpy('httpClient.jsonp'),
          }
        }
      ]
    }).compileComponents());

  it('check subscribeEmail function has been called in service', () => {
    const httpClient = TestBed.get(HttpClient);
    const service = TestBed.get(MyService);

    const expected: any = Symbol();
    (httpClient.jsonp as any).and.returnValue(expected);

    const actual = service.submitForm('test@gmail.com');
    expect(actual).toBe(expected);
    expect(httpClient.jsonp).toHaveBeenCalledWith('https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55&ampEMAIL=test@gmail.com&subscribe=Subscribe&b_aaa7182511d7bd278fb9d510d_01681f1b55=', 'c');
  });
});


问:
How to use mouse click and keyboard keys in combination / together to perform or call any function in JAVASCRIPT?
I have a function which is called on click of a button i.e:

```<code>function print(){
alert("PRINT")
}

btn.addEventListener("click", print);
</code>```

This will print as soon as button is clicked . But I want to call this function on the combination of keyboard key + mouse click i.e something like (q+click) i.e user press q key of keyboard and by clicking the q along mouse click . For control key it can be done easily , but for other keys how it could be done ??

Thanks

答:
If you using RxJS, then you can achieve you wanted task more easily.

This is code for your task.

```<code>import { of, fromEvent, merge } from 'rxjs';
import { map } from 'rxjs/operators';

const halloBtn = document.getElementById('hallo_btn');

const halloBtnClick$ = fromEvent(halloBtn, 'click');

const pressKey$ = fromEvent(document, 'keydown');

const keyUp$ = fromEvent(document, 'keyup');

let keydownFlag = false;

merge(
  halloBtnClick$,
  pressKey$,
  keyUp$
).subscribe(event => {
  if (event.type === 'keydown') {
    keydownFlag = true;
  }

  if (event.type === 'keyup') {
    console.log('key up ... ');
    keydownFlag = false;
  }

  if (keydownFlag && event.type === 'click') {
    alert('wow..');
    keydownFlag = false;
  }
})
</code>```

Body:
I have a function which is called on click of a button i.e:

function print(){
alert("PRINT")
}

btn.addEventListener("click", print);

This will print as soon as button is clicked . But I want to call this function on the combination of keyboard key + mouse click i.e something like (q+click) i.e user press q key of keyboard and by clicking the q along mouse click . For control key it can be done easily , but for other keys how it could be done ??

Thanks

Body:
If you using RxJS, then you can achieve you wanted task more easily.

This is code for your task.

import { of, fromEvent, merge } from 'rxjs';
import { map } from 'rxjs/operators';

const halloBtn = document.getElementById('hallo_btn');

const halloBtnClick$ = fromEvent(halloBtn, 'click');

const pressKey$ = fromEvent(document, 'keydown');

const keyUp$ = fromEvent(document, 'keyup');

let keydownFlag = false;

merge(
  halloBtnClick$,
  pressKey$,
  keyUp$
).subscribe(event => {
  if (event.type === 'keydown') {
    keydownFlag = true;
  }

  if (event.type === 'keyup') {
    console.log('key up ... ');
    keydownFlag = false;
  }

  if (keydownFlag && event.type === 'click') {
    alert('wow..');
    keydownFlag = false;
  }
})


问:
Need some advice to choose the proper container
I'm trying to design a task scheduler to a game engine. A task could be an animation, a trigger controller, etc.

My problem is what container to choose. The idea is: when you insert a new task, the container must reorder and put the task in the proper place. Once executed, task could change and be scheduled again or deleted. This is mainly push and pop.

But, if possible, it would be nice if I could have random access to an element, but not vital. No matter if the container supports one or more elements with the same key.

I think that priority queue fits my needs but I saw that is based on vector implementation, and I think that this container must be somehow  optimized to push and pop.

Opinions?

答:
You can specify the container type you want with std::priority_queue.
However: you're storing pointers (I presume, since it sounds like what you're is
polymorphic and has identity), so copying is cheap.  You're managing it
as a heap (that's what std::priority_queue does), so insertions are done
using push_back and a number of swaps (lg(n) max).  I can't see any
reason to even consider another structure than std::vector.

std::priority_queue does hide all of the direct access operators (e.g.
operator[]).  It does this because if you modify an entry, you're
likely to invalidate the heap (which is a class invariant of the class).
If you do want to provide direct read access, however, the underlying
container is only protected, not private, so you can derive from it
and add the operators you want.  I'd very much limit it to const
operators, however.


问:
copying C-style arrays and structure
C++ does not allow copying of C-style arrays using =. But allows copying of structures using =, as in this link -> Copying array in C v/s copying structure in C.It does not have any credible answers yet.
 But consider following code

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

struct user {
    int a[4];
    char c;
};

int main() {
    user a{{1,2,3,4}, 'a'}, b{{4,5,6,7}, 'b'};
    a = b;             //should have given any error or warning but nothing
    return 0;
}
</code>```

Above code segment didn't gave any kind of errors and warnings, and just works fine. WHY?
Consider explaining both questions(this one and the one linked above).

答:
Your class user gets an implicitly declared copy constructor and implicitly declared copy assignment operator.

The implicitly declared copy assignment operator copies the content from b to a.

Two passages from the standard that seems to apply:

class.copy.ctor

if the member is an array, each element is direct-initialized with the corresponding subobject of x;

class.copy.assign

if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

Title: copying C-style arrays and structure

Body:
C++ does not allow copying of C-style arrays using =. But allows copying of structures using =, as in this link -> Copying array in C v/s copying structure in C.It does not have any credible answers yet.
 But consider following code

#include <iostream>
using namespace std;

struct user {
    int a[4];
    char c;
};

int main() {
    user a{{1,2,3,4}, 'a'}, b{{4,5,6,7}, 'b'};
    a = b;             //should have given any error or warning but nothing
    return 0;
}

Above code segment didn't gave any kind of errors and warnings, and just works fine. WHY?
Consider explaining both questions(this one and the one linked above).


问:
Google end point gives Invalid HTTP template in logs for GET /
I am using google end points to deploy some of my apis. I am exposing health API on [GET /] which returns http 200 so that GKE ingress can consider my container as healthy by invoking this API.

But when I am invoking this end point using [ip-address/], end point always complains method not exist.
This works fine for path [ip-address/hello]

Ask: Should I configure / end point in some different manner.

Below are the starter logs of ESP (GKE extensible service proxy container)

```<code>nginx: [warn] Using trusted CA certificates file: /etc/nginx/trusted-ca-certificates.crt
2020/06/02 11:33:13[error]1#1: Invalid HTTP template: /
2020/06/02 11:33:13[error]1#1: Failed to add http rule: selector: "1.abcd_api_endpoints_my_app_cloud_goog.GetHealth"
get: "/"
</code>```

My open api sepecification yaml

```<code>swagger: "2.0"
info:
  title: Dummy API
  description: Dummy API
  version: 1.0.0
host: abcd-api.endpoints.my-app.cloud.goog
consumes:
  - application/json
produces:
  - application/json
schemes:
  - http
paths:
  /:
    get:
      description: Logs service health status
      operationId: getHealth
      responses:
        '200':
          description: Logs service health.
  /hello:
    get:
      description: Returns Hello World
      operationId: helloWorld
      responses:
        '200':
          description: Returns Hello World
</code>```

答:
After reading through Google end points limitation for esp, I came to know that requests on root path are rejected by esp.

https://cloud.google.com/endpoints/docs/openapi/openapi-limitations#operations_on_url_root_path_

To resolve this problem and providing health end point esp provides --healthz paramter.

https://cloud.google.com/endpoints/docs/openapi/specify-proxy-startup-options

https://github.com/GoogleCloudPlatform/endpoints-samples/blob/master/k8s/esp_echo_gke_ingress.yaml

Body:
I am using google end points to deploy some of my apis. I am exposing health API on [GET /] which returns http 200 so that GKE ingress can consider my container as healthy by invoking this API.

But when I am invoking this end point using [ip-address/], end point always complains method not exist.
This works fine for path [ip-address/hello]

Ask: Should I configure / end point in some different manner.

Below are the starter logs of ESP (GKE extensible service proxy container)

nginx: [warn] Using trusted CA certificates file: /etc/nginx/trusted-ca-certificates.crt
2020/06/02 11:33:13[error]1#1: Invalid HTTP template: /
2020/06/02 11:33:13[error]1#1: Failed to add http rule: selector: "1.abcd_api_endpoints_my_app_cloud_goog.GetHealth"
get: "/"

My open api sepecification yaml

swagger: "2.0"
info:
  title: Dummy API
  description: Dummy API
  version: 1.0.0
host: abcd-api.endpoints.my-app.cloud.goog
consumes:
  - application/json
produces:
  - application/json
schemes:
  - http
paths:
  /:
    get:
      description: Logs service health status
      operationId: getHealth
      responses:
        '200':
          description: Logs service health.
  /hello:
    get:
      description: Returns Hello World
      operationId: helloWorld
      responses:
        '200':
          description: Returns Hello World


问:
Java lambdas heap dump - Instance of lambda not getting garbage collected
I am facing some problems with garbage collection while generating an application in java, where I use Stream.map to trim all the elements in the list. The instances of anonymous lambda class exist in the heap dump even though the instance of the enclosing class is 0 as shown in the snap of visual VM.

The LambdaTesting class:

```<code>class LambdaTesting {

    protected List<String> values;

    protected LambdaTesting(List<String> values) {
        this.values = values;
    }
    public List<String> modify() {
        return this.values.stream().map(x -> x.trim()).collect(Collectors.toList());
    }
    public List<String> modifyLocal() {
        List<String> localValue = new ArrayList<>();
        localValue.add("Local FOO ");
        localValue.add("Local BAR ");
        return localValue.stream().map(x -> x.trim()).collect(Collectors.toList());
   }
}
</code>```

The method which creates the instance of LambdaTesting and invokes these methods:

```<code>public List<String> testMethods() {
    List<String> test = new ArrayList<>();
    test.add("Global FOO  ");
    test.add("   GLOBAL BAR");
    LambdaTesting lambdaTesting = new LambdaTesting(test);
    lambdaTesting.modifyLocal();
    lambdaTesting.modify();
}
</code>```

The thread dump was taken after putting a debug point at the next line after testMethods is invoked.

Why are the references to Lambda still present in the heap dump?

答:
As elaborated in Does a lambda expression create an object on the heap every time it's executed?, a non-capturing lambda expression will be remembered and reused, which implies that it is permanently associated with the code that created it. That’s not different to, e.g. string literals whose object representation stays in memory as long as the code containing the literal is alive.

This is an implementation detail. It doesn’t have to be that way, but the reference implementation and hence, all commonly used JREs do it that way.

A non-capturing lambda expression is a lambda expression that uses no (non-constant) variables of the surrounding context and does not use this, neither implicitly nor explicitly. So it bears no state, hence, consumes a tiny amount of memory. There is also no possibility to create a leak regarding other objects, as having references to other objects is what makes the difference between non-capturing and capturing lambda expressions and likely is the main reason why capturing lambda expressions are not remembered that way.

So the maximum number of such never-collected instances is equal to the total number of lambda expression in your application, which might be a few hundred or even thousands, but still small compared to the total number of objects the application will ever create. As explained in Function.identity() or t->t, putting a lambda expression into a factory method instead of repeating it in the source code, can reduce the number of instances. But given the rather small total number of objects, that’s rarely a concern. Compare with the number of the already mentioned string literals or the Class objects which already exist in the runtime…

Body:
I am facing some problems with garbage collection while generating an application in java, where I use Stream.map to trim all the elements in the list. The instances of anonymous lambda class exist in the heap dump even though the instance of the enclosing class is 0 as shown in the snap of visual VM.

The LambdaTesting class:

class LambdaTesting {

    protected List<String> values;

    protected LambdaTesting(List<String> values) {
        this.values = values;
    }
    public List<String> modify() {
        return this.values.stream().map(x -> x.trim()).collect(Collectors.toList());
    }
    public List<String> modifyLocal() {
        List<String> localValue = new ArrayList<>();
        localValue.add("Local FOO ");
        localValue.add("Local BAR ");
        return localValue.stream().map(x -> x.trim()).collect(Collectors.toList());
   }
}

The method which creates the instance of LambdaTesting and invokes these methods:

public List<String> testMethods() {
    List<String> test = new ArrayList<>();
    test.add("Global FOO  ");
    test.add("   GLOBAL BAR");
    LambdaTesting lambdaTesting = new LambdaTesting(test);
    lambdaTesting.modifyLocal();
    lambdaTesting.modify();
}

The thread dump was taken after putting a debug point at the next line after testMethods is invoked.

Why are the references to Lambda still present in the heap dump?


问:
organisable file catalog which applies changes to original files in different locations
Is there a solution for having

One unified list/catalog of all files and folders from different external harddrives, which can be used to move and rename items but later when that external drive is connected, The relative files/folders get renamed, copied, moved and removed based on changes made in that catalog.

This is because it is very hard and cumbersome to connect all external HDDs and even if connected all of them have to run for the entire duration of organising every file in all drives.

Basically like an Adobe Lightroom Catalog but for files and folders. We can work on the catalog and changes get applied to originals when HDD is connected.

答:
Never mind stackoverflow, after three days of rigorous search I found the solution to get what I needed done.

With this process anyone can have only the links of all their Terabytes of files in all their Hard-drives, servers, NASs, Cloud etc. in a small ready to access package (hardly MBs) and can be organised, tagged, renamed and cleaned.

Then later once done can replace all the links with original files in their respective organised and modified locations without any hassle and Hard-drive runtime or strain.

I used apple script to tell finder to do the following, but the arriving at the solution took several twists, turns and trial and errors due to my lack of programming fundamentals and how file systems work.

SOLUTION:

Three steps of apple script to

Replicate a directory structure between a source and destination folder with only folders and sub-folders (all). But with the symbolic links of files rather than the files itself.

Converting all the symbolic links to Mac finder type aliases so that they can be processed with apple script.

Replacing all the aliases with the the original files they are pointing to.

The script for each step is also posted with detailed comments along with the screenshots

STEP 0

STEP 1:

```<code>set sourceFolder to choose folder with prompt "Choose Source Folder"
(* To prompt a window with to choose source folder *)
set destinationFolder to choose folder with prompt "Choose Destination Folder"
(* To prompt a window with the title choose destination folder *)
tell application "Finder"

    do shell script "/opt/X11/bin/lndir " & quoted form of POSIX path of sourceFolder & " " & quoted form of POSIX path of destinationFolder & ""
    (* Using shell to execute "lndir" command with its path (as there was a 'command not found' error initially)
        and since we need to use HFS style paths of source and destination directories in the lndir command,
        we are using the quoted form of HFS path i.e. POSIX style (because apple script's POSIX style paths of sourceFolder
        and destinationFolder references used in the beginning lines of script are not used in shell *)

end tell

(* Installing lndir command to terminal is step 1 and it is downloaded using go from github (https://github.com/launchdarkly/go-lndir) *)

(* lndir command whihc is a unix command replicates the directory strucutre of folders and sub-folders between source and destination folders
excluding the files but places the symbolic links of the files instead in the destination directories *)

(* unix lndir man page (http://www.xfree86.org/4.3.0/lndir.1.html) *)
</code>```

STEP 1

STEP 2:

```<code>set sourceFolder to choose folder with prompt "Choose Source Folder"
(* get a prompt windows to choose source folder *)

tell application "Finder"
    set allSymLinks to entire contents of sourceFolder
    (* define a variable allSymlinks so that every file in that folder is scanned for its kind and arrayed *)
    repeat with aSymLink in allSymLinks
        (* repeat the following for every file found (as a variable 'aSymLink') in the array made ('allSymLinks')*)
        if kind of aSymLink is alias then
            (* if the file type is an alias (which is the same for both symbolic link and a mac finder alias) then *)
            set posixPath to POSIX path of aSymLink
            (* set variable to the POSIX path of that file (as it is required for apple script) *)
            move aSymLink to trash
            (* move that symbolic link file to trash *)
            set aliasPath to POSIX file of posixPath as alias
            (* set a variable 'aliasPath' while making a POSIX file (a mac finder alias file)
            with the POSIX path acquired from the symbolic link before we moved it to trash *)
        end if
    end repeat
end tell

(* this script is an intermediary step only because the apple script would't work when we simply write the 'if' condition with kind is alias then...
as though the kind of Symbolic Link is alias, for some reason apple script didn't use it as it would with an original mac finder alias,
so we are converitng it to mac finder type alias using the POSIX path*)

(* Probably the reason might be that apple script can only fetch the original file if the path is of POSIX style *)
</code>```

STEP 2

STEP 3:

```<code>set sourceFolder to choose folder with prompt "Choose Source Folder"
(* get a prompt windows to choose source folder *)

tell application "Finder"
    set allAliases to entire contents of sourceFolder
    (* define a variable allAliases so that every file in that folder is scanned for its kind and arrayed *)
    repeat with anAlias in allAliases
        (* repeat the following for every file found (as a varaible 'anAlias') in the array made ('allAliases')*)
        if class of anAlias is alias file then
            (* if the file's class type is an alias then *)
            set originalFile to original item of anAlias
            (* defining originalFile to the original file the alias is pointing to *)
            set containerFolder to container of anAlias
            (* defining contianerFolder to the folder the alias is pointing to *)
            move anAlias to trash
            (* deleting the alias to trash *)
            move originalFile to containerFolder
            (* moving the original file to the folder *)
        end if
    end repeat
end tell

(* Apple Script didn't work when like in the previous step's script If i wrote 'kind is alias', before I changed them to POSIX style alias,
which apple script seems to work with *)

(* Probably the reason might be that apple script can only fetch the original file if the path is of POSIX style *)
</code>```

STEP 3_a

STEP 3_b.

I wished there was an app for all this

But then I would have never learned all these.

Hoping this will be useful to everyone in need.

Good Day

Body:
Never mind stackoverflow, after three days of rigorous search I found the solution to get what I needed done.

With this process anyone can have only the links of all their Terabytes of files in all their Hard-drives, servers, NASs, Cloud etc. in a small ready to access package (hardly MBs) and can be organised, tagged, renamed and cleaned.

Then later once done can replace all the links with original files in their respective organised and modified locations without any hassle and Hard-drive runtime or strain.

I used apple script to tell finder to do the following, but the arriving at the solution took several twists, turns and trial and errors due to my lack of programming fundamentals and how file systems work.

SOLUTION:

Three steps of apple script to

Replicate a directory structure between a source and destination folder with only folders and sub-folders (all). But with the symbolic links of files rather than the files itself.

Converting all the symbolic links to Mac finder type aliases so that they can be processed with apple script.

Replacing all the aliases with the the original files they are pointing to.

The script for each step is also posted with detailed comments along with the screenshots

STEP 0

STEP 1:

set sourceFolder to choose folder with prompt "Choose Source Folder"
(* To prompt a window with to choose source folder *)
set destinationFolder to choose folder with prompt "Choose Destination Folder"
(* To prompt a window with the title choose destination folder *)
tell application "Finder"

    do shell script "/opt/X11/bin/lndir " & quoted form of POSIX path of sourceFolder & " " & quoted form of POSIX path of destinationFolder & ""
    (* Using shell to execute "lndir" command with its path (as there was a 'command not found' error initially)
        and since we need to use HFS style paths of source and destination directories in the lndir command,
        we are using the quoted form of HFS path i.e. POSIX style (because apple script's POSIX style paths of sourceFolder
        and destinationFolder references used in the beginning lines of script are not used in shell *)

end tell

(* Installing lndir command to terminal is step 1 and it is downloaded using go from github (https://github.com/launchdarkly/go-lndir) *)

(* lndir command whihc is a unix command replicates the directory strucutre of folders and sub-folders between source and destination folders
excluding the files but places the symbolic links of the files instead in the destination directories *)

(* unix lndir man page (http://www.xfree86.org/4.3.0/lndir.1.html) *)

STEP 1

STEP 2:

set sourceFolder to choose folder with prompt "Choose Source Folder"
(* get a prompt windows to choose source folder *)

tell application "Finder"
    set allSymLinks to entire contents of sourceFolder
    (* define a variable allSymlinks so that every file in that folder is scanned for its kind and arrayed *)
    repeat with aSymLink in allSymLinks
        (* repeat the following for every file found (as a variable 'aSymLink') in the array made ('allSymLinks')*)
        if kind of aSymLink is alias then
            (* if the file type is an alias (which is the same for both symbolic link and a mac finder alias) then *)
            set posixPath to POSIX path of aSymLink
            (* set variable to the POSIX path of that file (as it is required for apple script) *)
            move aSymLink to trash
            (* move that symbolic link file to trash *)
            set aliasPath to POSIX file of posixPath as alias
            (* set a variable 'aliasPath' while making a POSIX file (a mac finder alias file)
            with the POSIX path acquired from the symbolic link before we moved it to trash *)
        end if
    end repeat
end tell

(* this script is an intermediary step only because the apple script would't work when we simply write the 'if' condition with kind is alias then...
as though the kind of Symbolic Link is alias, for some reason apple script didn't use it as it would with an original mac finder alias,
so we are converitng it to mac finder type alias using the POSIX path*)

(* Probably the reason might be that apple script can only fetch the original file if the path is of POSIX style *)

STEP 2

STEP 3:

set sourceFolder to choose folder with prompt "Choose Source Folder"
(* get a prompt windows to choose source folder *)

tell application "Finder"
    set allAliases to entire contents of sourceFolder
    (* define a variable allAliases so that every file in that folder is scanned for its kind and arrayed *)
    repeat with anAlias in allAliases
        (* repeat the following for every file found (as a varaible 'anAlias') in the array made ('allAliases')*)
        if class of anAlias is alias file then
            (* if the file's class type is an alias then *)
            set originalFile to original item of anAlias
            (* defining originalFile to the original file the alias is pointing to *)
            set containerFolder to container of anAlias
            (* defining contianerFolder to the folder the alias is pointing to *)
            move anAlias to trash
            (* deleting the alias to trash *)
            move originalFile to containerFolder
            (* moving the original file to the folder *)
        end if
    end repeat
end tell

(* Apple Script didn't work when like in the previous step's script If i wrote 'kind is alias', before I changed them to POSIX style alias,
which apple script seems to work with *)

(* Probably the reason might be that apple script can only fetch the original file if the path is of POSIX style *)

STEP 3_a

STEP 3_b.

I wished there was an app for all this

But then I would have never learned all these.

Hoping this will be useful to everyone in need.

Good Day


问:
Can two actors both required for a usecase be the same person?
I have been presented with the following use case diagram.

The given question was "How many people are required for the Use Case?".

I was taught, that Actors are used to model certain roles in the domain and that a "real" person can take multiple roles.

Going strictly by that definition, a single person with both roles should be enough, but I am not sure whether I am missing something, since intuitively there should be a reason, why there are two actors present.
Can a single "real" person be enough here?

答:
The question seems to assume that actors are people. However this is not the case: an actor can be another system interacting with the subject of your use case.

So strictly speaking, if A and B would be systems, then no people would be required at all.

But even if all actors in the diagram would be  humans: the multiplicity of actors in your diagram is not specified. This creates an ambiguity.  Most people assume it means 1, i.e. 1..1, i.e. a mandatory actor. As Axel explained in the comment, this would be the correct interpretation of the UML specs (it's not written black on white, but some inferences allow to deduct it).  However many people also used to represent an association of a use-case with all primary actors that can possibly be involved without explicitly mentioning a 0..1 optional multiplicity (probably because it was newly introduced with UML 2.5).  Therefore, in practice there is still an ambiguity if both actors are really mandatory.

Finally, as you already rightly analysed and Bruno confirmed, even if both actors would be required it could be the same person.


问:
Is it possible to get beans by class type in Dagger2 similarly to Spring does?
Spring framework allows to get beans by class type in the following way:

```<code>ApplicationContext context;
Class<? extends Foo> fooClass;
Foo fooBean = context.getBean(fooClass);
</code>```

Is there any way to achieve something similar to this with Dagger2?

答:
As far as I know, only if you manually define a map multibinding over the class as a map key.

```<code>@Singleton
public class MyClass {
    @Inject
    public MyClass() {}
}

@Module
public abstract class MyModule {
    @Binds
    @IntoMap
    @ClassKey(MyClass.class)
    public abstract Object bindMyClass(MyClass impl);
}
</code>```

And then

```<code>@Inject
Map<Class<?>, Provider<Object>> providers;

MyClass myClass = (MyClass)providers.get(MyClass.class).get();
</code>```

It'd be possible to restrict the key to ? extends MyClass with custom keys.

```<code>@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface FooKey {
    Class<? extends Foo> value();
}
</code>```

Body:
Spring framework allows to get beans by class type in the following way:

ApplicationContext context;
Class<? extends Foo> fooClass;
Foo fooBean = context.getBean(fooClass);

Is there any way to achieve something similar to this with Dagger2?

Body:
As far as I know, only if you manually define a map multibinding over the class as a map key.

@Singleton
public class MyClass {
    @Inject
    public MyClass() {}
}

@Module
public abstract class MyModule {
    @Binds
    @IntoMap
    @ClassKey(MyClass.class)
    public abstract Object bindMyClass(MyClass impl);
}

And then

@Inject
Map<Class<?>, Provider<Object>> providers;

MyClass myClass = (MyClass)providers.get(MyClass.class).get();

It'd be possible to restrict the key to ? extends MyClass with custom keys.

@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface FooKey {
    Class<? extends Foo> value();
}


问:
How do I grab an index from an array in a HashMap?
I've got a HashMap<Object, String[]> I just want to grab the 0 index position from the String[]. How do I do that?

Can I just do this? mMap.get(position)[0]?

答:
A map is not an array.  It's a dictionary of keys that map to items.  So there is no ordered index in the Map part, there's a lookup key.  This means that a Map has no "next" item.

In the event that you stored a String[] in the map, then you could get the first element of the String array like so:

```<code>String first = ((String[])mMap.get(lookupKey))[0];
</code>```

Since you are using generics, your compiler will make the casting unnecessary, simplifying the answer to

```<code>String first = mMap.get(lookupKey)[0];
</code>```

Note that this is not using the position to access the item stored in the Map, it's using the lookup key.  In addition, there is a casting of the returned Object into a String[] (because we stored a String[] in the map earlier), and then there is a dereferncing of the first ('0') element.

Body:
A map is not an array.  It's a dictionary of keys that map to items.  So there is no ordered index in the Map part, there's a lookup key.  This means that a Map has no "next" item.

In the event that you stored a String[] in the map, then you could get the first element of the String array like so:

String first = ((String[])mMap.get(lookupKey))[0];

Since you are using generics, your compiler will make the casting unnecessary, simplifying the answer to

String first = mMap.get(lookupKey)[0];

Note that this is not using the position to access the item stored in the Map, it's using the lookup key.  In addition, there is a casting of the returned Object into a String[] (because we stored a String[] in the map earlier), and then there is a dereferncing of the first ('0') element.


问:
Is there a function in R that splits a matrix along a margin using a factor or categorical vector?
I am trying to split a matrix in the same way that you might split a data.frame using split. Is there a function that does that? For example, I have matrix m and I am trying to split it into a list of matrices using vector g.

```<code>m <- matrix(rnorm(50), ncol = 5)
groups <- c('A', 'B', 'C')
g <- sample(groups, 10, replace = T)
</code>```

split doesn't seem to work with matrices so we could convert it into a data.frame:

```<code>split(data.frame(m), f = g)
</code>```

This works but I'd like to keep it as a matrix. The following loop works:

```<code>lapply(groups, function(x) m[g == x,])
</code>```

But is there a dedicated function, or a better way?

答:
A couple of solutions have been proposed. Here's a benchmark for a matrix of size 100,000 * 5 being split into 1,000 groups:

```<code>nr <- 1e5
m <- matrix(rnorm(nr * 5), ncol = 5)
groups <- seq_len(1000)
g <- sample(groups, nr, replace = T)

microbenchmark(
  data.frame = split(data.frame(m), f = g),
  split.data.frame = split.data.frame(m, g),
  matrix = lapply(split(m, g), matrix, ncol = ncol(m)),
  lapply1 = lapply(groups, function(x) m[g == x,]),
  lappyl2 = lapply(split(seq_len(nrow(m)), g), function(i) m[i,])
)

Unit: milliseconds
             expr       min        lq      mean    median        uq       max neval
       data.frame 101.50167 119.37017 132.39754 124.60196 133.04204  299.9586   100
 split.data.frame  14.82502  17.43736  24.66659  18.96938  25.33538  119.5009   100
           matrix  18.99796  22.73603  28.14735  25.82694  31.52766  102.1667   100
          lapply1 699.65742 778.61135 817.87159 811.95775 840.05130 1089.5721   100
          lappyl2  15.37083  17.58404  24.13295  19.08363  24.65315  106.8594   100
</code>```

For a small number of groups, lapply1 appears to be the faster method.

Body:
I am trying to split a matrix in the same way that you might split a data.frame using split. Is there a function that does that? For example, I have matrix m and I am trying to split it into a list of matrices using vector g.

m <- matrix(rnorm(50), ncol = 5)
groups <- c('A', 'B', 'C')
g <- sample(groups, 10, replace = T)

split doesn't seem to work with matrices so we could convert it into a data.frame:

split(data.frame(m), f = g)

This works but I'd like to keep it as a matrix. The following loop works:

lapply(groups, function(x) m[g == x,])

But is there a dedicated function, or a better way?

Body:
A couple of solutions have been proposed. Here's a benchmark for a matrix of size 100,000 * 5 being split into 1,000 groups:

nr <- 1e5
m <- matrix(rnorm(nr * 5), ncol = 5)
groups <- seq_len(1000)
g <- sample(groups, nr, replace = T)

microbenchmark(
  data.frame = split(data.frame(m), f = g),
  split.data.frame = split.data.frame(m, g),
  matrix = lapply(split(m, g), matrix, ncol = ncol(m)),
  lapply1 = lapply(groups, function(x) m[g == x,]),
  lappyl2 = lapply(split(seq_len(nrow(m)), g), function(i) m[i,])
)

Unit: milliseconds
             expr       min        lq      mean    median        uq       max neval
       data.frame 101.50167 119.37017 132.39754 124.60196 133.04204  299.9586   100
 split.data.frame  14.82502  17.43736  24.66659  18.96938  25.33538  119.5009   100
           matrix  18.99796  22.73603  28.14735  25.82694  31.52766  102.1667   100
          lapply1 699.65742 778.61135 817.87159 811.95775 840.05130 1089.5721   100
          lappyl2  15.37083  17.58404  24.13295  19.08363  24.65315  106.8594   100

For a small number of groups, lapply1 appears to be the faster method.


问:
How to use TimeDistributed layer for predicting sequences of dynamic length? PYTHON 3
So I am trying to build an LSTM based autoencoder, which I want to use for the time series data. These are spitted up to sequences of different lengths. Input to the model has thus shape [None, None, n_features], where the first None stands for number of samples and the second for time_steps of the sequence. The sequences are processed by LSTM with argument return_sequences = False, coded dimension is then recreated by function RepeatVector and ran through LSTM again. In the end I would like to use the TimeDistributed layer, but how to tell python that the time_steps dimension is dynamic? See my code: </p>

```<code>from keras import backend as K
.... other dependencies .....
input_ae = Input(shape=(None, 2))  # shape: time_steps, n_features
LSTM1 = LSTM(units=128, return_sequences=False)(input_ae)
code = RepeatVector(n=K.shape(input_ae)[1])(LSTM1) # bottleneck layer
LSTM2 = LSTM(units=128, return_sequences=True)(code)
output = TimeDistributed(Dense(units=2))(LSTM2) # ???????  HOW TO ????

# no problem here so far:
model = Model(input_ae, outputs=output)
model.compile(optimizer='adam', loss='mse')
</code>```

答:
this function seems to do the trick

```<code>def repeat(x_inp):

    x, inp = x_inp
    x = tf.expand_dims(x, 1)
    x = tf.repeat(x, [tf.shape(inp)[1]], axis=1)

    return x
</code>```

example

```<code>input_ae = Input(shape=(None, 2))
LSTM1 = LSTM(units=128, return_sequences=False)(input_ae)
code = Lambda(repeat)([LSTM1, input_ae])
LSTM2 = LSTM(units=128, return_sequences=True)(code)
output = TimeDistributed(Dense(units=2))(LSTM2)

model = Model(input_ae, output)
model.compile(optimizer='adam', loss='mse')

X = np.random.uniform(0,1, (100,30,2))
model.fit(X, X, epochs=5)
</code>```

I'm using tf.keras with TF 2.2

Body:
So I am trying to build an LSTM based autoencoder, which I want to use for the time series data. These are spitted up to sequences of different lengths. Input to the model has thus shape [None, None, n_features], where the first None stands for number of samples and the second for time_steps of the sequence. The sequences are processed by LSTM with argument return_sequences = False, coded dimension is then recreated by function RepeatVector and ran through LSTM again. In the end I would like to use the TimeDistributed layer, but how to tell python that the time_steps dimension is dynamic? See my code:

from keras import backend as K
.... other dependencies .....
input_ae = Input(shape=(None, 2))  # shape: time_steps, n_features
LSTM1 = LSTM(units=128, return_sequences=False)(input_ae)
code = RepeatVector(n=K.shape(input_ae)[1])(LSTM1) # bottleneck layer
LSTM2 = LSTM(units=128, return_sequences=True)(code)
output = TimeDistributed(Dense(units=2))(LSTM2) # ???????  HOW TO ????

# no problem here so far:
model = Model(input_ae, outputs=output)
model.compile(optimizer='adam', loss='mse')

Body:
this function seems to do the trick

def repeat(x_inp):

    x, inp = x_inp
    x = tf.expand_dims(x, 1)
    x = tf.repeat(x, [tf.shape(inp)[1]], axis=1)

    return x

example

input_ae = Input(shape=(None, 2))
LSTM1 = LSTM(units=128, return_sequences=False)(input_ae)
code = Lambda(repeat)([LSTM1, input_ae])
LSTM2 = LSTM(units=128, return_sequences=True)(code)
output = TimeDistributed(Dense(units=2))(LSTM2)

model = Model(input_ae, output)
model.compile(optimizer='adam', loss='mse')

X = np.random.uniform(0,1, (100,30,2))
model.fit(X, X, epochs=5)

I'm using tf.keras with TF 2.2


问:
repeat previous row's value then sum if new values are seen from the same row of another column, then repeat current row in Python

Please see the above link for picture, it will be much easier to understand my question once you saw that picture. sorry I cannot directly post pic in this box.

from Column D I want to create a Column E like in the picture. I have spent some hours but could not figure it out. thanks

Body:
Assuming you can read the data from the excel into a dataframe (df) using read_csv or read_excel, this is what you can do:

df['Expected'] = df.groupby('ID')['Amt'].cumsum()

This is how I tested it (ignored the onboard_mth column as it was not needed for testing):

'''
yyyy-mm ID  Amt
2019-08 0   0
2019-09 0   0
2019-10 0   0
2019-11 0   0
2019-12 0   0
2020-01 0   0
2020-02 0   0
2020-03 0   100
2020-04 0   0
2020-05 0   0
2020-06 0   0
2020-07 0   0
2020-08 0   150
2020-09 0   0
2020-10 0   0
2020-11 0   0
2020-12 0   1000
2021-01 0   10000
2021-02 0   0
2021-03 0   0
2021-04 0   0
2021-05 0   0
2021-06 0   0
2021-07 0   0
2019-01 1   0
2019-02 1   0
2019-03 1   0
2019-04 1   0
2019-05 1   0
2019-06 1   0
'''

import pandas as pd

df = pd.read_clipboard()

df['Expected'] = df.groupby('ID')['Amt'].cumsum()

print(df)

Output:

    yyyy-mm  ID    Amt  Expected
0   2019-08   0      0         0
1   2019-09   0      0         0
2   2019-10   0      0         0
3   2019-11   0      0         0
4   2019-12   0      0         0
5   2020-01   0      0         0
6   2020-02   0      0         0
7   2020-03   0    100       100
8   2020-04   0      0       100
9   2020-05   0      0       100
10  2020-06   0      0       100
11  2020-07   0      0       100
12  2020-08   0    150       250
13  2020-09   0      0       250
14  2020-10   0      0       250
15  2020-11   0      0       250
16  2020-12   0   1000      1250
17  2021-01   0  10000     11250
18  2021-02   0      0     11250
19  2021-03   0      0     11250
20  2021-04   0      0     11250
21  2021-05   0      0     11250
22  2021-06   0      0     11250
23  2021-07   0      0     11250
24  2019-01   1      0         0
25  2019-02   1      0         0
26  2019-03   1      0         0
27  2019-04   1      0         0
28  2019-05   1      0         0
29  2019-06   1      0         0