问:
Disable select if there is nothing to show
I made a filter with multiple options. As you can see, there are sometimes no results. I give this back to the visitor as user feedback by saying: no results.

Now I want to make it that if certain combinations are made of filters (certain values), it is only possible to use a filter if there are actually values (so hide a option if there is no value on the page). This way I prevent a user from having to make endless filter combinations to find the right results. Can someone help me?

$("select.filterby").change(function() {
  var filters = $.map($("select.filterby").toArray(), function(e) {
    return $(e).val();
  }).join(".");
  $("div#FilterContainer").find("div.job-offer-card").hide();
  if ($("div#FilterContainer").find("div.job-offer-card." + filters).length) {
    $("div#FilterContainer").find("div.job-offer-card." + filters).show();

  } else {
    $("div#FilterContainer").find("div.noresults").show();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span> View by:</span>

    <label for="location">Location</label>
    <select id="location" class="filterby">
       <option value="all">Show All</option>
       <option value="australia">Australia</option>
       <option value="singapore">Singapore</option>
       <option value="newzealand">New Zealand</option>
       <option value="usa">USA</option>
       <option value="uk">UK</option>
       <option value="vietnam">Vietnam</option>
       <option value="global">Global</option>
       <option value="othercountry">Other</option>
    </select>

    <label for="type">Type</label>
    <select id="type" class="filterby">
       <option value="all">Show All</option>
       <option value="accommodation">Accommodation</option>
       <option value="app">App/Technology</option>
       <option value="business">Business</option>
       <option value="health">Health</option>
       <option value="hospitality">Hospitality</option>
       <option value="education">Education</option>
       <option value="retail">Retail</option>
       <option value="services">Services</option>
       <option value="travel">Travel</option>
    </select>

    <label for="code">Code</label>
    <select id="code" class="filterby">
       <option value="all">Show All</option>
       <option value="001">001</option>
       <option value="002">002</option>
       <option value="003">003</option>
       <option value="004">004</option>
    </select>

<div id="FilterContainer">
  <div class="job-offer-card noresults">
    <p>no results</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel 004">
    <p>1 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all vietnam  travel 003">
    <p>2 all vietnam travel</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>3 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all australia accommodation travel 003">
    <p>4 all australia accommodation travel</p>
  </div>
  <div class="job-offer-card all australia education">
    <p>5 all australia</p>
  </div>
  <div class="job-offer-card all vietnam newzealand usa accommodation">
    <p>6 all vietnam accommodation</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>7 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all vietnam  travel">
    <p>8 all vietnam travel</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>9 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all australia accommodation travel">
    <p>10 all australia accommodation travel</p>
  </div>
  <div class="job-offer-card all australia health 001">
    <p>11 all australia</p>
  </div>
  <div class="job-offer-card all vietnam accommodation 002">
    <p>12 all vietnam accommodation</p>
  </div>
</div></code>```

答:
Solution with dynamic select and dynamic FilterContainer elements showing.

Remark :  the class names 001 ... 004 should be changed to _001 ..._004, because they are not valid class names
see => Which characters are valid in CSS class names/selectors?

Or it could be more clear to use dataset => https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

const
    Selects = document.querySelectorAll('select')                      // 3 selects in this story
  , mainFC  = document.querySelector('#FilterContainer')               // result part
  , all_FC  = document.querySelectorAll('#FilterContainer div')        // details result part
  , zeroFC  = document.querySelector('#FilterContainer div.noresults') // when there is nothing
;

var PossibleOptions = new Set();  // set for all options feet in #FilterContainer div

all_FC.forEach(d=>{d.className.split(' ').forEach(c=>{PossibleOptions.add(c)})}) // first attempt

// for the start : set only options availables + onchange listener
Selects.forEach(s=>{                                // for each Select
  s.querySelectorAll('option').forEach(o=>{         // and for each option, in
    o.disabled = !PossibleOptions.has(o.value);     // is there 1 a result div using this class ?.
    if (o.value==='all') o.selected=true;           // start the select at position for all
  })
  s.onchange = SelecChange;                         // give listener 'change' to function named 'SelecChange'
})

function SelecChange(e)              // for every select action...
{
  //  e.target.value
  let                               // prepare ;
    List_Selects = []               // - array for all selects value
  , no_FC        = true             // - flag to know if there is no FS as result
  ;
  PossibleOptions.clear();          // new start

  Selects.forEach(s=>{              // make List_Selects
    if(s.value!='all')              // everything is nothing
    { List_Selects.push(s.value) }  // add select value
  });

  all_FC.forEach(d=>{               // for each FilterContainer
 as 'd'
    let ok = true;
    for(let cLS of List_Selects)    // for each option choosed in a select
    { ok = ok && d.classList.contains(cLS) } // check if in class list of the

    if (ok){
      d.classList.remove('noShow');   // so this div will be shown
      d.className.split(' ').forEach(c=>{ PossibleOptions.add(c) });
                                      // and all the div class item be added on the set
      no_FC = false;                  // one is enough
    }
    else {
      d.classList.add('noShow');    // soory guy, your not in the team for this time
    }
  })

  // now we have disable all options witch as no reality in FilterContainer
  Selects.forEach(s=>{
    s.querySelectorAll('option').forEach(o=>{
      o.disabled = !PossibleOptions.has(o.value);   // PossibleOptions know
    })
  })

  // last things: is there results ?
  if (no_FC) { zeroFC.classList.remove('noShow') }  // there is none
  else       { zeroFC.classList.add('noShow')    }  // there is one (or more)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.noShow { display: none }</code>```

 View by:

Location
<select id="location" class="filterby">
    <option value="all">Show All</option>
    <option value="australia">Australia</option>
    <option value="singapore">Singapore</option>
    <option value="newzealand">New Zealand</option>
    <option value="usa">USA</option>
    <option value="uk">UK</option>
    <option value="vietnam">Vietnam</option>
    <option value="global">Global</option>
    <option value="othercountry">Other</option>
</select>

Type
<select id="type" class="filterby">
    <option value="all">Show All</option>
    <option value="accommodation">Accommodation</option>
    <option value="app">App/Technology</option>
    <option value="business">Business</option>
    <option value="health">Health</option>
    <option value="hospitality">Hospitality</option>
    <option value="education">Education</option>
    <option value="retail">Retail</option>
    <option value="services">Services</option>
    <option value="travel">Travel</option>
</select>

Code
<select id="code" class="filterby">
    <option value="all">Show All</option>
    <option value="001">001</option>
    <option value="002">002</option>
    <option value="003">003</option>
    <option value="004">004</option>
</select>

no results

1 all vietnam accommodation travel _004

2 all vietnam travel _003

3 all vietnam accommodation travel

4 all australia accommodation travel 003

5 all australia education

6 all vietnam newzealand usa accommodation

7 all vietnam accommodation travel

8 all vietnam travel

9 all vietnam accommodation travel

10 all australia accommodation travel

11 all australia health _001

12 all vietnam accommodation _002

```
</div>
</div>
</p>

<p>Same Solution but using <strong>data-options</strong><br>
=> <code><div class="job-offer-card" data-options="all vietnam accommodation 002"></code><br>
( JS =><em>element.dataset.options</em>)</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const
    Selects = document.querySelectorAll('select')                      // 3 selects in this story
  , mainFC  = document.querySelector('#FilterContainer')               // result part
  , all_FC  = document.querySelectorAll('#FilterContainer div')        // details result part
  , zeroFC  = document.querySelector('#FilterContainer div.noresults') // when there is nothing
;

var PossibleOptions = new Set();  // set for all options feet in #FilterContainer div

all_FC.forEach(d=>{ d.dataset.options.split(' ').forEach(c=>{PossibleOptions.add(c)})}) // first attempt

// for the start : set only options availables + onchange listener
Selects.forEach(s=>{                                // for each Select
  s.querySelectorAll('option').forEach(o=>{         // and for each option, in
    o.disabled = !PossibleOptions.has(o.value);     // is there 1 a result div using this class ?.
    if (o.value==='all') o.selected=true;           // start the select at position for all
  })
  s.onchange = SelecChange;                         // give listener 'change' to function named 'SelecChange'
})

function SelecChange(e)              // for every select action...
{
  //  e.target.value
  let                               // prepare ;
    List_Selects = []               // - array for all selects value
  , no_FC        = true             // - flag to know if there is no FS as result
  ;
  PossibleOptions.clear();          // new start

  Selects.forEach(s=>{              // make List_Selects
    if(s.value!='all')              // everything is nothing
    { List_Selects.push(s.value) }  // add select value
  });

  all_FC.forEach(d=>{               // for each FilterContainer <div> as 'd'
    let
      ok  = true,
      opt = d.dataset.options.split(' ');

    for(let cLS of List_Selects)    // for each option choosed in a select
    { ok = ok && opt.includes(cLS) } // check if in class list of the <div>

    if (ok){
      opt.forEach(c=>{ PossibleOptions.add(c) }); // all the data-options item  be added on the set
      d.classList.remove('noShow');              // so this div will be shown
      no_FC = false;                            // one is enough
    }
    else {
      d.classList.add('noShow');    // soory guy, your not in the team for this time
    }
  })

  // now we have disable all options witch as no reality in FilterContainer
  Selects.forEach(s=>{
    s.querySelectorAll('option').forEach(o=>{
      o.disabled = !PossibleOptions.has(o.value);   // PossibleOptions know
    })
  })

  // last things: is there results ?
  if (no_FC) { zeroFC.classList.remove('noShow') }  // there is none
  else       { zeroFC.classList.add('noShow')    }  // there is one (or more)
}</code>```

.noShow { display: none }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="location">Location</label>
<select id="location" class="filterby">
    <option value="all">Show All</option>
    <option value="australia">Australia</option>
    <option value="singapore">Singapore</option>
    <option value="newzealand">New Zealand</option>
    <option value="usa">USA</option>
    <option value="uk">UK</option>
    <option value="vietnam">Vietnam</option>
    <option value="global">Global</option>
    <option value="othercountry">Other</option>
</select>

<label for="type">Type</label>
<select id="type" class="filterby">
    <option value="all">Show All</option>
    <option value="accommodation">Accommodation</option>
    <option value="app">App/Technology</option>
    <option value="business">Business</option>
    <option value="health">Health</option>
    <option value="hospitality">Hospitality</option>
    <option value="education">Education</option>
    <option value="retail">Retail</option>
    <option value="services">Services</option>
    <option value="travel">Travel</option>
</select>

<label for="code">Code</label>
<select id="code" class="filterby">
    <option value="all">Show All</option>
    <option value="001">001</option>
    <option value="002">002</option>
    <option value="003">003</option>
    <option value="004">004</option>
</select>
<hr>

<div id="FilterContainer">
  <div class="job-offer-card noresults noShow" data-options="all">
    <p>no results</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation travel 004">
    <p>1 all vietnam accommodation travel _004</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam travel _003">
    <p>2 all vietnam travel _003</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation travel">
    <p>3 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card" data-options="all australia accommodation travel 003">
    <p>4 all australia accommodation travel 003</p>
  </div>
  <div class="job-offer-card" data-options="all australia education">
    <p>5 all australia education</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam newzealand usa accommodation">
    <p>6 all vietnam newzealand usa accommodation</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation travel">
    <p>7 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam travel">
    <p>8 all vietnam travel</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation travel">
    <p>9 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card" data-options="all australia accommodation travel">
    <p>10 all australia accommodation travel</p>
  </div>
  <div class="job-offer-card" data-options="all australia health 001">
    <p>11 all australia health _001</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation 002">
    <p>12 all vietnam accommodation _002</p>
  </div>
</div></code>```

Body:
I made a filter with multiple options. As you can see, there are sometimes no results. I give this back to the visitor as user feedback by saying: no results.

Now I want to make it that if certain combinations are made of filters (certain values), it is only possible to use a filter if there are actually values (so hide a option if there is no value on the page). This way I prevent a user from having to make endless filter combinations to find the right results. Can someone help me?

$("select.filterby").change(function() {
  var filters = $.map($("select.filterby").toArray(), function(e) {
    return $(e).val();
  }).join(".");
  $("div#FilterContainer").find("div.job-offer-card").hide();
  if ($("div#FilterContainer").find("div.job-offer-card." + filters).length) {
    $("div#FilterContainer").find("div.job-offer-card." + filters).show();

  } else {
    $("div#FilterContainer").find("div.noresults").show();
  }
});

 View by:

    Location
    <select id="location" class="filterby">
       <option value="all">Show All</option>
       <option value="australia">Australia</option>
       <option value="singapore">Singapore</option>
       <option value="newzealand">New Zealand</option>
       <option value="usa">USA</option>
       <option value="uk">UK</option>
       <option value="vietnam">Vietnam</option>
       <option value="global">Global</option>
       <option value="othercountry">Other</option>
    </select>

    Type
    <select id="type" class="filterby">
       <option value="all">Show All</option>
       <option value="accommodation">Accommodation</option>
       <option value="app">App/Technology</option>
       <option value="business">Business</option>
       <option value="health">Health</option>
       <option value="hospitality">Hospitality</option>
       <option value="education">Education</option>
       <option value="retail">Retail</option>
       <option value="services">Services</option>
       <option value="travel">Travel</option>
    </select>

    Code
    <select id="code" class="filterby">
       <option value="all">Show All</option>
       <option value="001">001</option>
       <option value="002">002</option>
       <option value="003">003</option>
       <option value="004">004</option>
    </select>

no results

1 all vietnam accommodation travel

2 all vietnam travel

3 all vietnam accommodation travel

4 all australia accommodation travel

5 all australia

6 all vietnam accommodation

7 all vietnam accommodation travel

8 all vietnam travel

9 all vietnam accommodation travel

10 all australia accommodation travel

11 all australia

12 all vietnam accommodation

Body:
Solution with dynamic select and dynamic FilterContainer elements showing.

Remark :  the class names 001 ... 004 should be changed to _001 ..._004, because they are not valid class names
see => Which characters are valid in CSS class names/selectors?

Or it could be more clear to use dataset => https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

const
    Selects = document.querySelectorAll('select')                      // 3 selects in this story
  , mainFC  = document.querySelector('#FilterContainer')               // result part
  , all_FC  = document.querySelectorAll('#FilterContainer div')        // details result part
  , zeroFC  = document.querySelector('#FilterContainer div.noresults') // when there is nothing
;

var PossibleOptions = new Set();  // set for all options feet in #FilterContainer div

all_FC.forEach(d=>{d.className.split(' ').forEach(c=>{PossibleOptions.add(c)})}) // first attempt

// for the start : set only options availables + onchange listener
Selects.forEach(s=>{                                // for each Select
  s.querySelectorAll('option').forEach(o=>{         // and for each option, in
    o.disabled = !PossibleOptions.has(o.value);     // is there 1 a result div using this class ?.
    if (o.value==='all') o.selected=true;           // start the select at position for all
  })
  s.onchange = SelecChange;                         // give listener 'change' to function named 'SelecChange'
})

function SelecChange(e)              // for every select action...
{
  //  e.target.value
  let                               // prepare ;
    List_Selects = []               // - array for all selects value
  , no_FC        = true             // - flag to know if there is no FS as result
  ;
  PossibleOptions.clear();          // new start

  Selects.forEach(s=>{              // make List_Selects
    if(s.value!='all')              // everything is nothing
    { List_Selects.push(s.value) }  // add select value
  });

  all_FC.forEach(d=>{               // for each FilterContainer <div> as 'd'
    let ok = true;
    for(let cLS of List_Selects)    // for each option choosed in a select
    { ok = ok && d.classList.contains(cLS) } // check if in class list of the <div>

    if (ok){
      d.classList.remove('noShow');   // so this div will be shown
      d.className.split(' ').forEach(c=>{ PossibleOptions.add(c) });
                                      // and all the div class item be added on the set
      no_FC = false;                  // one is enough
    }
    else {
      d.classList.add('noShow');    // soory guy, your not in the team for this time
    }
  })

  // now we have disable all options witch as no reality in FilterContainer
  Selects.forEach(s=>{
    s.querySelectorAll('option').forEach(o=>{
      o.disabled = !PossibleOptions.has(o.value);   // PossibleOptions know
    })
  })

  // last things: is there results ?
  if (no_FC) { zeroFC.classList.remove('noShow') }  // there is none
  else       { zeroFC.classList.add('noShow')    }  // there is one (or more)
}

.noShow { display: none }

<h4> View by:</h4>

<label for="location">Location</label>
<select id="location" class="filterby">
    <option value="all">Show All</option>
    <option value="australia">Australia</option>
    <option value="singapore">Singapore</option>
    <option value="newzealand">New Zealand</option>
    <option value="usa">USA</option>
    <option value="uk">UK</option>
    <option value="vietnam">Vietnam</option>
    <option value="global">Global</option>
    <option value="othercountry">Other</option>
</select>

<label for="type">Type</label>
<select id="type" class="filterby">
    <option value="all">Show All</option>
    <option value="accommodation">Accommodation</option>
    <option value="app">App/Technology</option>
    <option value="business">Business</option>
    <option value="health">Health</option>
    <option value="hospitality">Hospitality</option>
    <option value="education">Education</option>
    <option value="retail">Retail</option>
    <option value="services">Services</option>
    <option value="travel">Travel</option>
</select>

<label for="code">Code</label>
<select id="code" class="filterby">
    <option value="all">Show All</option>
    <option value="001">001</option>
    <option value="002">002</option>
    <option value="003">003</option>
    <option value="004">004</option>
</select>
<hr>

<div id="FilterContainer">
  <div class="job-offer-card noresults noShow">
    <p>no results</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel 004">
    <p>1 all vietnam accommodation travel _004</p>
  </div>
  <div class="job-offer-card all vietnam travel _003">
    <p>2 all vietnam travel _003</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>3 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all australia accommodation travel 003">
    <p>4 all australia accommodation travel 003</p>
  </div>
  <div class="job-offer-card all australia education">
    <p>5 all australia education</p>
  </div>
  <div class="job-offer-card all vietnam newzealand usa accommodation">
    <p>6 all vietnam newzealand usa accommodation</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>7 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all vietnam travel">
    <p>8 all vietnam travel</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>9 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all australia accommodation travel">
    <p>10 all australia accommodation travel</p>
  </div>
  <div class="job-offer-card all australia health 001">
    <p>11 all australia health _001</p>
  </div>
  <div class="job-offer-card all vietnam accommodation 002">
    <p>12 all vietnam accommodation _002</p>
  </div>
</div>

Same Solution but using data-options

=> <div class="job-offer-card" data-options="all vietnam accommodation 002">

( JS =>element.dataset.options)

const
    Selects = document.querySelectorAll('select')                      // 3 selects in this story
  , mainFC  = document.querySelector('#FilterContainer')               // result part
  , all_FC  = document.querySelectorAll('#FilterContainer div')        // details result part
  , zeroFC  = document.querySelector('#FilterContainer div.noresults') // when there is nothing
;

var PossibleOptions = new Set();  // set for all options feet in #FilterContainer div

all_FC.forEach(d=>{ d.dataset.options.split(' ').forEach(c=>{PossibleOptions.add(c)})}) // first attempt

// for the start : set only options availables + onchange listener
Selects.forEach(s=>{                                // for each Select
  s.querySelectorAll('option').forEach(o=>{         // and for each option, in
    o.disabled = !PossibleOptions.has(o.value);     // is there 1 a result div using this class ?.
    if (o.value==='all') o.selected=true;           // start the select at position for all
  })
  s.onchange = SelecChange;                         // give listener 'change' to function named 'SelecChange'
})

function SelecChange(e)              // for every select action...
{
  //  e.target.value
  let                               // prepare ;
    List_Selects = []               // - array for all selects value
  , no_FC        = true             // - flag to know if there is no FS as result
  ;
  PossibleOptions.clear();          // new start

  Selects.forEach(s=>{              // make List_Selects
    if(s.value!='all')              // everything is nothing
    { List_Selects.push(s.value) }  // add select value
  });

  all_FC.forEach(d=>{               // for each FilterContainer <div> as 'd'
    let
      ok  = true,
      opt = d.dataset.options.split(' ');

    for(let cLS of List_Selects)    // for each option choosed in a select
    { ok = ok && opt.includes(cLS) } // check if in class list of the <div>

    if (ok){
      opt.forEach(c=>{ PossibleOptions.add(c) }); // all the data-options item  be added on the set
      d.classList.remove('noShow');              // so this div will be shown
      no_FC = false;                            // one is enough
    }
    else {
      d.classList.add('noShow');    // soory guy, your not in the team for this time
    }
  })

  // now we have disable all options witch as no reality in FilterContainer
  Selects.forEach(s=>{
    s.querySelectorAll('option').forEach(o=>{
      o.disabled = !PossibleOptions.has(o.value);   // PossibleOptions know
    })
  })

  // last things: is there results ?
  if (no_FC) { zeroFC.classList.remove('noShow') }  // there is none
  else       { zeroFC.classList.add('noShow')    }  // there is one (or more)
}

.noShow { display: none }

<label for="location">Location</label>
<select id="location" class="filterby">
    <option value="all">Show All</option>
    <option value="australia">Australia</option>
    <option value="singapore">Singapore</option>
    <option value="newzealand">New Zealand</option>
    <option value="usa">USA</option>
    <option value="uk">UK</option>
    <option value="vietnam">Vietnam</option>
    <option value="global">Global</option>
    <option value="othercountry">Other</option>
</select>

<label for="type">Type</label>
<select id="type" class="filterby">
    <option value="all">Show All</option>
    <option value="accommodation">Accommodation</option>
    <option value="app">App/Technology</option>
    <option value="business">Business</option>
    <option value="health">Health</option>
    <option value="hospitality">Hospitality</option>
    <option value="education">Education</option>
    <option value="retail">Retail</option>
    <option value="services">Services</option>
    <option value="travel">Travel</option>
</select>

<label for="code">Code</label>
<select id="code" class="filterby">
    <option value="all">Show All</option>
    <option value="001">001</option>
    <option value="002">002</option>
    <option value="003">003</option>
    <option value="004">004</option>
</select>
<hr>

<div id="FilterContainer">
  <div class="job-offer-card noresults noShow" data-options="all">
    <p>no results</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation travel 004">
    <p>1 all vietnam accommodation travel _004</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam travel _003">
    <p>2 all vietnam travel _003</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation travel">
    <p>3 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card" data-options="all australia accommodation travel 003">
    <p>4 all australia accommodation travel 003</p>
  </div>
  <div class="job-offer-card" data-options="all australia education">
    <p>5 all australia education</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam newzealand usa accommodation">
    <p>6 all vietnam newzealand usa accommodation</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation travel">
    <p>7 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam travel">
    <p>8 all vietnam travel</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation travel">
    <p>9 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card" data-options="all australia accommodation travel">
    <p>10 all australia accommodation travel</p>
  </div>
  <div class="job-offer-card" data-options="all australia health 001">
    <p>11 all australia health _001</p>
  </div>
  <div class="job-offer-card" data-options="all vietnam accommodation 002">
    <p>12 all vietnam accommodation _002</p>
  </div>
</div>


来源: stackexchange

问:
Batch move lines in a text file based on text
I am receiving a datalogger file that has a one file output. I want to move lines based on a string to multiple text files.

I can get it working with a batch file below but i want to automate it as the text file that the data logger sends always changes its name (with a date)

```<code>findstr TiltA HMA_input180529.txt >>output.txt
</code>```

example input
csv (HMA_input180529.txt)

```<code>2019-05-29 08:03:48,TiltA,3.420,19.9,0.5017,0.6903
2019-05-29 09:03:48,TiltB,3.420,19.9,0.3017,0.6903
</code>```

example output csv (TiltA.txt)

```<code>2019-05-29 08:03:48,TiltA,3.420,19.9,0.5017,0.6903
</code>```

I dont know where to start in calling all *.* files and then saving the new text file to be named the same as the string that was found eg TiltA

答:
You can do this pretty easily with a FOR /F loop.

```<code>for %%f in (*.txt) do (
    for /f "tokens=1-6 delims=," %%i in (%%f) do echo %%i,%%j,%%k,%%l,%%m,%%n>"%%j.txt"
)
</code>```

This assumes the format of token1,TITLE,token3,token4,token5,token6 stays the same.

OR

```<code>for %%f in (*.txt) do (
    for /f "tokens=2 delims=," %%i in (%%f) do type %%f | find /i "%%i">"%%i.txt"
)
</code>```

This assumes the format of token1,TITLE,* stays the same.

ContentLicense: CC BY-SA 4.0

Body:
I am receiving a datalogger file that has a one file output. I want to move lines based on a string to multiple text files.

I can get it working with a batch file below but i want to automate it as the text file that the data logger sends always changes its name (with a date)

findstr TiltA HMA_input180529.txt >>output.txt

example input
csv (HMA_input180529.txt)

2019-05-29 08:03:48,TiltA,3.420,19.9,0.5017,0.6903
2019-05-29 09:03:48,TiltB,3.420,19.9,0.3017,0.6903

example output csv (TiltA.txt)

2019-05-29 08:03:48,TiltA,3.420,19.9,0.5017,0.6903

I dont know where to start in calling all *.* files and then saving the new text file to be named the same as the string that was found eg TiltA

Body:
You can do this pretty easily with a FOR /F loop.

for %%f in (*.txt) do (
    for /f "tokens=1-6 delims=," %%i in (%%f) do echo %%i,%%j,%%k,%%l,%%m,%%n>"%%j.txt"
)

This assumes the format of token1,TITLE,token3,token4,token5,token6 stays the same.

OR

for %%f in (*.txt) do (
    for /f "tokens=2 delims=," %%i in (%%f) do type %%f | find /i "%%i">"%%i.txt"
)

This assumes the format of token1,TITLE,* stays the same.


问:
How can I get the return value from an `setTimeout` callback?
consider this code

```<code>const obj = {
  generate(num) {
    return Math.random()*num;
  },
  add(a,b) {
    return this.generate(a) + this.generate(b)
  }
};

function delay(func, ms) {
  function wrapper() {
    setTimeout(() => func.apply(this, arguments), ms)  // How can I get the return value from the original function?
  }

  return wrapper;
}

// create wrappers
obj.f1000 = delay(obj.add, 1000);
obj.f1500 = delay(obj.add, 1500);

obj.f1000(1,3);
obj.f1500(2,5);
</code>```

I made a wrapper to delay the method call for add()
Is there a way to retrieve the value from the callback inside setTimeout, i.e. the this.generate(a) + this.generate(b) from add()?

答:
Since setTimeout will execute the callback asynchronously, you will need to work with Promises (ES6) or async/await (ES7).

You can polyfill it for ES5.

Example with promises

const obj = {
  generate(num) {
    return Math.random() * num;
  },
  add(a, b) {
    return this.generate(a) + this.generate(b);
  }
};

// create promise
function timedPromise(func, args, ms) {
  return new Promise(resolve => {
    setTimeout(() => {
      // spread operator
      resolve(func.apply(null, args));
    }, ms);
  });
}

// create a function that creates a promise
function delay(func, ms) {
  function wrapper() {
    return timedPromise(func, arguments, ms);
  }

  return wrapper;
}

// obj.add uses this.generate, but 'this' was not bound to obj
obj.f1000 = delay(obj.add.bind(obj), 1000);
obj.f1500 = delay(obj.add.bind(obj), 1500);

console.info('calculating...')
const result1 = obj.f1000(1, 3);
const result2 = obj.f1500(2, 5);

result1.then(result => {
  console.info('f1000', result);
})

result2.then(result => {
  console.info('f1500', result);
})```

In your wrapper function, you bound this to the callable function. But since this was not defined in that specific scope, you would have run into some troubles. I bound the obj to the add function while passing it to delay().

Body:
consider this code

const obj = {
  generate(num) {
    return Math.random()*num;
  },
  add(a,b) {
    return this.generate(a) + this.generate(b)
  }
};

function delay(func, ms) {
  function wrapper() {
    setTimeout(() => func.apply(this, arguments), ms)  // How can I get the return value from the original function?
  }

  return wrapper;
}

// create wrappers
obj.f1000 = delay(obj.add, 1000);
obj.f1500 = delay(obj.add, 1500);

obj.f1000(1,3);
obj.f1500(2,5);

I made a wrapper to delay the method call for add()
Is there a way to retrieve the value from the callback inside setTimeout, i.e. the this.generate(a) + this.generate(b) from add()?

Body:
Since setTimeout will execute the callback asynchronously, you will need to work with Promises (ES6) or async/await (ES7).

You can polyfill it for ES5.

Example with promises

const obj = {
  generate(num) {
    return Math.random() * num;
  },
  add(a, b) {
    return this.generate(a) + this.generate(b);
  }
};

// create promise
function timedPromise(func, args, ms) {
  return new Promise(resolve => {
    setTimeout(() => {
      // spread operator
      resolve(func.apply(null, args));
    }, ms);
  });
}

// create a function that creates a promise
function delay(func, ms) {
  function wrapper() {
    return timedPromise(func, arguments, ms);
  }

  return wrapper;
}

// obj.add uses this.generate, but 'this' was not bound to obj
obj.f1000 = delay(obj.add.bind(obj), 1000);
obj.f1500 = delay(obj.add.bind(obj), 1500);

console.info('calculating...')
const result1 = obj.f1000(1, 3);
const result2 = obj.f1500(2, 5);

result1.then(result => {
  console.info('f1000', result);
})

result2.then(result => {
  console.info('f1500', result);
})

In your wrapper function, you bound this to the callable function. But since this was not defined in that specific scope, you would have run into some troubles. I bound the obj to the add function while passing it to delay().


问:
How to fix Uncaught TypeError in Phaser 3 for Game Development
I'm following a space shooter tutorial for a game I'm developing as I learn Javascript. The tutorial puts many of the classes in the same file stacked on top of each other, but I've read this isn't a good practice and all Classes should have their own separate file. The link for the tutorial is here...

https://yorkcs.com/2019/02/08/build-a-space-shooter-with-phaser-3-4/

I've made sure everything is typed properly, but whenever I run it in Chrome (and I've cleared my cache too), I get an error message that says...

Uncaught TypeError: Cannot read property 'getFirstTick' of null

It's throwing the error on line 21 of enemies.js for this line of code...

```<code>this.play( 'basicenemy' );
</code>```

I've tried several things because I've gotten different errors. I think I've made the mistake of following separate tutorials. I've tried adding the images to the files themselves instead of the sceneMain.js file where the first level is because at one point it was telling me that play() was undefined.

entities.js

```<code>class Entities extends Phaser.GameObjects.Sprite
{
  constructor(scene, x, y, key, type)
  {
    super(scene, x, y, key, type);
    this.scene = scene;
    this.scene.add.existing(this);
    this.scene.physics.world.enableBody(this, 0);
    this.setData("type", type);
    this.setData("isDead", false);
  }
}
</code>```

enemies.js

```<code>class BasicEnemy extends Entities
{
  constructor(scene, x, y)
  {
    super(scene, x, y, 'basicenemy', 'BasicEnemy');
    this.body.velocity.y = Phaser.Math.Between(50, 100);
    this.shootTimer = this.scene.time.addEvent({
        delay: 1000,
        callback: function() {
          var laser = new EnemyLaser(
            this.scene,
            this.x,
            this.y
          );
          laser.setScale(this.scaleX);
          this.scene.enemyLasers.add(laser);
        },
        callbackScope: this,
        loop: true
      });
    this.play( 'basicenemy' );
  }
}
</code>```

sceneMain.js

```<code>//The Bullet Group
    this.basicEnemy = this.add.group();
    this.enemyLasers = this.add.group();
    this.playerLasers = this.add.group();

    this.time.addEvent({
        delay: 100,
        callback: function() {
          var enemy = new BasicEnemy(
            this,
            Phaser.Math.Between(0, this.game.config.width),
            0
          );
          this.basicEnemy.add(enemy);
        },
        callbackScope: this,
        loop: true
      });
</code>```

In sceneMain.js I'm trying to get enemies to spawn from the top of the screen with this line...

```<code>this.basicEnemy.add(enemy);
</code>```

Any help would be much appreciated.

答:
```<code>class SceneMain extends Phaser.Scene
{
constructor()
{
    super('SceneMain');

}
preload()
//loads our images and sounds
{
    //this.load.image( "playership","images/blueship.png" );
    this.load.image( 'spaceback4','images/spaceback4.png' );
    this.load.spritesheet( 'blueships', 'images/blueships.png', { frameWidth: 73, frameHeight: 80 });
    this.load.spritesheet( 'blueshot', 'images/blueshipshot.png', { frameWidth: 20, frameHeight: 55 });
    this.load.spritesheet( 'basicenemy', 'images/basicenemy.png', { frameWidth: 65, frameHeight: 80 });

    this.load.audio( 'explosion', 'audio/explosion.mp3' );
    this.load.audio( 'laser', 'audio/lasershot.mp3' );
    this.load.audio( 'enemylaser', 'audio/enemylaser.mp3' );

}
create()
//define our objects
{
    //The Starfield Background
    this.starfield = this.add.tileSprite( 0, 0, 1080, 900, "spaceback4" );

    //The Grid System
    var gridConfig={ row:5, cols:5, scene:this };
    var alignGrid = new AlignGrid( gridConfig );
    //alignGrid.showNumbers();

    //The Score
    this.sb = new ScoreBox( {scene:this} );
    alignGrid.placeAtIndex( 2, this.sb );
    model.score = 0;

    //The Player Ship
    this.playerShip = this.physics.add.sprite( 0,0, 'blueships' );
    this.anims.create({
        key: 'fly',
        frames: this.anims.generateFrameNames( 'blueships', {start: 0, end: 9 }),
        frameRate: 16,
        repeat: -1
    });
    this.playerShip.play( 'fly', this );
    alignGrid.placeAtIndex( 22, this.playerShip );
    this.playerShip.setCollideWorldBounds( true );

    //The Enemy Ships
    this.basicEnemy = this.physics.add.sprite( 0,0, 'basicenemy' )
    this.basicEnemy2 = this.physics.add.sprite( 0,0, 'basicenemy' )
    this.basicEnemy3 = this.physics.add.sprite( 0,0, 'basicenemy' )

    this.anims.create({
        key: 'badfly',
        frames: this.anims.generateFrameNames( 'basicenemy', {start: 0, end: 9 }),
        frameRate: 16,
        repeat: -1
    });
    this.basicEnemy.play( 'badfly', this );
    this.basicEnemy2.play( 'badfly', this );
    this.basicEnemy3.play( 'badfly', this );
    alignGrid.placeAtIndex( 6, this.basicEnemy );
    alignGrid.placeAtIndex( 7, this.basicEnemy2 );
    alignGrid.placeAtIndex( 8, this.basicEnemy3 );

    //The Bullet Group
    this.basicEnemy = this.add.group();
    this.enemyLasers = this.add.group();
    this.playerLasers = this.add.group();

    this.time.addEvent({
        delay: 100,
        callback: function() {
          var enemy = new BasicEnemy(
            this,
            Phaser.Math.Between(0, this.game.config.width),
            0
          );
          this.basicEnemy.add(enemy);
        },
        callbackScope: this,
        loop: true
      });

    //The Audio
    this.sfx = {
        laser: [
          this.sound.add( 'laser' ),
          this.sound.add( 'enemylaser' )
        ],
        explosion: this.sound.add( 'explosion' )
      };

    //The Starfield
    alignGrid.placeAtIndex( 12, this.starfield );

    //Controls
    this.cursors = this.input.keyboard.createCursorKeys();
    this.fireButton = this.input.keyboard.addKey(Phaser.Input.Keyboard.SPACE);

}
update()
//constant running loops
{
    //Scroll the starfield
    this.starfield.tilePositionY += -1.5;

    //Player Movement
    this.playerShip.setAccelerationX( 0 );
    this.playerShip.setDragX( 300 );

    if (this.cursors.left.isDown)
    {
        this.playerShip.setAccelerationX (-300 );
    }
    if (this.cursors.right.isDown)
    {
        this.playerShip.setAccelerationX ( 300 );
    }

    //  Fire bullet
    /*if (this.fireButton.isDown || this.input.activePointer.isDown)
    {
        this.fireBullet();
    }*/

}
</code>```

Body:
I'm following a space shooter tutorial for a game I'm developing as I learn Javascript. The tutorial puts many of the classes in the same file stacked on top of each other, but I've read this isn't a good practice and all Classes should have their own separate file. The link for the tutorial is here...

https://yorkcs.com/2019/02/08/build-a-space-shooter-with-phaser-3-4/

I've made sure everything is typed properly, but whenever I run it in Chrome (and I've cleared my cache too), I get an error message that says...

Uncaught TypeError: Cannot read property 'getFirstTick' of null

It's throwing the error on line 21 of enemies.js for this line of code...

this.play( 'basicenemy' );

I've tried several things because I've gotten different errors. I think I've made the mistake of following separate tutorials. I've tried adding the images to the files themselves instead of the sceneMain.js file where the first level is because at one point it was telling me that play() was undefined.

entities.js

class Entities extends Phaser.GameObjects.Sprite
{
  constructor(scene, x, y, key, type)
  {
    super(scene, x, y, key, type);
    this.scene = scene;
    this.scene.add.existing(this);
    this.scene.physics.world.enableBody(this, 0);
    this.setData("type", type);
    this.setData("isDead", false);
  }
}

enemies.js

class BasicEnemy extends Entities
{
  constructor(scene, x, y)
  {
    super(scene, x, y, 'basicenemy', 'BasicEnemy');
    this.body.velocity.y = Phaser.Math.Between(50, 100);
    this.shootTimer = this.scene.time.addEvent({
        delay: 1000,
        callback: function() {
          var laser = new EnemyLaser(
            this.scene,
            this.x,
            this.y
          );
          laser.setScale(this.scaleX);
          this.scene.enemyLasers.add(laser);
        },
        callbackScope: this,
        loop: true
      });
    this.play( 'basicenemy' );
  }
}

sceneMain.js

//The Bullet Group
    this.basicEnemy = this.add.group();
    this.enemyLasers = this.add.group();
    this.playerLasers = this.add.group();

    this.time.addEvent({
        delay: 100,
        callback: function() {
          var enemy = new BasicEnemy(
            this,
            Phaser.Math.Between(0, this.game.config.width),
            0
          );
          this.basicEnemy.add(enemy);
        },
        callbackScope: this,
        loop: true
      });

In sceneMain.js I'm trying to get enemies to spawn from the top of the screen with this line...

this.basicEnemy.add(enemy);

Any help would be much appreciated.


问:
Modal dialog box in an application run on IE browser using selenium java not identified
I am not able to identify the modal dialog box in an application run on IE browser using selenium java. I am getting a null pointer exception. I tried all possible ways. I wanted to know if there is any bug in that issue?</p>

答:
Do you mean you are not able to switch to modal dialog? If yes than you can refer line of code below may help you to switch to modal dialog from parent window.

```<code> String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window

// Now you are in the popup window, perform necessary actions here

driver.switchTo().window(parentWindowHandler);  // switch back to parent window
</code>```

Reference:

How to handle Pop-up in Selenium WebDriver using Java

If I misunderstood anything from your above description than try to provide detailed description about your issue with sample code. We will again try to  check the issue and try to provide suggestions for it.

Body:
Do you mean you are not able to switch to modal dialog? If yes than you can refer line of code below may help you to switch to modal dialog from parent window.

 String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window

// Now you are in the popup window, perform necessary actions here

driver.switchTo().window(parentWindowHandler);  // switch back to parent window

Reference:

How to handle Pop-up in Selenium WebDriver using Java

If I misunderstood anything from your above description than try to provide detailed description about your issue with sample code. We will again try to  check the issue and try to provide suggestions for it.


问:
Unable to enter text in Compose new Tweet box on Twitter using Selenium Webdriver
I'm trying to automate Tweeting using Selenium Webdriver in Chrome. I can login and click the Tweet button, opening the Compose new Tweet box, but when I try to enter text with element.sendKeys(tweetMessage); I get

org.openqa.selenium.ElementNotInteractableException: element not
  interactable

Using:
selenium-java-3.141.59
chrome=74.0.3729.169
(Driver info: chromedriver=74.0.3729.6)

Here's the relevant code:

```<code>    String composeTweetXpath = "//div[@aria-labelledby='Tweetstorm-tweet-box-0-label Tweetstorm-tweet-box-0-text-label']//div";
    String tweetMessage = "This is my test Tweet";

    WebDriver driver;
    driver = new ChromeDriver();
.
.
.
.

try {
    element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(composeTweetXpath)));
    System.out.println("After wait until...");
    element = driver.findElement(By.xpath(composeTweetXpath));
    System.out.println("After driver.findElement...");
    element.click();
    System.out.println("After element.click...");
    element.sendKeys(tweetMessage);
    System.out.println("Found Tweet box and typed message");
} catch ( Exception e1) {
    System.out.println("Failed to find Tweet box");
    e1.printStackTrace();
}
</code>```

I'm surprised that I don't get the error on element.click(); but on element.sendKeys(tweetMessage); My output from this snippet is :

After wait until...

After driver.findElement...

After element.click...

Moved to element...

Failed to find Tweet box

org.openqa.selenium.ElementNotInteractableException: element not interactable

I've also tried using:

```<code>    String js = "arguments[1].value = arguments[0]; ";
    System.out.println("Executing : " + js);
    javascript.executeScript(js, tweetMessage, element);
</code>```

...instead of element.sendKeys(tweetMessage); This doesn't fall into the } catch ( Exception e1) { block, but still doesn't enter the text in the Compose new Tweet box.

Strangely enough, if I use driver = new FirefoxDriver(); I get the TimeoutException error at this line:

```<code>    element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(composeTweetXpath)));
</code>```

org.openqa.selenium.TimeoutException: Expected condition failed:
  waiting for element to be clickable: By.xpath:
  //div[@aria-labelledby='Tweetstorm-tweet-box-0-label
  Tweetstorm-tweet-box-0-text-label']//div (tried for 10 second(s) with
  500 milliseconds interval)

```<code>
</code>```

答:
Use a CSS selector

ChromeDriver newDriver = new ChromeDriver();
        WebDriverWait waits = new WebDriverWait(newDriver, 50);

```<code>    newDriver.get("https://twitter.com/");
    newDriver.findElement(By.name("session[username_or_email]")).sendKeys("arungnairktm@gmail.com");
    newDriver.findElement(By.name("session[password]")).sendKeys("Cisco_12345678");
    newDriver.findElement(By.className("submit")).click();
    WebElement composes = waits
            .until(ExpectedConditions.visibilityOfElementLocated(By.id("global-new-tweet-button")));
    composes.click();
    WebElement tweets = waits.until(ExpectedConditions.visibilityOf(newDriver.findElement(By.cssSelector(
            "#Tweetstorm-tweet-box-0 > div.tweet-box-content > div.tweet-content > div.RichEditor.RichEditor--emojiPicker.is-fakeFocus > div.RichEditor-container.u-borderRadiusInherit > div.RichEditor-scrollContainer.u-borderRadiusInherit > div.tweet-box.rich-editor.is-showPlaceholder"))));

    tweets.click();
    tweets.sendKeys("heys");
</code>```

Body:
I'm trying to automate Tweeting using Selenium Webdriver in Chrome. I can login and click the Tweet button, opening the Compose new Tweet box, but when I try to enter text with element.sendKeys(tweetMessage); I get

org.openqa.selenium.ElementNotInteractableException: element not
  interactable

Using:
selenium-java-3.141.59
chrome=74.0.3729.169
(Driver info: chromedriver=74.0.3729.6)

Here's the relevant code:

    String composeTweetXpath = "//div[@aria-labelledby='Tweetstorm-tweet-box-0-label Tweetstorm-tweet-box-0-text-label']//div";
    String tweetMessage = "This is my test Tweet";

    WebDriver driver;
    driver = new ChromeDriver();
.
.
.
.

try {
    element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(composeTweetXpath)));
    System.out.println("After wait until...");
    element = driver.findElement(By.xpath(composeTweetXpath));
    System.out.println("After driver.findElement...");
    element.click();
    System.out.println("After element.click...");
    element.sendKeys(tweetMessage);
    System.out.println("Found Tweet box and typed message");
} catch ( Exception e1) {
    System.out.println("Failed to find Tweet box");
    e1.printStackTrace();
}

I'm surprised that I don't get the error on element.click(); but on element.sendKeys(tweetMessage); My output from this snippet is :

After wait until...

After driver.findElement...

After element.click...

Moved to element...

Failed to find Tweet box

org.openqa.selenium.ElementNotInteractableException: element not interactable

I've also tried using:

    String js = "arguments[1].value = arguments[0]; ";
    System.out.println("Executing : " + js);
    javascript.executeScript(js, tweetMessage, element);

...instead of element.sendKeys(tweetMessage); This doesn't fall into the } catch ( Exception e1) { block, but still doesn't enter the text in the Compose new Tweet box.

Strangely enough, if I use driver = new FirefoxDriver(); I get the TimeoutException error at this line:

    element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(composeTweetXpath)));

org.openqa.selenium.TimeoutException: Expected condition failed:
  waiting for element to be clickable: By.xpath:
  //div[@aria-labelledby='Tweetstorm-tweet-box-0-label
  Tweetstorm-tweet-box-0-text-label']//div (tried for 10 second(s) with
  500 milliseconds interval)

Body:
Use a CSS selector

ChromeDriver newDriver = new ChromeDriver();
        WebDriverWait waits = new WebDriverWait(newDriver, 50);

    newDriver.get("https://twitter.com/");
    newDriver.findElement(By.name("session[username_or_email]")).sendKeys("arungnairktm@gmail.com");
    newDriver.findElement(By.name("session[password]")).sendKeys("Cisco_12345678");
    newDriver.findElement(By.className("submit")).click();
    WebElement composes = waits
            .until(ExpectedConditions.visibilityOfElementLocated(By.id("global-new-tweet-button")));
    composes.click();
    WebElement tweets = waits.until(ExpectedConditions.visibilityOf(newDriver.findElement(By.cssSelector(
            "#Tweetstorm-tweet-box-0 > div.tweet-box-content > div.tweet-content > div.RichEditor.RichEditor--emojiPicker.is-fakeFocus > div.RichEditor-container.u-borderRadiusInherit > div.RichEditor-scrollContainer.u-borderRadiusInherit > div.tweet-box.rich-editor.is-showPlaceholder"))));

    tweets.click();
    tweets.sendKeys("heys");


问:
PHP - Manipulate user picture in active directory
Is it possible to retrieve and update a user's picture in Active Directory using PHP? If so, how would this be accomplished?

Here is my setup:

PHP 5.3 on IIS 7.5

Domain controller is Windows 2008

i told about it pictures-in-active-directory

答:
I don't think the user image is stored inside the Active Directory by default. User images are stored in the user profile and not in the Active Directory.

It is possible to extend the Active Directory schema to include images, but they are not used for the user image when logging in for example.

ContentLicense: CC BY-SA 3.0


问:
Get Row Index # for Row Containing Value Most Similar to a Value in Another Dataset
Suppose I have 2 Matrices m3 and m4:

m3 <- matrix(6:1,nrow=3,ncol=1)

```<code>    [,1]
[1,]   6
[2,]   5
[3,]   4
</code>```

m4 <- matrix(6:1,nrow=2,ncol=1)

```<code>    [,1]
[1,]   6
[2,]   5
</code>```

For each rowvalue in m4 (6 and 5) I want the index row of m3 containing the value most similar to the rowvalue of m4 (by absolute difference).

Therefore, since the values of m4[1,1] = 6 and m4[2,1] = 5, the closest values in m3 by absolute difference are m3[1,1] = 6 (rowindex=1) and m3[2,1] = 5 (rowindex=2)

So, I want matrix m5 to be:

```<code>    [,1]
[1,]   1
[2,]   2
</code>```

答:
You can use sapply -

```<code>sapply(m4, function(x) {
  which.min(abs(x - m3))
}) %>%
  matrix(ncol = 1)

     [,1]
[1,]    1
[2,]    2
</code>```

Body:
Suppose I have 2 Matrices m3 and m4:

m3 <- matrix(6:1,nrow=3,ncol=1)

    [,1]
[1,]   6
[2,]   5
[3,]   4

m4 <- matrix(6:1,nrow=2,ncol=1)

    [,1]
[1,]   6
[2,]   5

For each rowvalue in m4 (6 and 5) I want the index row of m3 containing the value most similar to the rowvalue of m4 (by absolute difference).

Therefore, since the values of m4[1,1] = 6 and m4[2,1] = 5, the closest values in m3 by absolute difference are m3[1,1] = 6 (rowindex=1) and m3[2,1] = 5 (rowindex=2)

So, I want matrix m5 to be:

    [,1]
[1,]   1
[2,]   2

Body:
You can use sapply -

sapply(m4, function(x) {
  which.min(abs(x - m3))
}) %>%
  matrix(ncol = 1)

     [,1]
[1,]    1
[2,]    2


问:
How to access website-specific Javascript objects in Go?
I'm building a logging tool for websites in Golang, and was wondering if its possible to query Javascript objects from my Go program. For example, when I open up Developer Tools in Chrome, and type a specific variable in the console, the variable's value is outputted.

I'd like to develop a Go script that can query a variable's value for a given website, and print that value to the machine's command line.

I've tried googling my question in multiple phrasings, but haven't found any relevant information. I'm not even sure if its even possible in any language.

答:
I think what you're really looking for is a "headless browser" written or consumable by Go -- here's a Reddit thread with some possibilities.

Effectively you're asking to curl a website and parse the runtime variables out of it -- but curl doesn't actually render the response, which is why you'd need a headless browser of some sort to render the output and then interact with the page in a sandbox environment.


问:
Create a dictionary of generic variables in swift
I'm looking for a way to store a generics subclass in a dictionary but I'm having problems.

In the following example I'm trying to create a dictionary of objects that I know will subclass Entity<T>. I'm successfully storing single instances of my sub classes FloatEntity and StringEntity in an Entity type var but when I try to store the same in a dictionary of type Dictionary<String, Entity> I get an error.

class Entity<T> {
    var _value: T
    var value: T { get { return _value } set {_value = newValue}}

    init (defaultValue: T) {
        _value = defaultValue
    }
}

class FloatEntity: Entity<Float> {
}

class StringEntity: Entity<String> {
}

func run () {
    let variable1: Entity = FloatEntity (defaultValue: 1)
    let variable2: Entity = StringEntity (defaultValue: "")
    var dictionary: Dictionary<String, Entity> = [
        "One": FloatEntity (defaultValue: 1),
        "Two": StringEntity (defaultValue: ""),
    ]
    print (variable1)
    print (variable2)
    print (dictionary)
}
```

The error:

Cannot convert value of type 'FloatEntitiy' to expected dictionary value
  type 'Entity'

Can anyone advise on how I might go about using a dictionary to store generics like this?

答:
Swift generics are invariant, thus Entity is not a subclass of Entity, even if B would be a subclass of A. So you cannot store the same types using the superclass of Entity in a dictionary.

You could achieve what you want by using AnyObject as your dictionary value, e.g. with this code:-

```<code>var dictionary: Dictionary<String, AnyObject> = [
  "One": FloatEntity (defaultValue: 1),
  "Two": FloatEntity (defaultValue: 2),
]
</code>```

I don't think you can extract a type-erased Entity from that though (happy to be corrected). But you could do something like this:-

```<code>let v = dictionary["One"]
if let v1 = v as? FloatEntity
{
  ...
}
</code>```

Body:
I'm looking for a way to store a generics subclass in a dictionary but I'm having problems.

In the following example I'm trying to create a dictionary of objects that I know will subclass Entity<T>. I'm successfully storing single instances of my sub classes FloatEntity and StringEntity in an Entity type var but when I try to store the same in a dictionary of type Dictionary<String, Entity> I get an error.

class Entity<T> {
    var _value: T
    var value: T { get { return _value } set {_value = newValue}}

    init (defaultValue: T) {
        _value = defaultValue
    }
}

class FloatEntity: Entity<Float> {
}

class StringEntity: Entity<String> {
}

func run () {
    let variable1: Entity = FloatEntity (defaultValue: 1)
    let variable2: Entity = StringEntity (defaultValue: "")
    var dictionary: Dictionary<String, Entity> = [
        "One": FloatEntity (defaultValue: 1),
        "Two": StringEntity (defaultValue: ""),
    ]
    print (variable1)
    print (variable2)
    print (dictionary)
}

The error:

Cannot convert value of type 'FloatEntitiy' to expected dictionary value
  type 'Entity'

Can anyone advise on how I might go about using a dictionary to store generics like this?

Body:
Swift generics are invariant, thus Entity<B> is not a subclass of Entity<A>, even if B would be a subclass of A. So you cannot store the same types using the superclass of Entity in a dictionary.

You could achieve what you want by using AnyObject as your dictionary value, e.g. with this code:-

var dictionary: Dictionary<String, AnyObject> = [
  "One": FloatEntity (defaultValue: 1),
  "Two": FloatEntity (defaultValue: 2),
]

I don't think you can extract a type-erased Entity from that though (happy to be corrected). But you could do something like this:-

let v = dictionary["One"]
if let v1 = v as? FloatEntity
{
  ...
}


问:
Duplicate 'Content' items were included. .json file in assets folder in .net core angular 6 web app
I have a .Net Core 2.1 web application using Angular 6 for the front-end, developed in Visual Studio 2017.

Inside my Angular assets folder I also have a json folder with a single file: iconClasses.json. When I publish this, I first build the angular app with ng build --prod from within the ClientApp folder. This moves the .json file to the dist folder, as expected:

In my .csproj the only ItemGroups are:

    <ItemGroup>
        <Content Include="ClientApp\dist\**\*" CopyToPublishDirectory="PreserveNewest" />
    </ItemGroup>

    <ItemGroup>
        <Content Remove="appsettings.Development.json" />

    </ItemGroup>
```

<p>Publishing this results in the following error:</p>

<blockquote>
  <p>Duplicate 'Content' items were included. The .NET SDK includes
  'Content' items from your project directory by default. You can either
  remove these items from your project file, or set the
  'EnableDefaultContentItems' property to 'false' if you want to
  explicitly include them in your project file. For more information,
  see https://aka.ms/sdkimplicititems. The duplicate items were: 'ClientApp\dist\assets\json\iconClasses.json'  </p>
</blockquote>

<p>Uncommenting the line that explicitly removes this file allows the publish to proceed, but the file is removed from the final published package. </p>

<p>Comparing the .js files in the dist/assets/js folder to the .json in the dist/assets/json shows that they are all of build action 'Content' and 'Do not copy'. Setting the build action of the .json file to 'None' simply adds the <code><Content Remove /></code> as above, but also:</p>

<pre class="lang-xml prettyprint-override"><code>    <ItemGroup>
      <None Include="ClientApp\dist\assets\json\iconClasses.json" />
    </ItemGroup>
</code>```

Again, this simply results in the .json file being removed from the publish package.

I did notice that the src\assets\json\iconClasses.json file's build action was set to 'Content' whereas the other src\assets files were set to 'None', so I set the .json file to 'None' also. However, this resulted in the same error, unless the dist version was explicitly removed also.

Adding the following to my PropertyGroup in my .csproj includes the .json file in the dist/assets/json but then misses out other files my system needs:

<EnableDefaultContentItems>false</EnableDefaultContentItems>
```

So, how can I have a .json file in the assets folder get moved to the dist assets folder? Is the only way to set EnableDefaultContentItems to false, figure out all the missing files and add them manually?

答:
Remove this:

    <ItemGroup>
         <Content Include="ClientApp\dist\**\*" CopyToPublishDirectory="PreserveNewest"/>
    </ItemGroup>
```

<blockquote>
  <p>The .NET SDK includes 'Content' items from your project directory by default. You can either remove these items from your project file...</p>
</blockquote>

<p>By default, .NET Core SDK includes this folder already (along with everything else in ClientApp/)
What you should try instead is removing the src folder (and everything else you don't want to publish, e2e etc.) from the published location, like so:</p>

<pre class="lang-html prettyprint-override"><code>    <ItemGroup>
      <None Include="ClientApp\src\**" />
    </ItemGroup>
</code>```

Body:
I have a .Net Core 2.1 web application using Angular 6 for the front-end, developed in Visual Studio 2017.

Inside my Angular assets folder I also have a json folder with a single file: iconClasses.json. When I publish this, I first build the angular app with ng build --prod from within the ClientApp folder. This moves the .json file to the dist folder, as expected:

In my .csproj the only ItemGroups are:

    <ItemGroup>
        <Content Include="ClientApp\dist\**\*" CopyToPublishDirectory="PreserveNewest" />
    </ItemGroup>

    <ItemGroup>
        <Content Remove="appsettings.Development.json" />

    </ItemGroup>

Publishing this results in the following error:

Duplicate 'Content' items were included. The .NET SDK includes
  'Content' items from your project directory by default. You can either
  remove these items from your project file, or set the
  'EnableDefaultContentItems' property to 'false' if you want to
  explicitly include them in your project file. For more information,
  see https://aka.ms/sdkimplicititems. The duplicate items were: 'ClientApp\dist\assets\json\iconClasses.json'

Uncommenting the line that explicitly removes this file allows the publish to proceed, but the file is removed from the final published package.

Comparing the .js files in the dist/assets/js folder to the .json in the dist/assets/json shows that they are all of build action 'Content' and 'Do not copy'. Setting the build action of the .json file to 'None' simply adds the <Content Remove /> as above, but also:

    <ItemGroup>
      <None Include="ClientApp\dist\assets\json\iconClasses.json" />
    </ItemGroup>

Again, this simply results in the .json file being removed from the publish package.

I did notice that the src\assets\json\iconClasses.json file's build action was set to 'Content' whereas the other src\assets files were set to 'None', so I set the .json file to 'None' also. However, this resulted in the same error, unless the dist version was explicitly removed also.

Adding the following to my PropertyGroup in my .csproj includes the .json file in the dist/assets/json but then misses out other files my system needs:

<EnableDefaultContentItems>false</EnableDefaultContentItems>

So, how can I have a .json file in the assets folder get moved to the dist assets folder? Is the only way to set EnableDefaultContentItems to false, figure out all the missing files and add them manually?

Body:
Remove this:

    <ItemGroup>
         <Content Include="ClientApp\dist\**\*" CopyToPublishDirectory="PreserveNewest"/>
    </ItemGroup>

The .NET SDK includes 'Content' items from your project directory by default. You can either remove these items from your project file...

By default, .NET Core SDK includes this folder already (along with everything else in ClientApp/)
What you should try instead is removing the src folder (and everything else you don't want to publish, e2e etc.) from the published location, like so:

    <ItemGroup>
      <None Include="ClientApp\src\**" />
    </ItemGroup>


问:
How to find mean of quantitative variable from categorical variable in a dataframe?
Let's say I have the following data frame in pandas:

```<code>data = {'State':['CA', 'CA', 'CA', 'CA', 'NY', 'NY', 'TX'],
        'Cost':[20, 30, 40, 50, 60, 70, 70]}
test = pd.DataFrame(data)
print(test.head(7))
</code>```

which would be the following

```<code>  State  Cost
0    CA    20
1    CA    30
2    CA    40
3    CA    50
4    NY    60
5    NY    70
6    TX    70
</code>```

In this scenario, the mean cost of California would be 35, the mean cost of new york would be 65, and the mean cost of texas would be 70.

Here is my question: what would be the query in pandas in which we could find the mean cost of a state given that state?

答:
Use groupby and mean:

```<code>print(test.groupby('State').mean())
</code>```

Which outputs:

```<code>       Cost
State
CA       35
NY       65
TX       70
</code>```

If you want a cleaner DataFrame:

```<code>print(test.groupby('State', as_index=False).mean())
</code>```

Which gives:

```<code>  State  Cost
0    CA    35
1    NY    65
2    TX    70
</code>```

Body:
Let's say I have the following data frame in pandas:

data = {'State':['CA', 'CA', 'CA', 'CA', 'NY', 'NY', 'TX'],
        'Cost':[20, 30, 40, 50, 60, 70, 70]}
test = pd.DataFrame(data)
print(test.head(7))

which would be the following

  State  Cost
0    CA    20
1    CA    30
2    CA    40
3    CA    50
4    NY    60
5    NY    70
6    TX    70

In this scenario, the mean cost of California would be 35, the mean cost of new york would be 65, and the mean cost of texas would be 70.

Here is my question: what would be the query in pandas in which we could find the mean cost of a state given that state?

Body:
Use groupby and mean:

print(test.groupby('State').mean())

Which outputs:

       Cost
State
CA       35
NY       65
TX       70

If you want a cleaner DataFrame:

print(test.groupby('State', as_index=False).mean())

Which gives:

  State  Cost
0    CA    35
1    NY    65
2    TX    70


问:
Why repaint() doesn't work when i want repaint my painting?
This is my first java animation and I want my flag to start using repaint (), but the method does nothing and I do not know why. It's about the moveFlag method, it should put the flag in motion reminiscent of a flag blowing in the wind. The application simply displays the flag but it does not move it.</p>

```<code>public class Testing extends JPanel implements ActionListener {
    private int x,y, xinc, yinc;

    public void paintComponent(Graphics g){
        xinc = 10;
        yinc = 10;
        x = 101;
        y = 151;

        Graphics2D gimg = (Graphics2D) g;

        Rectangle2D rect = new Rectangle2D.Double(50,50,10,300);

        CubicCurve2D cub1 = new
        CubicCurve2D.Double(60,50,x,10,y,100,200,50);
        gimg.draw(cub1);

        CubicCurve2D cub2 = new
        CubicCurve2D.Double(60,100,x,60,y,150,200,100);
        gimg.draw(cub2);

        CubicCurve2D cub3 = new
        CubicCurve2D.Double(60,150,x,110,y,200,200,150);
        gimg.draw(cub3);

        Line2D l1 = new Line2D.Double(200,50,200,150);
        gimg.draw(l1);

        GeneralPath gp1 = new GeneralPath();
        GeneralPath gp2 = new GeneralPath();

        gp1.moveTo(60,50);
        gp1.curveTo(x,10,y,100,200,50);
        gp1.lineTo(200,100);
        gp1.curveTo(y,150,x,60,60,100);
        gp1.lineTo(60,50);

        gimg.setColor(Color.WHITE);

        gimg.fill(gp1);

        gimg.setColor(Color.GRAY);

        gimg.fill(rect);

        gp2.moveTo(60,100);
        gp2.curveTo(x,60,y,150,200,100);
        gp2.lineTo(200,150);
        gp2.curveTo(y,200,x,110,60,150);
        gp2.lineTo(60,100);

        gimg.setColor(Color.RED);

        gimg.fill(gp2);
    }
    public void moveFlag(){  //waving animation
        Timer timer = new Timer(20, this);
        timer.start();

        x = x + xinc;
        y = y + yinc;

        if(x<=60||(x+xinc)>=130)
            xinc*=-1;

        if(y<=50||(y+yinc)>=230)
            yinc*=-1;

        //revalidate();
        repaint();
    }
    @Override
    public void actionPerformed(ActionEvent e) {

    }
    public static void main(String [] args){
        JFrame frame = new JFrame();

        Testing test = new Testing();
        frame.setContentPane(test);
        frame.setSize(500,500);
        frame.setVisible(true);

        test.moveFlag();
    }
}
</code>```

答:
You had the right idea but some of the code was in the wrong places.  I will explain in the comments.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;

    public class Testing extends JPanel implements ActionListener {
       private int x, y, xinc, yinc;

       public void paintComponent(Graphics g) {
          // added this statement.
          super.paintComponent(g);
          Graphics2D gimg = (Graphics2D) g;

          Rectangle2D rect = new Rectangle2D.Double(50, 50, 10, 300);

          CubicCurve2D cub1 =
                new CubicCurve2D.Double(60, 50, x, 10, y, 100, 200, 50);
          gimg.draw(cub1);

          CubicCurve2D cub2 =
                new CubicCurve2D.Double(60, 100, x, 60, y, 150, 200, 100);
          gimg.draw(cub2);

          CubicCurve2D cub3 =
                new CubicCurve2D.Double(60, 150, x, 110, y, 200, 200, 150);
          gimg.draw(cub3);

          Line2D l1 = new Line2D.Double(200, 50, 200, 150);
          gimg.draw(l1);

          GeneralPath gp1 = new GeneralPath();
          GeneralPath gp2 = new GeneralPath();

          gp1.moveTo(60, 50);
          gp1.curveTo(x, 10, y, 100, 200, 50);
          gp1.lineTo(200, 100);
          gp1.curveTo(y, 150, x, 60, 60, 100);
          gp1.lineTo(60, 50);

          gimg.setColor(Color.WHITE);

          gimg.fill(gp1);

          gimg.setColor(Color.GRAY);

          gimg.fill(rect);

          gp2.moveTo(60, 100);
          gp2.curveTo(x, 60, y, 150, 200, 100);
          gp2.lineTo(200, 150);
          gp2.curveTo(y, 200, x, 110, 60, 150);
          gp2.lineTo(60, 100);

          gimg.setColor(Color.RED);

          gimg.fill(gp2);
       }

       public void moveFlag() { // waving animation
          Timer timer = new Timer(20, this);
          timer.start();
          // moved the next four statements from paintComponents.  They
          // are initializations.  In paintComponent you kept resetting them.
          xinc = 10;
          yinc = 10;
          x = 101;
          y = 151;

          repaint();
       }

       @Override
       public void actionPerformed(ActionEvent e) {
         //moved all of these from moveFlag to here. This is called by
         //the timer event to update the x and y coordinates.
          x = x + xinc;
          y = y + yinc;

          if (x <= 60 || (x + xinc) >= 130)
             xinc *= -1;

          if (y <= 50 || (y + yinc) >= 230)
             yinc *= -1;

          // revalidate();
          repaint();
       }

      public static void main(String[] args) {
          JFrame frame = new JFrame();

          Testing test = new Testing();
          frame.setContentPane(test);
          frame.setSize(500, 500);
          frame.setVisible(true);

          test.moveFlag();
       }
    }

```

The only piece of code I had to add was the super.paintComponent(g) call.  This is necessary since you are overriding paintComponent() you need to ensure the parent method is called before you do your graphics.

Body:
This is my first java animation and I want my flag to start using repaint (), but the method does nothing and I do not know why. It's about the moveFlag method, it should put the flag in motion reminiscent of a flag blowing in the wind. The application simply displays the flag but it does not move it.

public class Testing extends JPanel implements ActionListener {
    private int x,y, xinc, yinc;

    public void paintComponent(Graphics g){
        xinc = 10;
        yinc = 10;
        x = 101;
        y = 151;

        Graphics2D gimg = (Graphics2D) g;

        Rectangle2D rect = new Rectangle2D.Double(50,50,10,300);

        CubicCurve2D cub1 = new
        CubicCurve2D.Double(60,50,x,10,y,100,200,50);
        gimg.draw(cub1);

        CubicCurve2D cub2 = new
        CubicCurve2D.Double(60,100,x,60,y,150,200,100);
        gimg.draw(cub2);

        CubicCurve2D cub3 = new
        CubicCurve2D.Double(60,150,x,110,y,200,200,150);
        gimg.draw(cub3);

        Line2D l1 = new Line2D.Double(200,50,200,150);
        gimg.draw(l1);

        GeneralPath gp1 = new GeneralPath();
        GeneralPath gp2 = new GeneralPath();

        gp1.moveTo(60,50);
        gp1.curveTo(x,10,y,100,200,50);
        gp1.lineTo(200,100);
        gp1.curveTo(y,150,x,60,60,100);
        gp1.lineTo(60,50);

        gimg.setColor(Color.WHITE);

        gimg.fill(gp1);

        gimg.setColor(Color.GRAY);

        gimg.fill(rect);

        gp2.moveTo(60,100);
        gp2.curveTo(x,60,y,150,200,100);
        gp2.lineTo(200,150);
        gp2.curveTo(y,200,x,110,60,150);
        gp2.lineTo(60,100);

        gimg.setColor(Color.RED);

        gimg.fill(gp2);
    }
    public void moveFlag(){  //waving animation
        Timer timer = new Timer(20, this);
        timer.start();

        x = x + xinc;
        y = y + yinc;

        if(x<=60||(x+xinc)>=130)
            xinc*=-1;

        if(y<=50||(y+yinc)>=230)
            yinc*=-1;

        //revalidate();
        repaint();
    }
    @Override
    public void actionPerformed(ActionEvent e) {

    }
    public static void main(String [] args){
        JFrame frame = new JFrame();

        Testing test = new Testing();
        frame.setContentPane(test);
        frame.setSize(500,500);
        frame.setVisible(true);

        test.moveFlag();
    }
}

Body:
You had the right idea but some of the code was in the wrong places.  I will explain in the comments.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;

    public class Testing extends JPanel implements ActionListener {
       private int x, y, xinc, yinc;

       public void paintComponent(Graphics g) {
          // added this statement.
          super.paintComponent(g);
          Graphics2D gimg = (Graphics2D) g;

          Rectangle2D rect = new Rectangle2D.Double(50, 50, 10, 300);

          CubicCurve2D cub1 =
                new CubicCurve2D.Double(60, 50, x, 10, y, 100, 200, 50);
          gimg.draw(cub1);

          CubicCurve2D cub2 =
                new CubicCurve2D.Double(60, 100, x, 60, y, 150, 200, 100);
          gimg.draw(cub2);

          CubicCurve2D cub3 =
                new CubicCurve2D.Double(60, 150, x, 110, y, 200, 200, 150);
          gimg.draw(cub3);

          Line2D l1 = new Line2D.Double(200, 50, 200, 150);
          gimg.draw(l1);

          GeneralPath gp1 = new GeneralPath();
          GeneralPath gp2 = new GeneralPath();

          gp1.moveTo(60, 50);
          gp1.curveTo(x, 10, y, 100, 200, 50);
          gp1.lineTo(200, 100);
          gp1.curveTo(y, 150, x, 60, 60, 100);
          gp1.lineTo(60, 50);

          gimg.setColor(Color.WHITE);

          gimg.fill(gp1);

          gimg.setColor(Color.GRAY);

          gimg.fill(rect);

          gp2.moveTo(60, 100);
          gp2.curveTo(x, 60, y, 150, 200, 100);
          gp2.lineTo(200, 150);
          gp2.curveTo(y, 200, x, 110, 60, 150);
          gp2.lineTo(60, 100);

          gimg.setColor(Color.RED);

          gimg.fill(gp2);
       }

       public void moveFlag() { // waving animation
          Timer timer = new Timer(20, this);
          timer.start();
          // moved the next four statements from paintComponents.  They
          // are initializations.  In paintComponent you kept resetting them.
          xinc = 10;
          yinc = 10;
          x = 101;
          y = 151;

          repaint();
       }

       @Override
       public void actionPerformed(ActionEvent e) {
         //moved all of these from moveFlag to here. This is called by
         //the timer event to update the x and y coordinates.
          x = x + xinc;
          y = y + yinc;

          if (x <= 60 || (x + xinc) >= 130)
             xinc *= -1;

          if (y <= 50 || (y + yinc) >= 230)
             yinc *= -1;

          // revalidate();
          repaint();
       }

      public static void main(String[] args) {
          JFrame frame = new JFrame();

          Testing test = new Testing();
          frame.setContentPane(test);
          frame.setSize(500, 500);
          frame.setVisible(true);

          test.moveFlag();
       }
    }

The only piece of code I had to add was the super.paintComponent(g) call.  This is necessary since you are overriding paintComponent() you need to ensure the parent method is called before you do your graphics.


答:
variable1 and variable2 are not of type Entity but are in fact Entity<Float> and Entity<String> which are two unrelated types.  Use a protocol to unite them:

```<code>protocol EntityProtocol { }

class Entity<T> : EntityProtocol {
    var _value: T
    var value: T { get { return _value } set {_value = newValue}}

    init (defaultValue: T) {
        _value = defaultValue
    }
}

class FloatEntity: Entity<Float> {
}

class StringEntity: Entity<String> {
}

func run () {
    let variable1: Entity = FloatEntity (defaultValue: 1)
    let variable2: Entity = StringEntity (defaultValue: "")
    var dictionary: Dictionary<String, EntityProtocol> = [
        "One": FloatEntity (defaultValue: 1),
        "Two": StringEntity (defaultValue: ""),
    ]
    print (variable1)
    print (variable2)
    print (dictionary)
}
</code>```

Title: Create a dictionary of generic variables in swift

Body:
variable1 and variable2 are not of type Entity but are in fact Entity<Float> and Entity<String> which are two unrelated types.  Use a protocol to unite them:

protocol EntityProtocol { }

class Entity<T> : EntityProtocol {
    var _value: T
    var value: T { get { return _value } set {_value = newValue}}

    init (defaultValue: T) {
        _value = defaultValue
    }
}

class FloatEntity: Entity<Float> {
}

class StringEntity: Entity<String> {
}

func run () {
    let variable1: Entity = FloatEntity (defaultValue: 1)
    let variable2: Entity = StringEntity (defaultValue: "")
    var dictionary: Dictionary<String, EntityProtocol> = [
        "One": FloatEntity (defaultValue: 1),
        "Two": StringEntity (defaultValue: ""),
    ]
    print (variable1)
    print (variable2)
    print (dictionary)
}


问:
How to fix layers offsets when exporting all Photoshop groups to .pngs in a javascript script?
When I play the animation in photoshop, it looks fine. Every layer is in the correct position. When I run my script that saves each group to a png, the results have some layers offset.

I believe layers have weird issues with positions in animations. An image in a layer could have a different position in one frame and not another frame. I believe I'd have to get the script to step the frame in the animation to get the correct position, but I'm not sure how I would do that.

```<code>var set;
var layer;
var count = 0;
for(var i = 0; i < app.activeDocument.layerSets.length; i ++)
{
    set = app.activeDocument.layerSets[i];
    set.visible = false;
    count ++;
}
for(var i = 0; i < app.activeDocument.layerSets.length; i ++)
{
    set = app.activeDocument.layerSets[i];
    set.visible = true;

    // save
    var fileName = set.name.replace(/[\\\*\/\?:"\|<> ]/g,'');
    if(fileName.length ==0) fileName = "autoname";
    var handle = File(app.activeDocument.path + "/" + fileName + ".png");
    pngSaveOptions = new PNGSaveOptions();
    activeDocument.saveAs(handle, pngSaveOptions, true, Extension.LOWERCASE);

    set.visible = false;
}

alert("Saved " + count + " images.");
</code>```

The correct animation plays in photoshop. The resulting .pngs are incorrect.
https://imgur.com/a/y9PLPUX

答:
Figured it out. This script has a function that can go to another frame in the animation. I use it to render all sub-groups of the animation to their own separate .pngs</p>

```<code>var set;
var layer;

for(var docI = 0; docI < app.documents.length; docI ++) {
    var doc = app.documents[docI];
    for (var frameIndex = 1; frameIndex <= 8; frameIndex++) {
        goToFrame(frameIndex);
        for (var i = 0; i < doc.layerSets.length; i++) {
            set = doc.layerSets[i];
            if (set.visible) {
                for (var setI = 0; setI < set.layerSets.length; setI++) {
                    var innerSet = set.layerSets[setI];
                    innerSet.visible = false;
                }
                for (var setI = 0; setI < set.layerSets.length; setI++) {
                    var innerSet = set.layerSets[setI];
                    innerSet.visible = true;
                    var fileName = innerSet.name.replace(/[\\\*\/\?:"\|<> ]/g, '');
                    if (fileName.length == 0) fileName = "autoname";
                    var handle = File(doc.path + "/output/" + doc.name.replace("player", fileName).replace(".psd", '') + (doc.layerSets.length - i) + ".png");
                    pngSaveOptions = new PNGSaveOptions();
                    activeDocument.saveAs(handle, pngSaveOptions, true, Extension.LOWERCASE);
                    innerSet.visible = false;
                }

            }
        }
    }
}

alert("Saved images.");

function goToFrame(index) {
    var jumpToFrameNumber = index; // counts from 1

    var desc = new ActionDescriptor();
    var ref1 = new ActionReference();
    ref1.putIndex( stringIDToTypeID( "animationFrameClass" ), jumpToFrameNumber );
    desc.putReference( charIDToTypeID( "null" ), ref1 );
    executeAction( charIDToTypeID( "slct" ), desc, DialogModes.NO );
}
</code>```

Body:
When I play the animation in photoshop, it looks fine. Every layer is in the correct position. When I run my script that saves each group to a png, the results have some layers offset.

I believe layers have weird issues with positions in animations. An image in a layer could have a different position in one frame and not another frame. I believe I'd have to get the script to step the frame in the animation to get the correct position, but I'm not sure how I would do that.

var set;
var layer;
var count = 0;
for(var i = 0; i < app.activeDocument.layerSets.length; i ++)
{
    set = app.activeDocument.layerSets[i];
    set.visible = false;
    count ++;
}
for(var i = 0; i < app.activeDocument.layerSets.length; i ++)
{
    set = app.activeDocument.layerSets[i];
    set.visible = true;

    // save
    var fileName = set.name.replace(/[\\\*\/\?:"\|<> ]/g,'');
    if(fileName.length ==0) fileName = "autoname";
    var handle = File(app.activeDocument.path + "/" + fileName + ".png");
    pngSaveOptions = new PNGSaveOptions();
    activeDocument.saveAs(handle, pngSaveOptions, true, Extension.LOWERCASE);

    set.visible = false;
}

alert("Saved " + count + " images.");

The correct animation plays in photoshop. The resulting .pngs are incorrect.
https://imgur.com/a/y9PLPUX

Body:
Figured it out. This script has a function that can go to another frame in the animation. I use it to render all sub-groups of the animation to their own separate .pngs

var set;
var layer;

for(var docI = 0; docI < app.documents.length; docI ++) {
    var doc = app.documents[docI];
    for (var frameIndex = 1; frameIndex <= 8; frameIndex++) {
        goToFrame(frameIndex);
        for (var i = 0; i < doc.layerSets.length; i++) {
            set = doc.layerSets[i];
            if (set.visible) {
                for (var setI = 0; setI < set.layerSets.length; setI++) {
                    var innerSet = set.layerSets[setI];
                    innerSet.visible = false;
                }
                for (var setI = 0; setI < set.layerSets.length; setI++) {
                    var innerSet = set.layerSets[setI];
                    innerSet.visible = true;
                    var fileName = innerSet.name.replace(/[\\\*\/\?:"\|<> ]/g, '');
                    if (fileName.length == 0) fileName = "autoname";
                    var handle = File(doc.path + "/output/" + doc.name.replace("player", fileName).replace(".psd", '') + (doc.layerSets.length - i) + ".png");
                    pngSaveOptions = new PNGSaveOptions();
                    activeDocument.saveAs(handle, pngSaveOptions, true, Extension.LOWERCASE);
                    innerSet.visible = false;
                }

            }
        }
    }
}

alert("Saved images.");

function goToFrame(index) {
    var jumpToFrameNumber = index; // counts from 1

    var desc = new ActionDescriptor();
    var ref1 = new ActionReference();
    ref1.putIndex( stringIDToTypeID( "animationFrameClass" ), jumpToFrameNumber );
    desc.putReference( charIDToTypeID( "null" ), ref1 );
    executeAction( charIDToTypeID( "slct" ), desc, DialogModes.NO );
}


问:
VueJS change font of specific row not all rows
Current code changes the font for all rows vs a specific row:

Vue.component('blog-post', {
  props: ['post'],
  template: `

 {{ post.title }}

      <button @click="$emit('enlarge-text')">Enlarge text</button>

  `,
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ],
    postFontSize : 1,
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}</code>```

  <blog-post v-for="post in posts" :post="post" :key="post.id" :style="{fontSize : postFontSize + 'em'}" @enlarge-text="postFontSize += 0.1"></blog-post>

```
</div>
</div>
</p>

<p>How can I just manipulate a specific row, one row, updating one row's font size vs all rows?</p>

<p>Tried the following but it did not work:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.component('blog-post', {
  props: ['post'],
  template: `
    <div class="blog-post row" :style="{fontSize : postFontSize + 'em'}" @enlarge-text="postFontSize += 0.1">
      <h3 class="cell">{{ post.title }}</h3>
      <button @click="$emit('enlarge-text')">Enlarge text</button>
      <div v-html="post.content" class="cell"></div>
    </div>
  `,
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ],
    postFontSize : 1,
  }
})</code>```

.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js"></script>

<div id="blog-post-demo">
  <blog-post v-for="post in posts" :post="post" :key="post.id"></blog-post>
</div></code>```

答:
If you want to update only 1 row, postFontSize should be local data of blog-post component

<!DOCTYPE html>

  <title>My first Vue app</title>

      <blog-post v-for="post in posts" :post="post" :key="post.id"></blog-post>

```

Body:
Current code changes the font for all rows vs a specific row:

Vue.component('blog-post', {
  props: ['post'],
  template: `

 {{ post.title }}

      <button @click="$emit('enlarge-text')">Enlarge text</button>

  `,
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ],
    postFontSize : 1,
  }
});

.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}

  <blog-post v-for="post in posts" :post="post" :key="post.id" :style="{fontSize : postFontSize + 'em'}" @enlarge-text="postFontSize += 0.1"></blog-post>

How can I just manipulate a specific row, one row, updating one row's font size vs all rows?

Tried the following but it did not work:

Vue.component('blog-post', {
  props: ['post'],
  template: `

{{ post.title }}

      <button @click="$emit('enlarge-text')">Enlarge text</button>

  `,
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ],
    postFontSize : 1,
  }
})

.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}

  <blog-post v-for="post in posts" :post="post" :key="post.id"></blog-post>

Body:
If you want to update only 1 row, postFontSize should be local data of blog-post component

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue app</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
  <style>
    .row {
      background-color: cyan;
    }

    .cell {
      background-color: antiquewhite;
    }
  </style>
</head>
<body>
    <div id="blog-post-demo">
      <blog-post v-for="post in posts" :post="post" :key="post.id"></blog-post>
    </div>
  <script>

Vue.component('blog-post', {
  props: ['post'],
  template: `
    <div class="blog-post row" :style="{fontSize : postFontSize + 'em'}">
      <h3 class="cell"> {{ post.title }}</h3>
      <button @click="postFontSize += 0.1">Enlarge text</button>
      <div v-html="post.content" class="cell"></div>
    </div>`,
  data() {
     return {
          postFontSize : 1
     }
  }
})
new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ]
  }
})
  </script>
</body>
</html>


问:
Typescript - How to use an interface in a callback function
Recently started using Typescript and something I'm unsure of.

I'm using an npm package azure-storage and specifically calling a method doesBlobExist:

```<code>blobService.doesBlobExist(containerName, blobName, (callbackResult: ErrorOrResult<BlobService.BlobResult>) => {
        //Want callbackResult.response here
});
</code>```

That doesBlobExist (function coming from the npm package) looks like this:

```<code>doesBlobExist(container: string, blob: string, callback: ErrorOrResult<BlobService.BlobResult>): void;
</code>```

And the type ErrorOrResult is an interface that has this:

```<code>interface ErrorOrResult<TResult> {
    (error: Error, result: TResult, response: ServiceResponse): void
}
</code>```

What I'm unsure of is where I call the function, I was hoping I can use that interface and do:

callbackResult.response as that is in the interface however callbackResult keeps being returned as null.
On looking into it, its being set as the error: Error from the interface.

So is it actually possible to do what I want above, or do I have to use that function like:

```<code>blobService.doesBlobExist(containerName, blobName, (error, result, response) => {
        //i.e. specify the 3 items directly in the interface
});
</code>```

答:
reading your problem, you can use the solution you wrote above, you can do something similar to:

```<code>blobService.doesBlobExist(containerName, blobName, (error, result, response) => {
        if(error !== null){
           // Do something
           return;
        }
        // here you can work with your response data
});
</code>```

If you want to avoid the error you can omit the if loop, and work direcly with your response, but you have to insert all the posible options in the response.

callbackResult.response as that is in the interface however callbackResult keeps being returned as null. On looking into it, its being set as the error: Error from the interface.

As you said, you are getting a null because the function are returning no errors.

Body:
Recently started using Typescript and something I'm unsure of.

I'm using an npm package azure-storage and specifically calling a method doesBlobExist:

blobService.doesBlobExist(containerName, blobName, (callbackResult: ErrorOrResult<BlobService.BlobResult>) => {
        //Want callbackResult.response here
});

That doesBlobExist (function coming from the npm package) looks like this:

doesBlobExist(container: string, blob: string, callback: ErrorOrResult<BlobService.BlobResult>): void;

And the type ErrorOrResult is an interface that has this:

interface ErrorOrResult<TResult> {
    (error: Error, result: TResult, response: ServiceResponse): void
}

What I'm unsure of is where I call the function, I was hoping I can use that interface and do:

callbackResult.response as that is in the interface however callbackResult keeps being returned as null.
On looking into it, its being set as the error: Error from the interface.

So is it actually possible to do what I want above, or do I have to use that function like:

blobService.doesBlobExist(containerName, blobName, (error, result, response) => {
        //i.e. specify the 3 items directly in the interface
});

Body:
reading your problem, you can use the solution you wrote above, you can do something similar to:

blobService.doesBlobExist(containerName, blobName, (error, result, response) => {
        if(error !== null){
           // Do something
           return;
        }
        // here you can work with your response data
});

If you want to avoid the error you can omit the if loop, and work direcly with your response, but you have to insert all the posible options in the response.

callbackResult.response as that is in the interface however callbackResult keeps being returned as null. On looking into it, its being set as the error: Error from the interface.

As you said, you are getting a null because the function are returning no errors.