问:
Angular Filter by 2 dates
I need to add a Filter of the Date range. Mean I need to show only that data which user input from the date and to date. I have an array of data in which there is only one date is showing. But I want to filter it like this user input any 2 dates (From and To) And in the array I only that data show which are between input dates.

```<code>   <div class="row">
   <div class="col-12">
     <div class="content-header">Claims Status</div>
       <p class="content-sub-header">Claims Settled 23</p>
   </div>
  </div>

 <section id="extended">

   <div class="row">
     <div class="col-sm-12">
       <div class="card">

    <div class="row" >
     <div class="col-sm bg-primary text-white" style="text-align: center;" ><div>Claims<br>(settled)</div><div *ngIf="statusunsettledcc">  {{statusunsettledcc}}</div></div>
    <div class="col-sm bg-success text-white" style="text-align: center;"><div>Claim Amount<br>(settled)</div><div *ngIf="statusunsettledamount">{{statusunsettledamount | number : fractionSize}}</div></div>
    <div class="col-sm bg-danger text-white" style="text-align: center;" ><div>Claims<br>(unsettled)</div><div *ngIf="status2settledcc">{{status2settledcc}}</div></div>
    <div class="col-sm bg-warning text-white" style="text-align: center;"><div>Claim Amount<br>(unsettled)</div><div *ngIf="status2settledamount">{{status2settledamount | number : fractionSize}}</div></div>
    </div>

  <div class="card-header">
    <div class="card-title-wrap bar-success">
      <h4 class="card-title">Claims</h4>
    </div>
  </div>
  <div class="card-body">
    <div class="card-block">

      <div class="row">
        <div class="col-md-3">
          <div class="form-group" >
            <label for="">Search Name</label>

            <input type="text" class="form-control" [(ngModel)]="userFilter.member_name" placeholder="Search name" name="search">
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group" >
            <label for="">Search Claim No</label>
            <input type="search"
            class="form-control" placeholder="Claim No" [(ngModel)]="userFilter.claim_no">
          </div>
        </div>

   <div class="col-md-3 form-group">
        <input type="date" class="form-control" [(ngModel)]="from"> //From date
    </div>
    <div class="col-md-3 form-group">
        <input type="date" class="form-control" [(ngModel)]="to"> //To Date
    </div>

        <div class="col-md-3" *ngIf="company">
          <div class="form-group">
            <label for="">Company</label>
            <select class="form-control" [(ngModel)]="userFilter.company_id" (change)="getClaims()">
              <option value='' >All</option>
              <option value="999">Airlink Communication</option>
              <option value="637">Ascertia (Pvt) Ltd</option>
              <option value="1053">Frontier Works Organization</option>
              <option value="1174">Ebryx (pvt) Ltd</option>
              <option value="274">HY Enterprises (Pvt) Limited</option>
              <option value="459">Naimat Saleem trust NST (US GROUP)</option>
              <option value="659">Samad Rubber Works (Pvt) Ltd</option>
              <option value="56">Sundry Clients</option>
              <option value="620">TIMEXPERTS (PRIVATE) Limited</option>
              <option value="39">US Apparel & Textile (Pvt) Limited</option>
              <option value="40">US Denim Mills (Pvt) Limited</option>
            </select>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="">Claim Status</label>
            <select class="form-control" [(ngModel)]="userFilter.status">
              <option value='' >All</option>

              <option value="submitted">Submitted</option>
              <option value="approved">Approved</option>
              <option value="cancel">Objection Claim</option>
              <option value="settled">Settled</option>
              <option value="rejected">Rejected</option>
              <option value="CLOSED">Closed</option>
              <option value="OUTSTANDING">Outstanding</option>

            </select>
          </div>
        </div>

        <div class="col-md-3" *ngIf="policyclaim">
          <div class="form-group">
           <label for="">Policy</label>
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getClaims()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>
         </div>
       </div>

        <div class="col-md-3" *ngIf="policysamad">
          <div class="form-group">
           <label for="">Policy</label>
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getSamad()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>
         </div>
       </div>

     </div>

     <table class="table table-responsive-md text-center">
      <thead>
        <tr>
          <th>STATUS</th>
          <th>Name</th>
          <th>Patient Name</th>
          <th>Approved Amount</th>
          <th>Claimed Amount</th>
          <th>Company</th>
          <th>Submitted By</th>
          <th>Claim No</th>
          <!-- <th>Website URL</th> -->

        </tr>
      </thead>
      <tbody *ngIf="data1">

        <tr *ngFor="let x of data1 | filterBy: userFilter" (click)="openDeal(deletecontent, x)" >

          <td>
            <span class="text-success" *ngIf="x.status == 'submitted'">Submitted</span>
            <span class="text-primary" *ngIf="x.status == 'settled'">Settled</span>
            <span class="text-warning" *ngIf="x.status == 'rejected'">Rejected</span>
            <span class="text-danger" *ngIf="x.status == 'Approved'">Approved</span>
            <span class="text-danger" *ngIf="x.status == 'ojection claim'">Objection claim</span>

          </td>
          <td >
            <div style="text-align: left;">
              <img [src]="x.userPhoto || 'https://mbtskoudsalg.com/images/user-image-png.png'" class="img-sm" alt="" style="text-align: left;">
              {{x.member_name}}
            </div>
          </td>
          <td style="text-align: left;">{{x.patient_name}}</td>
          <td>{{x.approved_value}}</td>
          <td>{{x.claimed_value}}</td>
          <td>

            <span  class="text-success" *ngIf="x.company_id == '999'" >Airlink Communication</span>
            <span class="text-success" *ngIf="x.company_id == '637'">Ascertia (Pvt) Ltd</span>
            <span *ngIf="x.company_id == '1053'" class="text-success">Frontier Works Organization</span>
            <span *ngIf="x.company_id == '1174'" class="text-success">Ebryx (pvt) Ltd</span>
            <span  *ngIf="x.company_id == '274'" class="text-success">HY Enterprises (Pvt) Limited</span>
            <span *ngIf="x.company_id == '459'" class="text-success">Naimat Saleem trust NST (US GROUP)</span>
            <span *ngIf="x.company_id == '659'" class="text-success">Samad Rubber Works (Pvt) Ltd</span>
            <span *ngIf="x.company_id == '56'" class="text-success">Sundry Clients</span>
            <span *ngIf="x.company_id == '620'" class="text-success">TIMEXPERTS (PRIVATE) Limited</span>
            <span *ngIf="x.company_id == '39'" class="text-success">US Apparel & Textile (Pvt) Limited</span>
            <span *ngIf="x.company_id == '40'" class="text-success">US Denim Mills (Pvt) Limited</span>

          </td>

          <td>{{x.submitted_at || 'not-defined'}}

          </td>
          <td>{{x.claim_no}}</td>

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

.ts

```<code>getClaims(){

this.policyclaim = true;

if(this.userFilter.company_id){
this.url = 'url='+this.userFilter.company_id;

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

  if (this.from && this.to) {
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));
    this.data1.filter(obj => new Date(obj.date) > fromDate && new Date(obj.date) < toDate);
    console.log(this.data1);
  }

else
{
this.url = 'url/get_claims.php?offset=0&limit=50';

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_claims_amt.php?cstatus=OUTSTANDING').subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url/get_claims_amt.php?cstatus=CLOSED').subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url/insurance-api/get_company_policy.php?').subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

this.clientData = this.httpClient.get<any>(this.url).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

if(this.userFilter.policy_id){

let vv = this.data1.filter(v => v.policy_id === this.userFilter.policy_id);
console.log(vv);

this.httpClient.get<any>('http://url='+this.userFilter.policy_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url='+this.userFilter.policy_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_company_policy.php?company_id='+this.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

this.url = 'url/get_claims.php?';

this.clientData = this.httpClient.get<any>(this.url,
{
params: {
policy_id: this.userFilter.policy_id
 },

}).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

});

//const sum1 = vv.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = vv.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = vv.filter((obj) => obj.status === status).length;
//var countunsettled = vv.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

}
//else{

//const sum1 = this.data1.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = this.data1.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = this.data1.filter((obj) => obj.status === status).length;
//var countunsettled = this.data1.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

//}

});

}
</code>```

答:
First transform your "data1" adding a propertie "date" that was a string of the date of the form YYYYmmdd. You can use this function to add a propertie: companyName and statusName to avoid yours *ngIf. I don't prove but can be like

```<code>companies=[{id:999,name:"Airlink Communication"},{id:637,name:"Ascertia (Pvt) Ltd"},..]

const months=[{month:"00",name:"ENE"},{month:"01",name:"FEB"}...]
dataFormated=data.map(x=>{
   const company=companies.find(c=>c.id==x.company_id);
   const status=x.status.substring(0,1).toUpperCase()+x.status.substr(1)
   const datepart=x.submitted_at.split('-');
   const date=''+datepart[2]+month.find(m=>m.name==datepart[1]).month+datepart[0]
   //date becomes, e.g. "180611" for x.submited_at "11-JUL-18"

   return
     {
         ...x,
         companyName:company?company.name:'',
         status:status
         date:date
     }
})
</code>```

Well, then you can filter using the new propertie "date" -is a string, you can use a filter or an if-

Updated the filter becomes like

```<code>if (this.from && this.to) {
    //first convert this.from and this.to to string of form YYmmdd
    //your'e using simply html input type date that return a string
    //I suggested you use mat-datepicker or ng-datepicker, but in your case
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));

    //see how convert a number in string with 2 digits using slice(-2),
    //e.g. ('0'+2).slice(-2) is "02"
    const fromDateTxt=''+(fromDate.getFullYear()%100)+
      ('0'+fromDate.getMonth()+1).slice(-2)+
      ('0'+fromDate.getDate()).slice(-2)

    const toDateTxt=''+(toDate.getFullYear()%100)+
      ('0'+toDate.getMonth()+1).slice(-2)+
      ('0'+toDate.getDate()).slice(-2)

    this.data1=dataFormated.filter(
          obj => obj.date >= fromDateTxt && obj.date< toDateTxt);
    console.log(this.data1);
}
</code>```

Title: Angular Filter by 2 dates

Body:
I need to add a Filter of the Date range. Mean I need to show only that data which user input from the date and to date. I have an array of data in which there is only one date is showing. But I want to filter it like this user input any 2 dates (From and To) And in the array I only that data show which are between input dates.

Claims Status

Claims Settled 23

Claims
(settled)

  {{statusunsettledcc}}

Claim Amount
(settled)

{{statusunsettledamount | number : fractionSize}}

Claims
(unsettled)

{{status2settledcc}}

Claim Amount
(unsettled)

{{status2settledamount | number : fractionSize}}

Claims

            Search Name

            <input type="text" class="form-control" [(ngModel)]="userFilter.member_name" placeholder="Search name" name="search">

            Search Claim No
            <input type="search"
            class="form-control" placeholder="Claim No" [(ngModel)]="userFilter.claim_no">

        <input type="date" class="form-control" [(ngModel)]="from"> //From date

        <input type="date" class="form-control" [(ngModel)]="to"> //To Date

            Company
            <select class="form-control" [(ngModel)]="userFilter.company_id" (change)="getClaims()">
              <option value='' >All</option>
              <option value="999">Airlink Communication</option>
              <option value="637">Ascertia (Pvt) Ltd</option>
              <option value="1053">Frontier Works Organization</option>
              <option value="1174">Ebryx (pvt) Ltd</option>
              <option value="274">HY Enterprises (Pvt) Limited</option>
              <option value="459">Naimat Saleem trust NST (US GROUP)</option>
              <option value="659">Samad Rubber Works (Pvt) Ltd</option>
              <option value="56">Sundry Clients</option>
              <option value="620">TIMEXPERTS (PRIVATE) Limited</option>
              <option value="39">US Apparel & Textile (Pvt) Limited</option>
              <option value="40">US Denim Mills (Pvt) Limited</option>
            </select>

            Claim Status
            <select class="form-control" [(ngModel)]="userFilter.status">
              <option value='' >All</option>

              <option value="submitted">Submitted</option>
              <option value="approved">Approved</option>
              <option value="cancel">Objection Claim</option>
              <option value="settled">Settled</option>
              <option value="rejected">Rejected</option>
              <option value="CLOSED">Closed</option>
              <option value="OUTSTANDING">Outstanding</option>

            </select>

           Policy
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getClaims()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>

           Policy
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getSamad()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>

          STATUS
          Name
          Patient Name
          Approved Amount
          Claimed Amount
          Company
          Submitted By
          Claim No

            Submitted
            Settled
            Rejected
            Approved
            Objection claim

              {{x.member_name}}

          {{x.patient_name}}
          {{x.approved_value}}
          {{x.claimed_value}}

            Airlink Communication
            Ascertia (Pvt) Ltd
            Frontier Works Organization
            Ebryx (pvt) Ltd
            HY Enterprises (Pvt) Limited
            Naimat Saleem trust NST (US GROUP)
            Samad Rubber Works (Pvt) Ltd
            Sundry Clients
            TIMEXPERTS (PRIVATE) Limited
            US Apparel & Textile (Pvt) Limited
            US Denim Mills (Pvt) Limited

          {{x.submitted_at || 'not-defined'}}

          {{x.claim_no}}

.ts

getClaims(){

this.policyclaim = true;

if(this.userFilter.company_id){
this.url = 'url='+this.userFilter.company_id;

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

  if (this.from && this.to) {
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));
    this.data1.filter(obj => new Date(obj.date) > fromDate && new Date(obj.date) < toDate);
    console.log(this.data1);
  }

else
{
this.url = 'url/get_claims.php?offset=0&limit=50';

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_claims_amt.php?cstatus=OUTSTANDING').subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url/get_claims_amt.php?cstatus=CLOSED').subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url/insurance-api/get_company_policy.php?').subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

this.clientData = this.httpClient.get<any>(this.url).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

if(this.userFilter.policy_id){

let vv = this.data1.filter(v => v.policy_id === this.userFilter.policy_id);
console.log(vv);

this.httpClient.get<any>('http://url='+this.userFilter.policy_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url='+this.userFilter.policy_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_company_policy.php?company_id='+this.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

this.url = 'url/get_claims.php?';

this.clientData = this.httpClient.get<any>(this.url,
{
params: {
policy_id: this.userFilter.policy_id
 },

}).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

});

//const sum1 = vv.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = vv.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = vv.filter((obj) => obj.status === status).length;
//var countunsettled = vv.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

}
//else{

//const sum1 = this.data1.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = this.data1.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = this.data1.filter((obj) => obj.status === status).length;
//var countunsettled = this.data1.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

//}

});

}

Body:
First transform your "data1" adding a propertie "date" that was a string of the date of the form YYYYmmdd. You can use this function to add a propertie: companyName and statusName to avoid yours *ngIf. I don't prove but can be like

companies=[{id:999,name:"Airlink Communication"},{id:637,name:"Ascertia (Pvt) Ltd"},..]

const months=[{month:"00",name:"ENE"},{month:"01",name:"FEB"}...]
dataFormated=data.map(x=>{
   const company=companies.find(c=>c.id==x.company_id);
   const status=x.status.substring(0,1).toUpperCase()+x.status.substr(1)
   const datepart=x.submitted_at.split('-');
   const date=''+datepart[2]+month.find(m=>m.name==datepart[1]).month+datepart[0]
   //date becomes, e.g. "180611" for x.submited_at "11-JUL-18"

   return
     {
         ...x,
         companyName:company?company.name:'',
         status:status
         date:date
     }
})

Well, then you can filter using the new propertie "date" -is a string, you can use a filter or an if-

Updated the filter becomes like

if (this.from && this.to) {
    //first convert this.from and this.to to string of form YYmmdd
    //your'e using simply html input type date that return a string
    //I suggested you use mat-datepicker or ng-datepicker, but in your case
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));

    //see how convert a number in string with 2 digits using slice(-2),
    //e.g. ('0'+2).slice(-2) is "02"
    const fromDateTxt=''+(fromDate.getFullYear()%100)+
      ('0'+fromDate.getMonth()+1).slice(-2)+
      ('0'+fromDate.getDate()).slice(-2)

    const toDateTxt=''+(toDate.getFullYear()%100)+
      ('0'+toDate.getMonth()+1).slice(-2)+
      ('0'+toDate.getDate()).slice(-2)

    this.data1=dataFormated.filter(
          obj => obj.date >= fromDateTxt && obj.date< toDateTxt);
    console.log(this.data1);
}


来源: stackexchange

问:
How can I use `git diff --color-words` outside a Git repository?
How can I get output like in  git diff --color-words, but outside Git?

Closest thing is wdiff  -t, but it underlines/inverts things instead of using green/red colours and does not allow specifying my whitespace regex.

答:
```<code>git diff --color-words --no-index old.txt new.txt
</code>```

ContentLicense: CC BY-SA 4.0


问:
Using Azure Key Vault and Active Directory to Retrieve Secrets
For a Python code base I would like to have developers accessing application secrets using Azure Key Vault, with the idea that when we deploy, the application also should be able to connect. Hence, I'm thinking Active Directory.

However, I can not find any examples on the interweb that show this with the Python SDK. Initially, I would think to retrieve the CLI user:

```<code>from azure.common.credentials import get_azure_cli_credentials

credentials, subscription_id, tenant_id = get_azure_cli_credentials(with_tenant=True)
</code>```

and then use this retrieved set of credentials to access the key vault:

```<code>from azure.keyvault import KeyVaultClient

vault_url = "https://########.vault.azure.net/"
secret_name = "########"
secret_version = "########"

client = KeyVaultClient(credentials)
secret = client.get_secret(vault_url, secret_name, secret_version)

print(secret)
</code>```

However, I retrieve an error that:

```<code>azure.keyvault.v7_0.models.key_vault_error_py3.KeyVaultErrorException: Operation returned an invalid status code 'Unauthorized'
</code>```

I can confirm that credentials, subscription_id and tenant_id are correct, and that using the CLI, I can succesfully retrieve the secret content. So it must be some Python SDK-specific thing.

Any ideas?

答:
It looks like this is a bug in the Python SDK.

https://github.com/Azure/azure-sdk-for-python/issues/5096

You can use your own AD username and password with the UserPassCredentials class. It's not the logged in user, but's it's probably as close as you'll get for now.

EG:

```<code>from azure.common.credentials import UserPassCredentials
credentials = UserPassCredentials('username','password')

client = KeyVaultClient(credentials)
secret = client.get_secret(vault_url, secret_name, secret_version)

print(secret)
</code>```

Body:
For a Python code base I would like to have developers accessing application secrets using Azure Key Vault, with the idea that when we deploy, the application also should be able to connect. Hence, I'm thinking Active Directory.

However, I can not find any examples on the interweb that show this with the Python SDK. Initially, I would think to retrieve the CLI user:

from azure.common.credentials import get_azure_cli_credentials

credentials, subscription_id, tenant_id = get_azure_cli_credentials(with_tenant=True)

and then use this retrieved set of credentials to access the key vault:

from azure.keyvault import KeyVaultClient

vault_url = "https://########.vault.azure.net/"
secret_name = "########"
secret_version = "########"

client = KeyVaultClient(credentials)
secret = client.get_secret(vault_url, secret_name, secret_version)

print(secret)

However, I retrieve an error that:

azure.keyvault.v7_0.models.key_vault_error_py3.KeyVaultErrorException: Operation returned an invalid status code 'Unauthorized'

I can confirm that credentials, subscription_id and tenant_id are correct, and that using the CLI, I can succesfully retrieve the secret content. So it must be some Python SDK-specific thing.

Any ideas?

Body:
It looks like this is a bug in the Python SDK.

https://github.com/Azure/azure-sdk-for-python/issues/5096

You can use your own AD username and password with the UserPassCredentials class. It's not the logged in user, but's it's probably as close as you'll get for now.

EG:

from azure.common.credentials import UserPassCredentials
credentials = UserPassCredentials('username','password')

client = KeyVaultClient(credentials)
secret = client.get_secret(vault_url, secret_name, secret_version)

print(secret)


问:
Docker-compose with Airflow - MS SQL Server (connection failed)
I´m not able to connect in the SQL Server inside Airflow using docker-compose. I want to take data from SQL Server direct to Cloud Storage and then the data will be sent to Big Query.

How to solve this?

```<code>import json
from datetime import timedelta, datetime

from airflow import DAG
from airflow.models import Variable
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
from airflow.contrib.operators.bigquery_check_operator import BigQueryCheckOperator
from airflow.contrib.operators.file_to_gcs import FileToGoogleCloudStorageOperator
from airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator
from airflow.contrib.operators.mysql_to_gcs import MySqlToGoogleCloudStorageOperator

default_args = {
    'owner': 'Test Data',
    'depends_on_past': True,
    'start_date': datetime(2019, 5, 29),
    'end_date': datetime(2019, 5, 30),
    'email': ['email@clientx.com.br'],
    'email_on_failure': True,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

# Set Schedule: Run pipeline once a day.
# Use cron to define exact time. Eg. 8:15am would be "15 08 * * *"
schedule_interval = "* * * * *"

# Define DAG: Set ID and assign default args and schedule interval
dag = DAG(
    'bigquery_github_trends',
    default_args=default_args,
    schedule_interval=schedule_interval
    )

extract = MySqlToGoogleCloudStorageOperator(
    task_id='chama_extract',
    mysql_conn_id='mysql_hml',
    google_cloud_storage_conn_id='my_gcp_conn',
    sql="""SELECT * FROM test""",
    bucket='my_bucket',
    filename='test/test{}.json',
    schema_filename='schemas/test.json',
    dag=dag)

load = GoogleCloudStorageToBigQueryOperator(
            task_id='chama_load',
            bigquery_conn_id='my_gcp_conn',
            google_cloud_storage_conn_id='my_gcp_conn',
            bucket='my_bucket',
            destination_project_dataset_table="tst.teste123",
            source_objects=['test/test0.json'],
            schema_object='schemas/test.json',
            source_format='NEWLINE_DELIMITED_JSON',
            create_disposition='CREATE_IF_NEEDED',
            write_disposition='WRITE_TRUNCATE',
            dag=dag)

# Setting up Dependencies
load.set_upstream(extract)
</code>```

Docker-compose.yml

version: '3'
services:
  postgres:
    image: postgres:9.6
    environment:
      - POSTGRES_USER=airflow
      - POSTGRES_PASSWORD=airflow
      - POSTGRES_DB=airflow
    ports:
      - "5432:5432"

  webserver:
    image: puckel/docker-airflow:1.10.1
    build:
      context: https://github.com/puckel/docker-airflow.git#1.10.1
      dockerfile: Dockerfile
      args:
        AIRFLOW_DEPS: gcp_api,s3
    restart: always
    depends_on:
      - postgres
    environment:
      - LOAD_EX=n
      - EXECUTOR=Local
      - FERNET_KEY=jsDPRErfv8Z_eVTnGfF8ywd19j4pyqE3NpdUBA_oRTo=
    volumes:
      - ./examples/intro-example/dags:/usr/local/airflow/dags
      # Uncomment to include custom plugins
      # - ./plugins:/usr/local/airflow/plugins
    ports:
      - "8080:8080"
    command: webserver
    healthcheck:
      test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
      interval: 30s
      timeout: 30s
      retries: 3```
</div>
</div>
</p>

<p>docker-compose-gcloud.yml
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>version: '3'
services:
  postgres:
    image: postgres:9.6
    environment:
      - POSTGRES_USER=airflow
      - POSTGRES_PASSWORD=airflow
      - POSTGRES_DB=airflow
    ports:
      - "5432:5432"

  webserver:
    image: puckel/docker-airflow:1.10.1
    build:
      context: https://github.com/puckel/docker-airflow.git#1.10.1
      dockerfile: Dockerfile
      args:
        AIRFLOW_DEPS: gcp_api,s3
    restart: always
    depends_on:
      - postgres
    environment:
      - LOAD_EX=n
      - EXECUTOR=Local
      - FERNET_KEY=jsDPRErfv8Z_eVTnGfF8ywd19j4pyqE3NpdUBA_oRTo=
    volumes:
      - ./examples/gcloud-example/dags:/usr/local/airflow/dags
      # Uncomment to include custom plugins
      # - ./plugins:/usr/local/airflow/plugins
    ports:
      - "8080:8080"
    command: webserver
    healthcheck:
      test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
      interval: 30s
      timeout: 30s
      retries: 3</code>```

And execute in docker the command:

docker-compose -f docker-compose-gcloud.yml up
  --abort-on-container-exit

Error message in Airflow:

[2019-05-29 07:00:37,938] {{logging_mixin.py:95}} INFO - [2019-05-29 07:00:37,937] {{base_hook.py:83}} INFO - Using connection to: 10.0.0.1
  [2019-05-29 07:00:58,974] {{models.py:1760}} ERROR - (2003, 'Can\'t connect to MySQL server on 10.0.0.1 (111 "Connection refused")')

  Traceback (most recent call last):

    File "/usr/local/lib/python3.6/site-packages/airflow/models.py", line 1659, in _run_raw_task

      result = task_copy.execute(context=context)

    File "/usr/local/lib/python3.6/site-packages/airflow/contrib/operators/mysql_to_gcs.py", line 105, in execute

      cursor = self._query_mysql()

    File "/usr/local/lib/python3.6/site-packages/airflow/contrib/operators/mysql_to_gcs.py", line 127, in _query_mysql

      conn = mysql.get_conn()

    File "/usr/local/lib/python3.6/site-packages/airflow/hooks/mysql_hook.py", line 103, in get_conn

      conn = MySQLdb.connect(**conn_config)

    File "/usr/local/lib/python3.6/site-packages/MySQLdb/init.py", line 84, in Connect

      return Connection(*args, **kwargs)

    File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 164, in init

      super(Connection, self).init(*args, **kwargs2)

  MySQLdb._exceptions.OperationalError: (2003, 'Can\'t connect to MySQL server on 10.0.0.1 (111 "Connection refused")')

  [2019-05-29 07:00:58,988] {{models.py:1789}} INFO - All retries failed; marking task as FAILED

  [2019-05-29 07:00:58,992] {{logging_mixin.py:95}} INFO - [2019-05-29 07:00:58,991] {{configuration.py:255}} WARNING - section/key [smtp/smtp_user] not found in config

  [2019-05-29 07:00:58,998] {{models.py:1796}} ERROR - [Errno 99] Cannot assign requested address

  Traceback (most recent call last):

    File "/usr/local/lib/python3.6/site-packages/airflow/models.py", line 1659, in _run_raw_task

      result = task_copy.execute(context=context)

    File "/usr/local/lib/python3.6/site-packages/airflow/contrib/operators/mysql_to_gcs.py", line 105, in execute

      cursor = self._query_mysql()

    File "/usr/local/lib/python3.6/site-packages/airflow/contrib/operators/mysql_to_gcs.py", line 127, in _query_mysql

      conn = mysql.get_conn()

    File "/usr/local/lib/python3.6/site-packages/airflow/hooks/mysql_hook.py", line 103, in get_conn

      conn = MySQLdb.connect(**conn_config)

    File "/usr/local/lib/python3.6/site-packages/MySQLdb/init.py", line 84, in Connect

      return Connection(*args, **kwargs)

    File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 164, in init

      super(Connection, self).init(*args, **kwargs2)

  MySQLdb._exceptions.OperationalError: (2003, 'Can\'t connect to MySQL server on 10.0.0.1 (111 "Connection refused")')

答:
From the error, the key part to me seems to be the "get_conn" piece. This indicates that when airflow is trying to establish the connection to the database it fails. This means either your connection is not specified (it looks like it might be) or that some part of it is incorrect.

You should check the password, server address, and port are all correct. These should be in either you airflow.cfg, as environment variables, or set in the webserver (Admin panel)

Body:
I´m not able to connect in the SQL Server inside Airflow using docker-compose. I want to take data from SQL Server direct to Cloud Storage and then the data will be sent to Big Query.

How to solve this?

import json
from datetime import timedelta, datetime

from airflow import DAG
from airflow.models import Variable
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
from airflow.contrib.operators.bigquery_check_operator import BigQueryCheckOperator
from airflow.contrib.operators.file_to_gcs import FileToGoogleCloudStorageOperator
from airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator
from airflow.contrib.operators.mysql_to_gcs import MySqlToGoogleCloudStorageOperator

default_args = {
    'owner': 'Test Data',
    'depends_on_past': True,
    'start_date': datetime(2019, 5, 29),
    'end_date': datetime(2019, 5, 30),
    'email': ['email@clientx.com.br'],
    'email_on_failure': True,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

# Set Schedule: Run pipeline once a day.
# Use cron to define exact time. Eg. 8:15am would be "15 08 * * *"
schedule_interval = "* * * * *"

# Define DAG: Set ID and assign default args and schedule interval
dag = DAG(
    'bigquery_github_trends',
    default_args=default_args,
    schedule_interval=schedule_interval
    )

extract = MySqlToGoogleCloudStorageOperator(
    task_id='chama_extract',
    mysql_conn_id='mysql_hml',
    google_cloud_storage_conn_id='my_gcp_conn',
    sql="""SELECT * FROM test""",
    bucket='my_bucket',
    filename='test/test{}.json',
    schema_filename='schemas/test.json',
    dag=dag)

load = GoogleCloudStorageToBigQueryOperator(
            task_id='chama_load',
            bigquery_conn_id='my_gcp_conn',
            google_cloud_storage_conn_id='my_gcp_conn',
            bucket='my_bucket',
            destination_project_dataset_table="tst.teste123",
            source_objects=['test/test0.json'],
            schema_object='schemas/test.json',
            source_format='NEWLINE_DELIMITED_JSON',
            create_disposition='CREATE_IF_NEEDED',
            write_disposition='WRITE_TRUNCATE',
            dag=dag)

# Setting up Dependencies
load.set_upstream(extract)

Docker-compose.yml

version: '3'
services:
  postgres:
    image: postgres:9.6
    environment:
      - POSTGRES_USER=airflow
      - POSTGRES_PASSWORD=airflow
      - POSTGRES_DB=airflow
    ports:
      - "5432:5432"

  webserver:
    image: puckel/docker-airflow:1.10.1
    build:
      context: https://github.com/puckel/docker-airflow.git#1.10.1
      dockerfile: Dockerfile
      args:
        AIRFLOW_DEPS: gcp_api,s3
    restart: always
    depends_on:
      - postgres
    environment:
      - LOAD_EX=n
      - EXECUTOR=Local
      - FERNET_KEY=jsDPRErfv8Z_eVTnGfF8ywd19j4pyqE3NpdUBA_oRTo=
    volumes:
      - ./examples/intro-example/dags:/usr/local/airflow/dags
      # Uncomment to include custom plugins
      # - ./plugins:/usr/local/airflow/plugins
    ports:
      - "8080:8080"
    command: webserver
    healthcheck:
      test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
      interval: 30s
      timeout: 30s
      retries: 3

docker-compose-gcloud.yml

version: '3'
services:
  postgres:
    image: postgres:9.6
    environment:
      - POSTGRES_USER=airflow
      - POSTGRES_PASSWORD=airflow
      - POSTGRES_DB=airflow
    ports:
      - "5432:5432"

  webserver:
    image: puckel/docker-airflow:1.10.1
    build:
      context: https://github.com/puckel/docker-airflow.git#1.10.1
      dockerfile: Dockerfile
      args:
        AIRFLOW_DEPS: gcp_api,s3
    restart: always
    depends_on:
      - postgres
    environment:
      - LOAD_EX=n
      - EXECUTOR=Local
      - FERNET_KEY=jsDPRErfv8Z_eVTnGfF8ywd19j4pyqE3NpdUBA_oRTo=
    volumes:
      - ./examples/gcloud-example/dags:/usr/local/airflow/dags
      # Uncomment to include custom plugins
      # - ./plugins:/usr/local/airflow/plugins
    ports:
      - "8080:8080"
    command: webserver
    healthcheck:
      test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
      interval: 30s
      timeout: 30s
      retries: 3

And execute in docker the command:

docker-compose -f docker-compose-gcloud.yml up
  --abort-on-container-exit

Error message in Airflow:

[2019-05-29 07:00:37,938] {{logging_mixin.py:95}} INFO - [2019-05-29 07:00:37,937] {{base_hook.py:83}} INFO - Using connection to: 10.0.0.1
  [2019-05-29 07:00:58,974] {{models.py:1760}} ERROR - (2003, 'Can\'t connect to MySQL server on 10.0.0.1 (111 "Connection refused")')

  Traceback (most recent call last):

    File "/usr/local/lib/python3.6/site-packages/airflow/models.py", line 1659, in _run_raw_task

      result = task_copy.execute(context=context)

    File "/usr/local/lib/python3.6/site-packages/airflow/contrib/operators/mysql_to_gcs.py", line 105, in execute

      cursor = self._query_mysql()

    File "/usr/local/lib/python3.6/site-packages/airflow/contrib/operators/mysql_to_gcs.py", line 127, in _query_mysql

      conn = mysql.get_conn()

    File "/usr/local/lib/python3.6/site-packages/airflow/hooks/mysql_hook.py", line 103, in get_conn

      conn = MySQLdb.connect(**conn_config)

    File "/usr/local/lib/python3.6/site-packages/MySQLdb/init.py", line 84, in Connect

      return Connection(*args, **kwargs)

    File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 164, in init

      super(Connection, self).init(*args, **kwargs2)

  MySQLdb._exceptions.OperationalError: (2003, 'Can\'t connect to MySQL server on 10.0.0.1 (111 "Connection refused")')

  [2019-05-29 07:00:58,988] {{models.py:1789}} INFO - All retries failed; marking task as FAILED

  [2019-05-29 07:00:58,992] {{logging_mixin.py:95}} INFO - [2019-05-29 07:00:58,991] {{configuration.py:255}} WARNING - section/key [smtp/smtp_user] not found in config

  [2019-05-29 07:00:58,998] {{models.py:1796}} ERROR - [Errno 99] Cannot assign requested address

  Traceback (most recent call last):

    File "/usr/local/lib/python3.6/site-packages/airflow/models.py", line 1659, in _run_raw_task

      result = task_copy.execute(context=context)

    File "/usr/local/lib/python3.6/site-packages/airflow/contrib/operators/mysql_to_gcs.py", line 105, in execute

      cursor = self._query_mysql()

    File "/usr/local/lib/python3.6/site-packages/airflow/contrib/operators/mysql_to_gcs.py", line 127, in _query_mysql

      conn = mysql.get_conn()

    File "/usr/local/lib/python3.6/site-packages/airflow/hooks/mysql_hook.py", line 103, in get_conn

      conn = MySQLdb.connect(**conn_config)

    File "/usr/local/lib/python3.6/site-packages/MySQLdb/init.py", line 84, in Connect

      return Connection(*args, **kwargs)

    File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 164, in init

      super(Connection, self).init(*args, **kwargs2)

  MySQLdb._exceptions.OperationalError: (2003, 'Can\'t connect to MySQL server on 10.0.0.1 (111 "Connection refused")')


问:
What is these twostep, checkblocked about in this middleware?
I am 2-week-old to Laravel. I am using 5.8. I've planned to take the project from (https://github.com/jeremykenedy/laravel-auth) for learning purpose. I use sublime to track the functionalities or keywords and to look how it's defined in src. I can't track some words anywhere in the file. Sorry in advance if this question was too dumb.</p>

```<code>Route::group(['middleware' => ['auth', 'activated', 'activity', 'twostep', 'checkblocked']], function () {

   //  Homepage Route - Redirect based on user role is in controller.
   Route::get('/home', ['as' => 'public.home',   'uses' => 'UserController@index']);

    // Show users profile - viewable by other users.
    Route::get('profile/{username}', [
     'as'   => '{username}',
    'uses' => 'ProfilesController@show',
    ]);
  });
</code>```

答:
It's just an array of middleware, hope you know about middlewares.
If not its just files where request goes first for chceking a particular conditions.

so now to your question ,  'twostep', 'checkblocked' are middleware where request goes to for a check before request to fullfill.

Hence, from variable name i can guess, These middleware is made for check , user on two-step verification(twostep) or not and second one, it checks, the user is blocked or not 'checkblocked',

If you wanna read these files code, you can go to kernal.php file inside app/http directory, and in this file, you can see an array named as $routeMiddleware, and track these files, inside middleware directory.

Update

Hence you did not get these files because user use these two packages for this.

for twostep user use this package you can find this package inside composer.json file in project directory "jeremykenedy/laravel2step": "^1.1",

and now for second checkblocked , he also uses package for this.

You can also view this package inside composer.json file "jeremykenedy/laravel-blocker": "^1.0", here is the link of package Package Link

Body:
I am 2-week-old to Laravel. I am using 5.8. I've planned to take the project from (https://github.com/jeremykenedy/laravel-auth) for learning purpose. I use sublime to track the functionalities or keywords and to look how it's defined in src. I can't track some words anywhere in the file. Sorry in advance if this question was too dumb.

Route::group(['middleware' => ['auth', 'activated', 'activity', 'twostep', 'checkblocked']], function () {

   //  Homepage Route - Redirect based on user role is in controller.
   Route::get('/home', ['as' => 'public.home',   'uses' => 'UserController@index']);

    // Show users profile - viewable by other users.
    Route::get('profile/{username}', [
     'as'   => '{username}',
    'uses' => 'ProfilesController@show',
    ]);
  });


问:
Use of eval keyword in Kotlin
What is use of eval() during safe cast and smart cast in kotlin?

Is it similar to eval() which we use in javascript, python or any other language?

答:
The eval() function is only available in Kotlin/JS , and simply calls the JavaScript eval() function.

This means you can't use it in code you might want to run on Kotlin/JVM or Kotlin/Native.

(Also, while I'm not familiar with Kotlin/JS, I'd imagine that could be quite powerful and also quite dangerous, so maybe caution is indicated…)

Title: Use of eval keyword in Kotlin


问:
Not able to access the Word Document on my system using the UWP application
I am trying to edit a existing Word document using the UWP app (Universal Windows). But for some reason I am getting "File does not exist" error.

I have tried using the below code to access the word document:

```<code>using(WordprocessingDocument wordDoc = WordprocessingDocument.Open("C:\\Users\\Public\\Desktop\\Doc1.docx", true))
{

}
</code>```

System.IO.FileNotFoundException: 'Could not find document'

答:
By default, the UWP doesn't allow to access the files outside the app container. But from windows 10 build 17134, a new capability broadFileSystemAccess has been introduced. It allows apps to get the same access to the file system as the user who is currently running the app without any additional file-picker style prompts during runtime.

So, please check if you have declare this capability in the 'Package.appxmanifest' file.

Please see File access permissions and broadFileSystemAccess entry in App capability declarations for more information.

If you still face this issue when you add the broadFileSystemAccess capability, then, the issue should be in 'WordprocessingDocument.Open' API. You need to note that 'File access permissions' document has mentioned:

This broadFileSystemAccess capability works for APIs in the Windows.Storage namespace.

This means that the 'WordprocessingDocument.Open' may not use the Windows.Storage APIs to access the files. If so, you need to report this issue to Open-XML-SDK.

Body:
I am trying to edit a existing Word document using the UWP app (Universal Windows). But for some reason I am getting "File does not exist" error.

I have tried using the below code to access the word document:

using(WordprocessingDocument wordDoc = WordprocessingDocument.Open("C:\\Users\\Public\\Desktop\\Doc1.docx", true))
{

}

System.IO.FileNotFoundException: 'Could not find document'


问:
How do I handle fuzzy lines in elixir gettext po files?
I'm fixing spelling and grammar errors in my Elixir project's output strings. I haven't worked with gettext before (other than making strings.)

When I run mix gettext.extract and then mix gettext.merge priv/gettext the first po file I examined has kept the old spelling mistake and added the correction at the bottom with the comment line:

#, elixir-format, fuzzy

Do I resolve this manually by deleting the old version of the string? What do I do with the comment on the corrected line? Should I delete the old string from the pot file manually? (That seems to make the process of fixing these mistakes really annoying. I would expect the old unused strings to go away.) With two lines in the file for the original string will the application use the correct translated string if there are two versions for the same line? Some of the msgids have the comment line about elixir-format, what is it doing for me?

答:
If a translation is automatically extracted (i.e. they have a #: before the msgid), then they will be automatically removed when we can no longer find an equivalent. This applies to both extract and merge commands. So if you rely on extract + merge and you don't change the .pot files manually, then it will always be handled for you.

The "fuzzy" bit can be safely removed, it is there only to show you that the original msgid changed and we "guessed" the translation based on the previous msgid.

The elixir-format bit is used by gettext editors, so they know which kind of syntax they should use for interpolation and the like.


问:
AWS Glue python shell job can call AWS glue spark job
I am new to AWS GLUE and just want to solve a particular problem. Currently i have only Glue service available only and no EC2 node no lambda.
I am trying to run a AWS spark glue job from Aws python shell glue job . is that possible to run a AWS glue python shell job as a wrapper and call multiple time the same AWS glue spark job with different parameters.
I tried to run the below code snipet but getting boto Ecxeption error in logs.

```<code>import boto3
glue = boto3.client(service_name='glue', region_name='us-east-1',
              endpoint_url='https://glue.us-east-1.amazonaws.com')
myNewJobRun = glue.start_job_run(JobName='WHICH I CREATED IN CONSOLE')
</code>```

In the above code i have already created a job in console and wants to hit the job from AWS python shell glue job.

Below i want to get the status of job if it is running then it will wait for some time and then again check the status.

```<code>status = glue.get_job_run(JobName=myJob['Name'], RunId=JobRun['JobRunId'])
</code>```

Can someone advice for share any code sample for reference

Thanks
Pradeep

答:
What is error?

You may have to add arguments to start_job_run()

response = glue.start_job_run(
                      JobName=jobName, Arguments=arguments, AllocatedCapacity=dpus)

status = glue.get_job_run(JobName=jobName,
                                               RunId=response['JobRunId'])

Body:
I am new to AWS GLUE and just want to solve a particular problem. Currently i have only Glue service available only and no EC2 node no lambda.
I am trying to run a AWS spark glue job from Aws python shell glue job . is that possible to run a AWS glue python shell job as a wrapper and call multiple time the same AWS glue spark job with different parameters.
I tried to run the below code snipet but getting boto Ecxeption error in logs.

import boto3
glue = boto3.client(service_name='glue', region_name='us-east-1',
              endpoint_url='https://glue.us-east-1.amazonaws.com')
myNewJobRun = glue.start_job_run(JobName='WHICH I CREATED IN CONSOLE')

In the above code i have already created a job in console and wants to hit the job from AWS python shell glue job.

Below i want to get the status of job if it is running then it will wait for some time and then again check the status.

status = glue.get_job_run(JobName=myJob['Name'], RunId=JobRun['JobRunId'])

Can someone advice for share any code sample for reference

Thanks
Pradeep


问:
Firefox: CSS: change style when button focused
It is possible to remove the extra Firefox-specific spacing from <button> tags. The only drawback is that the outline will be missing when you focus to the button on your keyboard.

I would very much like to make my buttons consistent across Chrome, IE8, Firefox. If I could use a CSS :hover, I could easily show the button as focused using the same style that removes that Firefox spacing and outline.

Is there any way to do this without JavaScript? I do not care if other browsers ignore the rule. In fact I would prefer a :-moz-focused if there is such a thing so I can be sure that it won't happen in the other browsers.

Also, if a Chrome style outer glow could be accomplished in Firefox, that would be twice as good.

答: CSS has the :focus selector for this purpose, which works like :hover, but applies to the element that has focus. There doesn’t seem to be a Firefox-specific version.

ContentLicense: CC BY-SA 3.0


问:
Getting OAuth tokens for Azure DevOps API consumption
I have a web app written in Angular 7. I'm trying to consume Azure DevOps APIs and I understand that I have to setup an Azure Active Directory App. I have tried few libraries like adal-angular msal-angular and wrappers like microsoft-adal-angular6. Followed their documentations and samples. I can successfully access the User's name, emails and a token. I can use the token for Microsoft Graph apis but not for Azure DevOps apis. I tried using this token as a Authentication Bearer for my HttpClient however I'm getting Status Code 203.

Then I found this answer and I think this is the missing part that I need but its for dotNet.

The API Im cosuming: https://app.vssps.visualstudio.com/_apis/accounts

Q:

What is the token Im getting?

How can I get the appropriate token using Angular 7?

What libraries do I need?

答:
I used @azure/msal-angular. I got the azure dev ops token using acquireTokenSilent(['499b84ac-1321-427f-aa17-267ca6975798/.default']). If it fails, I used the acquireTokenRedirect(['499b84ac-1321-427f-aa17-267ca6975798/.default'])

access token can be retrieved via getCachedTokenInternal([499b84ac-1321-427f-aa17-267ca6975798/.default])


问:
How to set to object parallel in Html
I am making two sign-up forms using html and CSS Bootstrap. I want the two forms to be in parallel and for the second i am using the  position tag of html but without success because even if i the forms are parallel there seems to be created not needed space.
the output
Is there a way to prevent that space which i circled not to be created?

```<code>          <main class="my-form">
                   <div class="container">
    <div class="row justify-content-flex-start">
        <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Apliko</div>
                    <div class="card-body">
                        <form name="my-form" onsubmit="return validform()" action="success.php" method="">
                            <div class="form-group row">
                                <label for="full_name" class="col-md-3 col-form-label text-md-right">Emri juaj:</label>
                                <div class="col-md-6">
                                    <input type="text" id="emri" class="form-control" name="emri">
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="email_address" class="col-md-3 col-form-label text-md-right">Adresa Email:</label>
                                <div class="col-md-6">
                                    <input type="text" id="email_address" class="form-control" name="email-address">
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="user_name" class="col-md-3 col-form-label text-md-right">Subjekti:</label>
                                <div class="col-md-6">
                                    <input type="text" id="subjekti" class="form-control" name="subjekti">
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="phone_number" class="col-md-3 col-form-label text-md-right">Mesazhi:</label>
                                <div class="col-md-6">
                                    <input type="text" id="mesazhi" class="form-control">
                                </div>
                            </div>
                             <div class="form-group row">
                                <label for="phone_number" class="col-md-3 col-form-label text-md-right">CV-ja juaj:</label>
                                <div class="col-md-6">
                                    <input type="file">
                                </div>
                            </div>

                                <div class="col-md-6 offset-md-3">
                                    <button type="button" class="btn btn-primary" onClick="myFunction(), location.href = 'index.html'">
                                    Register
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
        </div>
    </div>
</div>
</code>```

This was the first form. I started the second one like this.

```<code>     <main  style="position:sticky; left:680px; top:2px; width:900px; ">
    <div class="container">
    <div class="row justify-content-flex-end">
        <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Rregjistrohu si
          perdorues</div>
                    <div class="card-body">
                        <form name="my-form" onsubmit="return validform()" action="success.php" method="">
                            <div class="form-group row">
                                <label for="full_name" class="col-md-4 col-form-label text-md-right">Emer Mbiemer:</label>
                                <div class="col-md-6">
                                    <input type="text" id="full_name" class="form-control" name="full-name">
                                </div>
                            </div>
</code>```

答:
It seems to be manual width issue.
Horizontal scroll is due to excess manual width.
As you are using Bootstrap framework, it already gives you flexibility, So try to avoid defining manual width.
I have simplified the code structure.

Simplified Form Structure - Snippet

Hope so this will resolve your issue.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.css">

Heading

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nulla qui quisquam sit harum labore iusto cum, temporibus est soluta voluptatibus! Fugiat doloremque facere suscipit porro dolore odio harum vero at!

Profile

                            <form>

                                    Name:

                                        <input type="text" id="emri" class="form-control" name="emri">

                                    Email ID:

                                        <input type="text" id="email_address" class="form-control" name="email-address">

                                    Subject:

                                        <input type="text" id="subjekti" class="form-control" name="subjekti">

                                    Address:

                                        <input type="text" id="mesazhi" class="form-control">

                                    Updated CV:

                                        <input type="file">

                                    <button type="button" class="btn btn-primary" onClick="myFunction(), location.href = 'index.html'">
                                        Register
                                    </button>

                        </form>

Profile

                            <form>

                                    Name:

                                        <input type="text" id="emri" class="form-control" name="emri">

                                    Email ID:

                                        <input type="text" id="email_address" class="form-control" name="email-address">

                                    Subject:

                                        <input type="text" id="subjekti" class="form-control" name="subjekti">

                                    Address:

                                        <input type="text" id="mesazhi" class="form-control">

                                    New Field-1:

                                        <input type="text" id="mesazhi" class="form-control">

                                    New Field-2:

                                        <input type="text" id="mesazhi" class="form-control">

                                    Updated CV:

                                        <input type="file">

                                    <button type="button" class="btn btn-primary" onClick="myFunction(), location.href = 'index.html'">
                                        Register
                                    </button>

                        </form>

    ```

Title: How to set to object parallel in Html

Body:
I am making two sign-up forms using html and CSS Bootstrap. I want the two forms to be in parallel and for the second i am using the  position tag of html but without success because even if i the forms are parallel there seems to be created not needed space.
the output
Is there a way to prevent that space which i circled not to be created?

Apliko

                        <form name="my-form" onsubmit="return validform()" action="success.php" method="">

                                Emri juaj:

                                    <input type="text" id="emri" class="form-control" name="emri">

                                Adresa Email:

                                    <input type="text" id="email_address" class="form-control" name="email-address">

                                Subjekti:

                                    <input type="text" id="subjekti" class="form-control" name="subjekti">

                                Mesazhi:

                                    <input type="text" id="mesazhi" class="form-control">

                                CV-ja juaj:

                                    <input type="file">

                                    <button type="button" class="btn btn-primary" onClick="myFunction(), location.href = 'index.html'">
                                    Register
                                    </button>

                        </form>

This was the first form. I started the second one like this.

Rregjistrohu si
          perdorues

                        <form name="my-form" onsubmit="return validform()" action="success.php" method="">

                                Emer Mbiemer:

                                    <input type="text" id="full_name" class="form-control" name="full-name">

Body:
It seems to be manual width issue.
Horizontal scroll is due to excess manual width.
As you are using Bootstrap framework, it already gives you flexibility, So try to avoid defining manual width.
I have simplified the code structure.

Simplified Form Structure - Snippet

Hope so this will resolve your issue.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.css">
<main>
        <div class="bg-light py-3 mb-4">
            <div class="container">
                <h2>Heading</h2>
                <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nulla qui quisquam sit harum labore iusto cum, temporibus est soluta voluptatibus! Fugiat doloremque facere suscipit porro dolore odio harum vero at!</p>
            </div>
        </div>
        <div class="container">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <div class="card">
                        <div class="card-header">Profile</div>
                        <div class="card-body">
                            <form>
                                <div class="form-group row">
                                    <label for="full_name" class="col-md-3 col-form-label text-md-right">Name:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="emri" class="form-control" name="emri">
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label for="email_address" class="col-md-3 col-form-label text-md-right">Email ID:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="email_address" class="form-control" name="email-address">
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label for="user_name" class="col-md-3 col-form-label text-md-right">Subject:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="subjekti" class="form-control" name="subjekti">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="phone_number" class="col-md-3 col-form-label text-md-right">Address:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="mesazhi" class="form-control">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="phone_number" class="col-md-3 col-form-label text-md-right">Updated CV:</label>
                                    <div class="col-md-6">
                                        <input type="file">
                                    </div>
                                </div>
                                <div class="col-md-6 offset-md-3">
                                    <button type="button" class="btn btn-primary" onClick="myFunction(), location.href = 'index.html'">
                                        Register
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <!-- col-md-6 -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">Profile</div>
                        <div class="card-body">
                            <form>
                                <div class="form-group row">
                                    <label for="full_name" class="col-md-3 col-form-label text-md-right">Name:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="emri" class="form-control" name="emri">
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label for="email_address" class="col-md-3 col-form-label text-md-right">Email ID:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="email_address" class="form-control" name="email-address">
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label for="user_name" class="col-md-3 col-form-label text-md-right">Subject:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="subjekti" class="form-control" name="subjekti">
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label for="phone_number" class="col-md-3 col-form-label text-md-right">Address:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="mesazhi" class="form-control">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="phone_number" class="col-md-3 col-form-label text-md-right">New Field-1:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="mesazhi" class="form-control">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="phone_number" class="col-md-3 col-form-label text-md-right">New Field-2:</label>
                                    <div class="col-md-6">
                                        <input type="text" id="mesazhi" class="form-control">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="phone_number" class="col-md-3 col-form-label text-md-right">Updated CV:</label>
                                    <div class="col-md-6">
                                        <input type="file">
                                    </div>
                                </div>
                                <div class="col-md-6 offset-md-3">
                                    <button type="button" class="btn btn-primary" onClick="myFunction(), location.href = 'index.html'">
                                        Register
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <!-- col-md-6 -->
            </div>
            <!-- row -->
        </div>
        <!-- container -->
    </main>


问:
Save Canvas on disk from clients browser?
With node-canvas (https://github.com/learnboost/node-canvas) we can save Canvas on disk.

How can we access Canvas element on client's side from Node.js server?

Client connects to Node.js server

Server serves response. Client draws on Canvas

Client clicks "save" and SERVER saves this Canvas to server's disk.

Possible?

答: You can get the canvas data by calling var data = canvas.toDataUrl(); This creates a data url that you could then send back to the server to save. Check out 4.8.11 The canvas element. There are a few different options you can pass along to the toDataUrl function to vary the output.


问:
how to manual link npm package 'react native reanimated'
Can anyone please tell me how to manual link

react-native-reanimated

because the automatic cli linking not working and crashing react native app

答:
In Android,Add the following lines to android/settings.gradle

include ':react-native-reanimated'
project(':react-native-reanimated').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-reanimated/android')

Add the compile line to the dependencies in android/app/build.gradle

implementation project(':react-native-reanimated')

the import and link the package in MainApplication.java

import com.swmansion.reanimated.ReanimatedPackage;

```<code>protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
         new ReanimatedPackage(), );// <-- add this line
}
}
</code>```

in android/build.gradle

```<code>ext {
compileSdkVersion           = 25
targetSdkVersion            = 25
buildToolsVersion           = "25.0.2"
googlePlayServicesVersion   = "12.0.1"
supportLibVersion           = "27.0.0"
 }
</code>```

Body:
In Android,Add the following lines to android/settings.gradle

include ':react-native-reanimated'
project(':react-native-reanimated').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-reanimated/android')

Add the compile line to the dependencies in android/app/build.gradle

implementation project(':react-native-reanimated')

the import and link the package in MainApplication.java

import com.swmansion.reanimated.ReanimatedPackage;

protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
         new ReanimatedPackage(), );// <-- add this line
}
}

in android/build.gradle

ext {
compileSdkVersion           = 25
targetSdkVersion            = 25
buildToolsVersion           = "25.0.2"
googlePlayServicesVersion   = "12.0.1"
supportLibVersion           = "27.0.0"
 }


问:
Concept of vert.x concerning a webserver?
I don't quite get how vert.x is applied for a webserver.

The concept I know for webserver is the thread-based one.

You start your webserver, which then is running.

Then for every client that connects, you get a socket, which is then passed to its own thread handler.

The thread handler then processes the tasks for this specific socket.

So it is clearly defined which thread is doing the work for which socket.
However for every socket you need a new thread, which is expensive in the long run for many sockets.

Then there is the event-based concept that vert.x supplies.
So far I have understood, it should work anyhow like this:

The Vertx instance deploys Verticles.

Verticles run in background threads, but not every Verticle has its own thread. As an example there could be 1000 verticles deployed in a Vertx instance, but the Vertx instance handles only 8 threads (nr of cores * 2).

Then there are the event loops. I'm not sure how they refer to verticles. I've read that every verticle has 2 event loops, but don't really know how that works.

As a webserver example:

```<code>class WebServer: AbstractVerticle() {
    lateinit var server: HttpServer

    override fun start() {
        server = vertx.createHttpServer(HttpServerOptions().setPort(1234).setHost("localhost"))
        var router = Router.router(vertx);
        router.route("/test").handler { routingContext ->
            var response = routingContext.response();
            response.end("Hello from my first HttpServer")
        }
        server.requestHandler(router).listen()
    }
}
</code>```

This WebServer can be deployed multiple times in a Vertx instance. And as it seems, each WebServer instance gets its own thread. When I try to connect 100 Clients and reply with a simple response, it seems like each Client is handled synchronously. Because when I do a Thread.sleep statement in each server handler, then the every second one client gets a response. However it should be that all server handlers should start their 1 second sleep and then almost identically reply to all clients after this time.

This is the code to start 100 clients:

```<code>fun main(){
    Vertx.vertx().deployVerticle(object : AbstractVerticle(){
        override fun start() {
            for(i in 0 .. 100)
                MyWebClient(vertx)
        }
    })
}

class MyWebClient(val vertx: Vertx) {
    init {
        println("Client starting ...")
        val webClient = WebClient.create(vertx, WebClientOptions().setDefaultPort(1234).setDefaultHost("localhost"))
        webClient.get("/test").send { ar ->
            if(ar.succeeded()){
                val response: HttpResponse<Buffer> = ar.result()

                println("Received response with status code ${response.statusCode()} + ${response.body()}")
            } else {
                println("Something went wrong " + ar.cause().message)
            }
        }
    }
}
</code>```

Does anybody know an explanation for this?

答:
There are some major issues there.

When you do this:

```<code>class WebServer: AbstractVerticle() {
    lateinit var server: HttpServer

    override fun start() {
        server = vertx.createHttpServer(HttpServerOptions().setPort(1234).setHost("localhost"))
       ...
    }
}
</code>```

Then something like this:

```<code>vertx.deployVerticle(WebServer::class.java.name, DeploymentOptions().setInstances(4)
</code>```

You'll get 4 verticles, but only single one of them will actually listen on the port. So, you're not getting any more concurrency.

Second, when you use Thread.sleep in your Vert.x code, you're blocking the event loop thread.

Third, your test with client is incorrect. Creation of a WebClient is very expensive, so by creating those one after the other, you're actually issuing requests very slowly. If you really want to test your web application, use something like https://github.com/wg/wrk

Body:
I don't quite get how vert.x is applied for a webserver.

The concept I know for webserver is the thread-based one.

You start your webserver, which then is running.

Then for every client that connects, you get a socket, which is then passed to its own thread handler.

The thread handler then processes the tasks for this specific socket.

So it is clearly defined which thread is doing the work for which socket.
However for every socket you need a new thread, which is expensive in the long run for many sockets.

Then there is the event-based concept that vert.x supplies.
So far I have understood, it should work anyhow like this:

The Vertx instance deploys Verticles.

Verticles run in background threads, but not every Verticle has its own thread. As an example there could be 1000 verticles deployed in a Vertx instance, but the Vertx instance handles only 8 threads (nr of cores * 2).

Then there are the event loops. I'm not sure how they refer to verticles. I've read that every verticle has 2 event loops, but don't really know how that works.

As a webserver example:

class WebServer: AbstractVerticle() {
    lateinit var server: HttpServer

    override fun start() {
        server = vertx.createHttpServer(HttpServerOptions().setPort(1234).setHost("localhost"))
        var router = Router.router(vertx);
        router.route("/test").handler { routingContext ->
            var response = routingContext.response();
            response.end("Hello from my first HttpServer")
        }
        server.requestHandler(router).listen()
    }
}

This WebServer can be deployed multiple times in a Vertx instance. And as it seems, each WebServer instance gets its own thread. When I try to connect 100 Clients and reply with a simple response, it seems like each Client is handled synchronously. Because when I do a Thread.sleep statement in each server handler, then the every second one client gets a response. However it should be that all server handlers should start their 1 second sleep and then almost identically reply to all clients after this time.

This is the code to start 100 clients:

fun main(){
    Vertx.vertx().deployVerticle(object : AbstractVerticle(){
        override fun start() {
            for(i in 0 .. 100)
                MyWebClient(vertx)
        }
    })
}

class MyWebClient(val vertx: Vertx) {
    init {
        println("Client starting ...")
        val webClient = WebClient.create(vertx, WebClientOptions().setDefaultPort(1234).setDefaultHost("localhost"))
        webClient.get("/test").send { ar ->
            if(ar.succeeded()){
                val response: HttpResponse<Buffer> = ar.result()

                println("Received response with status code ${response.statusCode()} + ${response.body()}")
            } else {
                println("Something went wrong " + ar.cause().message)
            }
        }
    }
}

Does anybody know an explanation for this?

Body:
There are some major issues there.

When you do this:

class WebServer: AbstractVerticle() {
    lateinit var server: HttpServer

    override fun start() {
        server = vertx.createHttpServer(HttpServerOptions().setPort(1234).setHost("localhost"))
       ...
    }
}

Then something like this:

vertx.deployVerticle(WebServer::class.java.name, DeploymentOptions().setInstances(4)

You'll get 4 verticles, but only single one of them will actually listen on the port. So, you're not getting any more concurrency.

Second, when you use Thread.sleep in your Vert.x code, you're blocking the event loop thread.

Third, your test with client is incorrect. Creation of a WebClient is very expensive, so by creating those one after the other, you're actually issuing requests very slowly. If you really want to test your web application, use something like https://github.com/wg/wrk


问:
how to list person's post in his profile activity
I am building a social app using firebase , when it comes to profile activity and I want to post only person's post I can't ,I managed to post all users post to the home page as news feed but I can't filter only users posts , this is the users node with the person id as a child

i tried this

```<code>   userRef=FirebaseDatabase.getInstance().getReference().child("Users");
RecieverId=getIntent().getExtras().get("brand_id").toString();

 private void DisplayAllOffers() {
        FirebaseRecyclerOptions<Posts> options = new FirebaseRecyclerOptions.Builder<Posts>()
                .setQuery(PostRef.child(RecieverId),Posts.class).build();

        FirebaseRecyclerAdapter<Posts,PostViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Posts, PostViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull  PostViewHolder holder, int position, @NonNull Posts model) {
//                holder.Title.setText(model.getTitle());
                final  String postKey = getRef(position).getKey();
                holder.Price.setText(model.getPrice());
                holder.Duration.setText(model.getDuration());
                holder.date.setText(model.getDate());
                holder.description.setText(model.getDescription());
                holder.time.setText(model.getTime());
                holder.username.setText(model.getUsername());
                holder.setLikeButtonStatus(postKey);
                Picasso.get().load(model.getProfileImage()).into(holder.ProfileImage);
                Picasso.get().load(model.getPostImage()).into(holder.postImage);

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent postIntent = new Intent(BrandActivity.this,ClickPostActivity.class);
                        postIntent.putExtra("postKey",postKey);
                        startActivity(postIntent);
                    }
                });

            }

            @NonNull
            @Override
            public PostViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

                View view =LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.offer_layout,viewGroup,false);
                PostViewHolder holder =new PostViewHolder(view);
                return holder;

            }
        };
        Profile_posts.setAdapter(firebaseRecyclerAdapter);
        firebaseRecyclerAdapter.startListening();

    }
</code>```

and it returns an empty recyclerview

答:
If you want to user-specific post than you have to change your options with

```<code>FirebaseRecyclerOptions<Posts> options = new FirebaseRecyclerOptions.Builder<Posts>().setQuery(PostRef.orderByChild("Uid").equalTo(FirebaseAuth.getInstance().getUid())),Posts.class).build();
</code>```

here this PostRef.orderByChild("Uid").equalTo(FirebaseAuth.getInstance().getUid()) query filter curent user post

you also can get other than the current user specific post, all you have to do only change FirebaseAuth.getInstance().getUid() to user id in equalTo function

Body:
I am building a social app using firebase , when it comes to profile activity and I want to post only person's post I can't ,I managed to post all users post to the home page as news feed but I can't filter only users posts , this is the users node with the person id as a child

i tried this

   userRef=FirebaseDatabase.getInstance().getReference().child("Users");
RecieverId=getIntent().getExtras().get("brand_id").toString();

 private void DisplayAllOffers() {
        FirebaseRecyclerOptions<Posts> options = new FirebaseRecyclerOptions.Builder<Posts>()
                .setQuery(PostRef.child(RecieverId),Posts.class).build();

        FirebaseRecyclerAdapter<Posts,PostViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Posts, PostViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull  PostViewHolder holder, int position, @NonNull Posts model) {
//                holder.Title.setText(model.getTitle());
                final  String postKey = getRef(position).getKey();
                holder.Price.setText(model.getPrice());
                holder.Duration.setText(model.getDuration());
                holder.date.setText(model.getDate());
                holder.description.setText(model.getDescription());
                holder.time.setText(model.getTime());
                holder.username.setText(model.getUsername());
                holder.setLikeButtonStatus(postKey);
                Picasso.get().load(model.getProfileImage()).into(holder.ProfileImage);
                Picasso.get().load(model.getPostImage()).into(holder.postImage);

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent postIntent = new Intent(BrandActivity.this,ClickPostActivity.class);
                        postIntent.putExtra("postKey",postKey);
                        startActivity(postIntent);
                    }
                });

            }

            @NonNull
            @Override
            public PostViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

                View view =LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.offer_layout,viewGroup,false);
                PostViewHolder holder =new PostViewHolder(view);
                return holder;

            }
        };
        Profile_posts.setAdapter(firebaseRecyclerAdapter);
        firebaseRecyclerAdapter.startListening();

    }

and it returns an empty recyclerview

Body:
If you want to user-specific post than you have to change your options with

FirebaseRecyclerOptions<Posts> options = new FirebaseRecyclerOptions.Builder<Posts>().setQuery(PostRef.orderByChild("Uid").equalTo(FirebaseAuth.getInstance().getUid())),Posts.class).build();

here this PostRef.orderByChild("Uid").equalTo(FirebaseAuth.getInstance().getUid()) query filter curent user post

you also can get other than the current user specific post, all you have to do only change FirebaseAuth.getInstance().getUid() to user id in equalTo function


问:
How to implement/show following pop-over above textField?
I m trying to implement following functionality in my iOS project.
Here is the screen,

If user do not enter anything or entered wrong data in email and mobile textFields, I want to show like this.

Case 1: If user didn't entered the email or entered incorrect email then it will show an message/view with "Enter valid Email Address"

Case 2: If user didn't entered the mobile number or entered incorrect mobile number then it will show an message/view with "Enter valid Mobile Number"

How to achieve this using swift?

答: You could create a view on top of them and set it hidden, and when the email is wrong. You could unhide the view.


问:
Cron Job doesn't trigger with TimeZone
I've been doing some test with cron jobs with timezones.
My goal is to setup 1 cron job per timezone so it can be run independently of the server location.

```<code>package main

import (
    "fmt"
    "github.com/robfig/cron"
    "os"
    "os/signal"
    "time"
)

func helloWorld() {
  fmt.Println("hello world")
}

func main() {
    s, err1 := cron.Parse("26 15 * * *")
    fmt.Println(err1)
    l, err := time.LoadLocation("Asia/Tokyo")
    fmt.Println(err)
    c := cron.NewWithLocation(l)
    c.Schedule(s, cron.FuncJob(helloWorld))
    c.Start()

    sig := make(chan os.Signal)
    signal.Notify(sig, os.Interrupt, os.Kill)
    <-sig
}
</code>```

Here i'm just trying to make a test. I expect to see helloWorld at 15:26 Tokyo time. ( 3:26PM )

The sig snippet is something i've found on stack overflow for testing purposes so that the program doesn't close before the cron job has time to run.

I'm always setting up the time 1 or 2 minutes ahead and it's never working.
any idea why ?

答: I was an error of the cron formula "26 15 * * *"  should have been "00 26 15 * *"

Title: Cron Job doesn't trigger with TimeZone

Body:
I've been doing some test with cron jobs with timezones.
My goal is to setup 1 cron job per timezone so it can be run independently of the server location.

package main

import (
    "fmt"
    "github.com/robfig/cron"
    "os"
    "os/signal"
    "time"
)

func helloWorld() {
  fmt.Println("hello world")
}

func main() {
    s, err1 := cron.Parse("26 15 * * *")
    fmt.Println(err1)
    l, err := time.LoadLocation("Asia/Tokyo")
    fmt.Println(err)
    c := cron.NewWithLocation(l)
    c.Schedule(s, cron.FuncJob(helloWorld))
    c.Start()

    sig := make(chan os.Signal)
    signal.Notify(sig, os.Interrupt, os.Kill)
    <-sig
}

Here i'm just trying to make a test. I expect to see helloWorld at 15:26 Tokyo time. ( 3:26PM )

The sig snippet is something i've found on stack overflow for testing purposes so that the program doesn't close before the cron job has time to run.

I'm always setting up the time 1 or 2 minutes ahead and it's never working.
any idea why ?