问:
How to use *ngIf for async http.get data request - Angular 2
I have a web application that is retrieving data from multiple api and is supposed to use the data into some charts. The problem is that when the charts get rendered the data from the api are not in yet. I tried using .then() method but it tells me that property then does not exist on type void. Furthermore I tried using the ngIf method, following this answer, but is not working either. Do you know how could I solve this please?

Below are my component and my component template.

app.component.ts

```<code>import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mimesi dashboard graphs';

  //COUNTS
  public countIndexerMetaApi; //array of one number populated from http.get
  public countIndexerMetaNumber; //number extracted into array and stored as an int
  public countIndexerMetaArray; //array to store countNumber afterwards

  public countIndexerServedApi;
  public countIndexerServedNumber;
  public countIndexerServedArray;

  public countRealTimeServedApi;
  public countRealTimeServedNumber;
  public countRealTimeServedArray;

  //DATES
  public dateIndexerMetaToStore; //date got from moment method that needs to be stored
  public dateIndexerMetaArray; //array to store dates for graph label

  public dateIndexerServedToStore;
  public dateIndexerServedArray;

  public dateRealTimeServedToStore;
  public dateRealTimeServedArray;

  //API LINKS
  private apiCountIndexerMetaUrl: string = 'http://localhost:3000/api/countIndexerMetaApi';
  /*      TODO - API FOR COUNT OF OTHER TWO TABLES      */
  private apiCountIndexerServedUrl: string = 'http://localhost:3000/api/countIndexerServedApi';
  private apiCountRealTimeServedUrl: string = 'http://localhost:3000/api/countRealTimeServedApi';

  //VARIABLE FOR TIMEOUT
  public isDataAvailable:boolean = false;

  constructor(private http:Http) {
    let now = moment.locale("it");

    //COUNT
    this.countIndexerMetaApi = 0;
    this.countIndexerMetaNumber = 0;
    this.countIndexerMetaArray = [];

    this.countIndexerServedApi = 0;
    this.countIndexerServedNumber = 0;
    this.countIndexerServedArray = []

    this.countRealTimeServedApi = 0;
    this.countRealTimeServedNumber = 0;
    this.countRealTimeServedArray = []

    //DATES
    this.dateIndexerMetaToStore = "";
    this.dateIndexerMetaArray = [];

    this.dateIndexerServedToStore = "";
    this.dateIndexerServedArray = [];

    this.dateRealTimeServedToStore = "";
    this.dateRealTimeServedArray = [];
  }

  ngOnInit() {
    this.getIndexerMetaCount();
    this.getIndexerServedCount();
    this.getRealTimeServedCount();
  }

  //COUNT
  getIndexerMetaCount(){
    this.http.get(this.apiCountIndexerMetaUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerMetaApi = data.map(countIndexerMetaApiObj => countIndexerMetaApiObj.countIndexerMetaApi))
            },
        );
    //this.countIndexerMetaNumber = this.countIndexerMetaApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerMetaArray.push(this.countIndexerMetaNumber); // problem follows through
  }
  printCountIndexerMetaArray(){
    this.countIndexerMetaApi.forEach(element => {
      console.log(element);
    });
  }

  getIndexerServedCount(){
    this.http.get(this.apiCountIndexerServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerServedApi = data.map(countObj => countObj.countIndexerServedApi))
            },
        );
    //this.countIndexerServedNumber = this.countIndexerServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerServedArray.push(this.countIndexerServedNumber); // problem follows through
  }
  printCountIndexerServedArray(){
    this.countIndexerServedApi.forEach(element => {
      console.log(element);
    });
  }

  getRealTimeServedCount(){
    this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countRealTimeServedApi = data.map(countObj => countObj.countRealTimeServedApi))
            },
        );
    //this.countRealTimeServedNumber = this.countRealTimeServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countRealTimeServedArray.push(this.countRealTimeServedNumber); // problem follows through
  }
  printRealTimeServedArray(){
    this.countRealTimeServedApi.forEach(element => {
      console.log(element);
    });
  }

  //DATES
  dateIndexerMeta() {
    this.dateIndexerMetaToStore = moment().add(-122, 'days');
    this.dateIndexerMetaArray.push(this.dateIndexerMetaToStore);
  }

  dateIndexerServed() {
    this.dateIndexerServedToStore = moment().add(-122, 'days');
    this.dateIndexerServedArray.push(this.dateIndexerServedToStore);
  }

  dateRealTimeServed() {
    this.dateRealTimeServedToStore = moment().add(-122, 'days');
    this.dateRealTimeServedArray.push(this.dateRealTimeServedToStore);
  }

  //TIMEOUT TRIAL
  timeoutTrial(){
    console.log(this.isDataAvailable);
    setTimeout(function() {this.isDataAvailable = true;
      console.log(this.isDataAvailable);
    }, 5000); //<-- timeout works but other functions don't refresh even if isDataAvailable changed
  }

  /*      CHARTS      */

  //DATA
  public lineChartData:Array<any> = [
    {data: this.countIndexerMetaArray, label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: this.countIndexerServedArray, label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: this.countRealTimeServedArray, label: 'Real-Time served links'},
  ];

  //LABELS
  public lineChartLabels:Array<any> = this.dateIndexerMetaArray;

  public lineChartLabels1:Array<any> = this.dateIndexerServedArray;

  public lineChartLabels2:Array<any> = this.dateRealTimeServedArray;

  //OPTIONS
  public lineChartOptions:any = {
    responsive: true,

    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },

  };

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  //COLORS
  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  //EVENTS
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}
</code>```

app.component.html

```<code><div class="container">

<div class="front-end-app">
    <ul>
      <h3>Count Indexer Meta:</h3>
      <li *ngFor="let countIndexerMetaNumber of countIndexerMetaApi">
        {{countIndexerMetaNumber}}
      </li>
      <h3>Count Indexer Served:</h3>
      <li *ngFor="let countIndexerServedNumber of countIndexerServedApi">
        {{countIndexerServedNumber}}
      </li>
      <h3>Count Real Time Served:</h3>
      <li *ngFor="let countRealTimeServedNumber of countRealTimeServedApi">
        {{countRealTimeServedNumber}}
      </li>
    </ul>
    <hr>

    <div class="head">
      <h1>{{title}}</h1>
    </div>
    <hr>
    <div class="row">
      <div class="col-md-6">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                  [datasets]="lineChartData"
                  [labels]="lineChartLabels"
                  [options]="lineChartOptions"
                  [colors]="lineChartColors"
                  [legend]="lineChartLegend"
                  [chartType]="lineChartType"
                  (chartHover)="chartHovered($event)"
                  (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData1"
                    [labels]="lineChartLabels1"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
      <div class="col-md-6 offset-md-3">
        <div class="card">
          <div class="card-block">
            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData2"
                    [labels]="lineChartLabels2"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerMetaArray()"> Click to print count indexer meta array</button>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerServedArray()"> Click to print count indexer served array</button>
  <button type="button" class="btn btn-primary" (click)="printRealTimeServedArray()"> Click to print count real time served array</button>
</div>
</code>```

For any question or further explanation just comment and I'll answer straight away. Thanks!

答:
Just use a boolean to show loading.

```<code>public isloading = true;
</code>```

Inside your http call , set this to false once you got all the data you want.

```<code>this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                this.countRealTimeServedApi =
                    data.map(countObj => countObj.countRealTimeServedApi);
                this.isloading= false;
            },
        );
</code>```

In your HTTP have ngIf for the isloading part

```<code><div *ngIf="isloading" > loading .... </div>
<div *ngIf="!isloading" >
   <!-- show the chart contents -->
</div>
</code>```

If you are having multiple HTTP calls then use &&

```<code> <div *ngIf="isIndexMetaCountloading
            || isIndexerServedCountLoading
            || isRealTimeServedCountLoading" >
   loading ...
</div>

<div *ngIf="!isIndexMetaCountloading
            && !isIndexerServedCountLoading
            && isRealTimeServedCountLoading" >
   <!-- show the chart contents -->
</div>
</code>```

Body:
I have a web application that is retrieving data from multiple api and is supposed to use the data into some charts. The problem is that when the charts get rendered the data from the api are not in yet. I tried using .then() method but it tells me that property then does not exist on type void. Furthermore I tried using the ngIf method, following this answer, but is not working either. Do you know how could I solve this please?

Below are my component and my component template.

app.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Mimesi dashboard graphs';

  //COUNTS
  public countIndexerMetaApi; //array of one number populated from http.get
  public countIndexerMetaNumber; //number extracted into array and stored as an int
  public countIndexerMetaArray; //array to store countNumber afterwards

  public countIndexerServedApi;
  public countIndexerServedNumber;
  public countIndexerServedArray;

  public countRealTimeServedApi;
  public countRealTimeServedNumber;
  public countRealTimeServedArray;

  //DATES
  public dateIndexerMetaToStore; //date got from moment method that needs to be stored
  public dateIndexerMetaArray; //array to store dates for graph label

  public dateIndexerServedToStore;
  public dateIndexerServedArray;

  public dateRealTimeServedToStore;
  public dateRealTimeServedArray;

  //API LINKS
  private apiCountIndexerMetaUrl: string = 'http://localhost:3000/api/countIndexerMetaApi';
  /*      TODO - API FOR COUNT OF OTHER TWO TABLES      */
  private apiCountIndexerServedUrl: string = 'http://localhost:3000/api/countIndexerServedApi';
  private apiCountRealTimeServedUrl: string = 'http://localhost:3000/api/countRealTimeServedApi';

  //VARIABLE FOR TIMEOUT
  public isDataAvailable:boolean = false;

  constructor(private http:Http) {
    let now = moment.locale("it");

    //COUNT
    this.countIndexerMetaApi = 0;
    this.countIndexerMetaNumber = 0;
    this.countIndexerMetaArray = [];

    this.countIndexerServedApi = 0;
    this.countIndexerServedNumber = 0;
    this.countIndexerServedArray = []

    this.countRealTimeServedApi = 0;
    this.countRealTimeServedNumber = 0;
    this.countRealTimeServedArray = []

    //DATES
    this.dateIndexerMetaToStore = "";
    this.dateIndexerMetaArray = [];

    this.dateIndexerServedToStore = "";
    this.dateIndexerServedArray = [];

    this.dateRealTimeServedToStore = "";
    this.dateRealTimeServedArray = [];
  }

  ngOnInit() {
    this.getIndexerMetaCount();
    this.getIndexerServedCount();
    this.getRealTimeServedCount();
  }

  //COUNT
  getIndexerMetaCount(){
    this.http.get(this.apiCountIndexerMetaUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerMetaApi = data.map(countIndexerMetaApiObj => countIndexerMetaApiObj.countIndexerMetaApi))
            },
        );
    //this.countIndexerMetaNumber = this.countIndexerMetaApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerMetaArray.push(this.countIndexerMetaNumber); // problem follows through
  }
  printCountIndexerMetaArray(){
    this.countIndexerMetaApi.forEach(element => {
      console.log(element);
    });
  }

  getIndexerServedCount(){
    this.http.get(this.apiCountIndexerServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countIndexerServedApi = data.map(countObj => countObj.countIndexerServedApi))
            },
        );
    //this.countIndexerServedNumber = this.countIndexerServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countIndexerServedArray.push(this.countIndexerServedNumber); // problem follows through
  }
  printCountIndexerServedArray(){
    this.countIndexerServedApi.forEach(element => {
      console.log(element);
    });
  }

  getRealTimeServedCount(){
    this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                console.log(this.countRealTimeServedApi = data.map(countObj => countObj.countRealTimeServedApi))
            },
        );
    //this.countRealTimeServedNumber = this.countRealTimeServedApi[0]; //<-- timing problem since this.count is not yet got from http.get() so it seems undefined
    //this.countRealTimeServedArray.push(this.countRealTimeServedNumber); // problem follows through
  }
  printRealTimeServedArray(){
    this.countRealTimeServedApi.forEach(element => {
      console.log(element);
    });
  }

  //DATES
  dateIndexerMeta() {
    this.dateIndexerMetaToStore = moment().add(-122, 'days');
    this.dateIndexerMetaArray.push(this.dateIndexerMetaToStore);
  }

  dateIndexerServed() {
    this.dateIndexerServedToStore = moment().add(-122, 'days');
    this.dateIndexerServedArray.push(this.dateIndexerServedToStore);
  }

  dateRealTimeServed() {
    this.dateRealTimeServedToStore = moment().add(-122, 'days');
    this.dateRealTimeServedArray.push(this.dateRealTimeServedToStore);
  }

  //TIMEOUT TRIAL
  timeoutTrial(){
    console.log(this.isDataAvailable);
    setTimeout(function() {this.isDataAvailable = true;
      console.log(this.isDataAvailable);
    }, 5000); //<-- timeout works but other functions don't refresh even if isDataAvailable changed
  }

  /*      CHARTS      */

  //DATA
  public lineChartData:Array<any> = [
    {data: this.countIndexerMetaArray, label: 'Indexer meta served links'},
  ];

  public lineChartData1:Array<any> = [
    {data: this.countIndexerServedArray, label: 'Indexer served links'},
  ];

  public lineChartData2:Array<any> = [
    {data: this.countRealTimeServedArray, label: 'Real-Time served links'},
  ];

  //LABELS
  public lineChartLabels:Array<any> = this.dateIndexerMetaArray;

  public lineChartLabels1:Array<any> = this.dateIndexerServedArray;

  public lineChartLabels2:Array<any> = this.dateRealTimeServedArray;

  //OPTIONS
  public lineChartOptions:any = {
    responsive: true,

    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'DD MMM',
            'second': 'DD MMM',
            'minute': 'DD MMM',
            'hour': 'DD MMM',
            'day': 'DD MMM',
            'week': 'DD MMM',
            'month': 'DD MMM',
            'quarter': 'DD MMM',
            'year': 'DD MMM',
          }
        }
      }],
    },

  };

  public lineChartLegend:boolean = true;
  public lineChartType:string = 'line';

  //COLORS
  public lineChartColors:Array<any> = [
    { // grey
      backgroundColor: 'rgba(255,55,55,0.2)',
      borderColor: 'rgba(255,55,55,1)',
      pointBackgroundColor: 'rgba(255,55,55,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,55,55,0.8)'
    },
  ];

  //EVENTS
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }
}

app.component.html

Count Indexer Meta:

        {{countIndexerMetaNumber}}

Count Indexer Served:

        {{countIndexerServedNumber}}

Count Real Time Served:

        {{countRealTimeServedNumber}}

{{title}}

            <canvas baseChart width="600" height="400"
                  [datasets]="lineChartData"
                  [labels]="lineChartLabels"
                  [options]="lineChartOptions"
                  [colors]="lineChartColors"
                  [legend]="lineChartLegend"
                  [chartType]="lineChartType"
                  (chartHover)="chartHovered($event)"
                  (chartClick)="chartClicked($event)"></canvas>

            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData1"
                    [labels]="lineChartLabels1"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>

            <canvas baseChart width="600" height="400"
                    [datasets]="lineChartData2"
                    [labels]="lineChartLabels2"
                    [options]="lineChartOptions"
                    [colors]="lineChartColors"
                    [legend]="lineChartLegend"
                    [chartType]="lineChartType"
                    (chartHover)="chartHovered($event)"
                    (chartClick)="chartClicked($event)"></canvas>

  <button type="button" class="btn btn-primary" (click)="printCountIndexerMetaArray()"> Click to print count indexer meta array</button>
  <button type="button" class="btn btn-primary" (click)="printCountIndexerServedArray()"> Click to print count indexer served array</button>
  <button type="button" class="btn btn-primary" (click)="printRealTimeServedArray()"> Click to print count real time served array</button>

For any question or further explanation just comment and I'll answer straight away. Thanks!

Body:
Just use a boolean to show loading.

public isloading = true;

Inside your http call , set this to false once you got all the data you want.

this.http.get(this.apiCountRealTimeServedUrl)
        .map((res: Response) => res.json())
        .subscribe(
            data => {
                this.countRealTimeServedApi =
                    data.map(countObj => countObj.countRealTimeServedApi);
                this.isloading= false;
            },
        );

In your HTTP have ngIf for the isloading part

<div *ngIf="isloading" > loading .... </div>
<div *ngIf="!isloading" >
   <!-- show the chart contents -->
</div>

If you are having multiple HTTP calls then use &&

 <div *ngIf="isIndexMetaCountloading
            || isIndexerServedCountLoading
            || isRealTimeServedCountLoading" >
   loading ...
</div>

<div *ngIf="!isIndexMetaCountloading
            && !isIndexerServedCountLoading
            && isRealTimeServedCountLoading" >
   <!-- show the chart contents -->
</div>


来源: stackexchange

问:
Append parameters to an existing url in Spring boot Java?
I am trying to call a rest api and get the data from the api. I need to add dynamic parameters to the url in spring boot. I am a bit lost as how should I go about it. Can anyone kindly suggest me something?

```<code>RestTemplate restTemplate = new RestTemplate();
        String consumeJSONString = restTemplate.getForObject("https://maps.googleapis.com/maps/api/geocode/json?latlng=5.47686,-73.961452&key=YOUR_API_KEY"
, String.class);
</code>```

I would like to append latlng and api key in the url dynamically. I would really appreciate any suggestions.

答:
You have to use the following variation of getForObject method

```<code>restTemplate.getForObject(url, responseType, uriVariables);
</code>```

So it becomes..

```<code>String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng={latlng}&key={key}";

Map<String, Object> uriVariables = new HashMap<>();
uriVariables.put("latlng", "5.47686,-73.961452");
uriVariables.put("key", "YOUR_API_KEY");

String consumeJSONString =  restTemplate.getForObject(url, String.class, uriVariables);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to call a rest api and get the data from the api. I need to add dynamic parameters to the url in spring boot. I am a bit lost as how should I go about it. Can anyone kindly suggest me something?

RestTemplate restTemplate = new RestTemplate();
        String consumeJSONString = restTemplate.getForObject("https://maps.googleapis.com/maps/api/geocode/json?latlng=5.47686,-73.961452&key=YOUR_API_KEY"
, String.class);

I would like to append latlng and api key in the url dynamically. I would really appreciate any suggestions.

Body:
You have to use the following variation of getForObject method

restTemplate.getForObject(url, responseType, uriVariables);

So it becomes..

String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng={latlng}&key={key}";

Map<String, Object> uriVariables = new HashMap<>();
uriVariables.put("latlng", "5.47686,-73.961452");
uriVariables.put("key", "YOUR_API_KEY");

String consumeJSONString =  restTemplate.getForObject(url, String.class, uriVariables);

ContentLicense: CC BY-SA 4.0


答:
Thanks to @R18, finally I could manage with this issue.

For the distance table I uploaded, the solution that I reached was to use the following code:

```<code>library(phyloseq)
library(vegan)
M <- import_mothur_dist("pcoa_UFdistance_matrix.dist")
unifrac <- metaMDS(M, distance = M, k = 2, trymax=100)
plot(unifrac$points[,1], unifrac$points[,2], main="Principal Coordinates Analysis", col.main="red", font.main=4, xlab="PCoA 1", ylab="PCoA 2")
text(unifrac, pos=3)
</code>```

Hope it will help someone!!

Title: How to generate an ordination plot from a distance matrix in R

Body:
Here I have another 'graphical' problem:

I have obtained from MOTHUR the following distance matrix (coming from a weighted unifrac analysis):

20
F3D0
F3D1        0.222664
F3D141      0.157368    0.293308
F3D142      0.180278    0.319198    0.0944511
F3D143      0.157659    0.290975    0.0545202   0.0761392
F3D144      0.199909    0.34045 0.104358    0.086418    0.089473
F3D145      0.207946    0.348532    0.107841    0.076302    0.0940067   0.051632
F3D146      0.117877    0.253996    0.0891617   0.130867    0.0882064   0.134407    0.138415
F3D147      0.197256    0.336583    0.102114    0.0764106   0.0890669   0.0514887   0.0479297   0.135324
F3D148      0.173824    0.311951    0.0606815   0.0648557   0.056463    0.074914    0.0811015   0.111996    0.0709027
F3D149      0.145614    0.276632    0.0462779   0.105512    0.0628737   0.10902 0.114584    0.0739466   0.107123    0.0690412
F3D150      0.129557    0.277624    0.0840909   0.128305    0.0863231   0.140256    0.145381    0.0744572   0.13672 0.113564    0.0659831
F3D2        0.133531    0.216587    0.160832    0.186833    0.176061    0.214934    0.215261    0.152591    0.205629    0.188325    0.156313    0.153841
F3D3        0.213102    0.305651    0.123818    0.113021    0.139376    0.148558    0.13853 0.174377    0.139851    0.126329    0.131294    0.166738    0.137784
F3D5        0.128668    0.185235    0.167733    0.205183    0.176585    0.224806    0.230984    0.14497 0.223492    0.18933 0.153624    0.148617    0.127574    0.192433
F3D6        0.139411    0.236633    0.135418    0.124848    0.134198    0.175098    0.166205    0.118905    0.166144    0.151842    0.120964    0.12724 0.0950943   0.119852    0.129523
F3D7        0.198884    0.315888    0.130385    0.0989168   0.131945    0.14625 0.126203    0.173689    0.128993    0.121373    0.140199    0.152123    0.152893    0.0906675   0.186674    0.111134
F3D8        0.178656    0.18783 0.205737    0.22104 0.219858    0.268701    0.2644  0.184943    0.268051    0.229503    0.1979  0.20035 0.164427    0.203089    0.119084    0.142398    0.185551
F3D9        0.153265    0.186706    0.196143    0.21504 0.20728 0.262127    0.255558    0.174563    0.2607  0.221969    0.192437    0.185154    0.13976 0.195538    0.0973901   0.127619    0.177605    0.0558726
Mock        0.653789    0.645344    0.633297    0.623553    0.633903    0.633135    0.63394 0.635815    0.645332    0.636453    0.629143    0.646918    0.663222    0.639517    0.649722    0.64073 0.654882    0.63988 0.646155

As this distance matrix come from a PCoA, what I want to do is to plot these distances in an ordination plot with R.

Any idea on how to doing this?

Thanks a lot

Body:
Thanks to @R18, finally I could manage with this issue.

For the distance table I uploaded, the solution that I reached was to use the following code:

library(phyloseq)
library(vegan)
M <- import_mothur_dist("pcoa_UFdistance_matrix.dist")
unifrac <- metaMDS(M, distance = M, k = 2, trymax=100)
plot(unifrac$points[,1], unifrac$points[,2], main="Principal Coordinates Analysis", col.main="red", font.main=4, xlab="PCoA 1", ylab="PCoA 2")
text(unifrac, pos=3)

Hope it will help someone!!


问:
Cannot explicitly call operator or accessor and static
I have two stupid questions :

The first one :

I have already asked this and I'm truly sorry to ask it again (even more so because there are a lot of posts about it), but now I really don't understand why that happens even if I read every other post, here is my code :

```<code>public class PageTitre {
    ...
    public void situation(string s) {
        onglet.get_Range("C11").Value = "(" + s + ")";
    }
}

public class PPE_Process {

    public static PageTitre pageTitre;

    public static void MainProcess() {
        ...
        pageTitre = new PageTitre();
        ...
    }
}

public partial class PPE_Ribbon {
    private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.situation(SituationEditBox.Text);
    }
}
</code>```

I have tried some other things, like putting situation as a variable of PageTitre and having a get and a set, and

```<code>private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.set_situation(SituationEditBox.Text);
    }
</code>```

Or

```<code>private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.situation = SituationEditBox.Text;
    }
</code>```

But nothing worked, with the same error: cannot explicitly call operator or accessor.

I guess there is a problem with the static? If that is the case, here is my second question:

Second one :

I read a lot of documentation about it but I really can't understand what is the use of "static"... Is it just so that we can't change the value outside of the class, or something like this? Then, would it really change something if I take off every static there is in my code?

Again, I am sorry that you have to answer this question again and again, but I understand a lot better if that is directly related to my code, and not someone answering someone else about some other random code, which has a different problem than mine. :/

Edit to add more information:

There shouldn't be any problem with .Value or .get_Range, as it works on other parts of the code, but
For .Value, here is the information given by Visual Studio:

void Range.set_Value([object RangeValueDataType = System.Type.Missing], [object value = System.Type.Missing])

For .get_Range: Excel.Range_Worksheet.get_Range(object Cell1, [object Cell2 = System.Type.Missing])

For static, I still don't really understand all these "instances" things, but I will try to look more, and add another question in this forum if I still don't understand after this.

答:
To your first question: I don't see any problem with your call of the method situation, maybe the problem is the statement inside the method (get_Range("C11"))?

To your second question: When you make a variable/property/method static it means that it is independent from any instance (object) of the class. Otherwise you couldn't access the property PPE_Process.pageTitre without an instance of PPE_Process.

Body:
I have two stupid questions :

The first one :

I have already asked this and I'm truly sorry to ask it again (even more so because there are a lot of posts about it), but now I really don't understand why that happens even if I read every other post, here is my code :

public class PageTitre {
    ...
    public void situation(string s) {
        onglet.get_Range("C11").Value = "(" + s + ")";
    }
}

public class PPE_Process {

    public static PageTitre pageTitre;

    public static void MainProcess() {
        ...
        pageTitre = new PageTitre();
        ...
    }
}

public partial class PPE_Ribbon {
    private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.situation(SituationEditBox.Text);
    }
}

I have tried some other things, like putting situation as a variable of PageTitre and having a get and a set, and

private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.set_situation(SituationEditBox.Text);
    }

Or

private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
    {
        PPE_Process.pageTitre.situation = SituationEditBox.Text;
    }

But nothing worked, with the same error: cannot explicitly call operator or accessor.

I guess there is a problem with the static? If that is the case, here is my second question:

Second one :

I read a lot of documentation about it but I really can't understand what is the use of "static"... Is it just so that we can't change the value outside of the class, or something like this? Then, would it really change something if I take off every static there is in my code?

Again, I am sorry that you have to answer this question again and again, but I understand a lot better if that is directly related to my code, and not someone answering someone else about some other random code, which has a different problem than mine. :/

Edit to add more information:

There shouldn't be any problem with .Value or .get_Range, as it works on other parts of the code, but
For .Value, here is the information given by Visual Studio:

void Range.set_Value([object RangeValueDataType = System.Type.Missing], [object value = System.Type.Missing])

For .get_Range: Excel.Range_Worksheet.get_Range(object Cell1, [object Cell2 = System.Type.Missing])

For static, I still don't really understand all these "instances" things, but I will try to look more, and add another question in this forum if I still don't understand after this.


问:
How to load my website dynamically when user requests from mobile or computer
I need to display my website dynamically. I.e when user requests form a computer the large layout should display and if user requests from mobile, my jquery mobile page should be displayed.

I'm not asking about Bootstrap framework.

答: user agents is not always a good option, what if the user vendor is not found in any of the enlisted phone type, then they are stocked to your sites PC version, worse yet would you detect all tablet phones to display a particular tablet version for your website to them. based on the program language you are using , Media Queries remains the best. it detects by screen width.</p>


问:
J2EE redirect to an external URL
I am developing a web application in which the servlet takes informaiton from index.jsp and does some data processing. After that, I want my application to redirect the user to an external url.

How can I do that? Should I redirect in the servlet or make the servlet call a jsp page which calls the url? and how to do that explicitly?

Thank you in advance!

答: make the servlet call a jsp page which calls the url.</p>

Title: J2EE redirect to an external URL


问:
Sticky scroll in Scala.JS
I'm trying to do the same a this answer in Scala.JS: https://stackoverflow.com/a/21067431

According to his exemple: http://jsfiddle.net/dotnetCarpenter/KpM5j/

I tried to redo here: https://scalafiddle.io/sf/gKgxQY0/3277

```<code>import scalatags.JsDom.all._
import scala.concurrent.duration._
import org.scalajs.dom

println(div(id := "logs", style := "height: 100px"))

js.timers.setInterval(1.millisecond) {
  val logs = dom.document.getElementById("logs")

  val isScrolledToBottom = logs.scrollHeight - logs.clientHeight <= logs.scrollTop + 1

  val child = dom.document.createElement("div")
  child.innerHTML = s"isScrolledToBottom: $isScrolledToBottom"
  logs.appendChild(child)

  if (isScrolledToBottom) logs.scrollTop = logs.scrollHeight - logs.clientHeight

  val child2 = dom.document.createElement("div")
  child2.innerHTML = s"logs.scrollTop: ${logs.scrollTop}"
  logs.appendChild(child2)
}
</code>```

Does anyone see why the Scala.JS version is not working?

Cheers

答:
Ok that was because I didn't add the overflow:auto on the div:
https://scalafiddle.io/sf/gKgxQY0/3294

```<code>import scalatags.JsDom.all._
import scala.concurrent.duration._
import org.scalajs.dom

println(div(id := "logs", style := "overflow:auto; height: 100px"))

js.timers.setInterval(1.second) {
  val logs = dom.document.getElementById("logs")

  val isScrolledToBottom =
    logs.scrollHeight - logs.clientHeight <= logs.scrollTop + 1

  val child = dom.document.createElement("div")
  child.innerHTML = s"isScrolledToBottom: $isScrolledToBottom"
  logs.appendChild(child)

  if (isScrolledToBottom)
    logs.scrollTop = logs.scrollHeight - logs.clientHeight
}
</code>```

Title: Sticky scroll in Scala.JS

Body:
I'm trying to do the same a this answer in Scala.JS: https://stackoverflow.com/a/21067431

According to his exemple: http://jsfiddle.net/dotnetCarpenter/KpM5j/

I tried to redo here: https://scalafiddle.io/sf/gKgxQY0/3277

import scalatags.JsDom.all._
import scala.concurrent.duration._
import org.scalajs.dom

println(div(id := "logs", style := "height: 100px"))

js.timers.setInterval(1.millisecond) {
  val logs = dom.document.getElementById("logs")

  val isScrolledToBottom = logs.scrollHeight - logs.clientHeight <= logs.scrollTop + 1

  val child = dom.document.createElement("div")
  child.innerHTML = s"isScrolledToBottom: $isScrolledToBottom"
  logs.appendChild(child)

  if (isScrolledToBottom) logs.scrollTop = logs.scrollHeight - logs.clientHeight

  val child2 = dom.document.createElement("div")
  child2.innerHTML = s"logs.scrollTop: ${logs.scrollTop}"
  logs.appendChild(child2)
}

Does anyone see why the Scala.JS version is not working?

Cheers

Body:
Ok that was because I didn't add the overflow:auto on the div:
https://scalafiddle.io/sf/gKgxQY0/3294

import scalatags.JsDom.all._
import scala.concurrent.duration._
import org.scalajs.dom

println(div(id := "logs", style := "overflow:auto; height: 100px"))

js.timers.setInterval(1.second) {
  val logs = dom.document.getElementById("logs")

  val isScrolledToBottom =
    logs.scrollHeight - logs.clientHeight <= logs.scrollTop + 1

  val child = dom.document.createElement("div")
  child.innerHTML = s"isScrolledToBottom: $isScrolledToBottom"
  logs.appendChild(child)

  if (isScrolledToBottom)
    logs.scrollTop = logs.scrollHeight - logs.clientHeight
}


问:
Fade out character by character in text using jQuery
In the code below I have a line of text "A B C" that I would like to fade out character by character, i.e. C is faded out first, then B and finally A. The code works, but I think that my solution is very clumpsy. If the text has more letters, then the code must be extended for each letter with callback after callback...

Can this be solved in a more neat way? Can the fadeOuts be placed in sequence instead of nested callbacks?

My final goal is to fade out a text character by character and then fade in a new text, character by character... Just like a Powerpoint animation :)

$(document).ready(function() {
  $("button").click(function() {
    $("#C").fadeOut(300, function() {
      $("#B").fadeOut(300, function() {
        $("#A").fadeOut(300);
      });
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <button>Click to fade out character by character</button><br><br>

  <div>
    <span id="A">A</span>
    <span id="B">B</span>
    <span id="C">C</span>
  </div></code>```

答:
Here you go with a solution https://jsfiddle.net/d0326z9m/

```<code>$("button").click(function() {
    var child = $('div').children();

    var i = child.length;
    setInterval(function() {
        $('#' + $(child[i-1]).attr('id')).fadeOut();
        i--;
        if( i < 0 ){
            window.clearInterval();
        }
    }, 300);
 });
</code>```

In this solution, doesn't matter how may children you have inside a div it will perform perfectly.

Body:
In the code below I have a line of text "A B C" that I would like to fade out character by character, i.e. C is faded out first, then B and finally A. The code works, but I think that my solution is very clumpsy. If the text has more letters, then the code must be extended for each letter with callback after callback...

Can this be solved in a more neat way? Can the fadeOuts be placed in sequence instead of nested callbacks?

My final goal is to fade out a text character by character and then fade in a new text, character by character... Just like a Powerpoint animation :)

$(document).ready(function() {
  $("button").click(function() {
    $("#C").fadeOut(300, function() {
      $("#B").fadeOut(300, function() {
        $("#A").fadeOut(300);
      });
    });
  });
});

  <button>Click to fade out character by character</button>

    A
    B
    C

Body:
Here you go with a solution https://jsfiddle.net/d0326z9m/

$("button").click(function() {
    var child = $('div').children();

    var i = child.length;
    setInterval(function() {
        $('#' + $(child[i-1]).attr('id')).fadeOut();
        i--;
        if( i < 0 ){
            window.clearInterval();
        }
    }, 300);
 });

In this solution, doesn't matter how may children you have inside a div it will perform perfectly.


问:
Android drag recycler view from bottom over map fragment
I would like to immitate google street view layout.
I have a viewpager with a single map. I would like to display a recycler on the bottom of each page, and drag + scroll it from bottom.
Here is the desired result (I don't need to hide the action bar) :

Would you know which layout to use in order to have the same drag / scroll from bottom effect?

I managed to have a single map for myviewpager :

but when I add the recyclerView in my viewpager fragments, it obviously hide the map :

Right now my tab fragment is only composed by the recyclerview

```<code><android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:visibility="invisible"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
tools:listitem="@layout/fragment_topic_list" />
</code>```

I tried to use a bottom sheet but it was catching the map event, and I was unable to control the scroll (inertia).

答:
Bottom Sheets are a lesser known part of the Design support library. The Design support library is an Android library intended to help android developers implement the Google material design guidelines.

Bottom sheets can be dragged up and down. You need to explore it more. I can point you toward some helpful resource. You should follow them. I really think they can help you.

Clone this plaid app's repo and study the code. It is using bottom sheet in it with drag and drop

Also follow this tutorial it will help you to understand the behavior of bottom sheet

I hope this answer will help you.

Body:
I would like to immitate google street view layout.
I have a viewpager with a single map. I would like to display a recycler on the bottom of each page, and drag + scroll it from bottom.
Here is the desired result (I don't need to hide the action bar) :

Would you know which layout to use in order to have the same drag / scroll from bottom effect?

I managed to have a single map for myviewpager :

but when I add the recyclerView in my viewpager fragments, it obviously hide the map :

Right now my tab fragment is only composed by the recyclerview

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:visibility="invisible"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
tools:listitem="@layout/fragment_topic_list" />

I tried to use a bottom sheet but it was catching the map event, and I was unable to control the scroll (inertia).


问:
AngularJS: ng-model not getting updated in UI

Hi I have a calender in my UI

```<code>     <select id="selectDuration" name="selectDuration" required ui-
     select2="select2DurationSettings" ng-model="duration" ng-
     change="loadSensoryEvents()">
</code>```

This duration value is not getting updated

This is my JS file

```<code>     if(filterStateService.getQuery()){
                filterStateService.setDefaultDuration(filterStateService.getDefaultDuration());
                $scope.duration = filterStateService.getDefaultDuration();
         }
</code>```

M updating this $scope.duration value but this value is not getting updated in my UI.

答:
Use object and declare  object in controller

```<code>$scope.selected = {};
</code>```

HTML

```<code><select id="selectDuration" name="selectDuration" required ui-
 select2="select2DurationSettings" ng-model="selected.duration" ng-
change="loadSensoryEvents()">
</code>```

Body:
Hi I have a calender in my UI

     <select id="selectDuration" name="selectDuration" required ui-
     select2="select2DurationSettings" ng-model="duration" ng-
     change="loadSensoryEvents()">

This duration value is not getting updated

This is my JS file

     if(filterStateService.getQuery()){
                filterStateService.setDefaultDuration(filterStateService.getDefaultDuration());
                $scope.duration = filterStateService.getDefaultDuration();
         }

M updating this $scope.duration value but this value is not getting updated in my UI.

Body:
Use object and declare  object in controller

$scope.selected = {};

HTML

<select id="selectDuration" name="selectDuration" required ui-
 select2="select2DurationSettings" ng-model="selected.duration" ng-
change="loadSensoryEvents()">


问:
How can we know a new contact is Added to Android?
Hello Guys i m using following code to open Android Add Contact Page ,

```<code>Intent intent1 = new Intent(Intent.ACTION_INSERT);
        intent1.setType(Contacts.CONTENT_ITEM_TYPE);
        intent1.setData(ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent1,300);
</code>```

But as a result code it sends -1 inside onActivityResult function
I want to have the ContactId of the newly added Person , How can we get this?

答:
When there is error in adding a contact to the the contacts database it will return -1 else it returns the ContactId of the contact.

Try using the following code:

```<code>Intent intent1= new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
startActivityForResult(intent1,300);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hello Guys i m using following code to open Android Add Contact Page ,

Intent intent1 = new Intent(Intent.ACTION_INSERT);
        intent1.setType(Contacts.CONTENT_ITEM_TYPE);
        intent1.setData(ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent1,300);

But as a result code it sends -1 inside onActivityResult function
I want to have the ContactId of the newly added Person , How can we get this?

Body:
When there is error in adding a contact to the the contacts database it will return -1 else it returns the ContactId of the contact.

Try using the following code:

Intent intent1= new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
startActivityForResult(intent1,300);


问:
Pyinstaller - Standalone .exe
I am trying to create an .exe file such that when run on any windows 10 pc will run without requiring any installations. What I tried using was:

```<code>pyinstaller --onefile main.py
</code>```

I ran the exe file on a friend's computer and it turns out that it required first python2.7 to be installed, then it said that modules weren't installed i.e; no module named datetime found. The executable finally ran after I installed all dependencies on my friend's computer but the whole point of creating .exe file was useless, I might as well have just typed python main.py after doing so much. Is there an appropriate way I could get an .exe file from .py which wont require anything to be installed? Like an actual standalone app. Thank you!

答: I've had good results using the pyinstaller module to one file even when running code with multiple dependencies on machines without python installed. Reading the documentation helped There is a comprehensive list of python to exe compilers in another stackoverflow question: a good python to exe compiler?</p>

Title: Pyinstaller - Standalone .exe

Body:
I am trying to create an .exe file such that when run on any windows 10 pc will run without requiring any installations. What I tried using was:

pyinstaller --onefile main.py

I ran the exe file on a friend's computer and it turns out that it required first python2.7 to be installed, then it said that modules weren't installed i.e; no module named datetime found. The executable finally ran after I installed all dependencies on my friend's computer but the whole point of creating .exe file was useless, I might as well have just typed python main.py after doing so much. Is there an appropriate way I could get an .exe file from .py which wont require anything to be installed? Like an actual standalone app. Thank you!


问:
InstaSharp authentication without user interaction
I'm trying to write a service, that can get the Instagram feed for a specific user.

Im using InstaSharp, but I can't figure out how to do the authentication without redirecting the end user to a https://api.instagram.com/oauth/authorize url

I can't find any examples, beside this (and others looking like it)

Can anyone give me any pointers.
For now I have a Instagram app in sandbox mode, and a selection of users, who have accepted the sandbox invite.

答:
I don't think it's possible with this library. You better generate your access token by yourself - https://elfsight.com/blog/2016/05/how-to-get-instagram-access-token/ and then request user's feed as like this

```<code>https://api.instagram.com/v1/users/{USER-ID}/media/recent/?access_token={YOUR-ACCESS-TOKEN}
</code>```

If you want to deserialize your JSON object to c#, please use this service - http://json2csharp.com for generating your class and then using Newtownsoft library:

```<code>JsonConvert.DeserializeObject<RootObject>(yourClass)
</code>```

Good luck.

Body:
I don't think it's possible with this library. You better generate your access token by yourself - https://elfsight.com/blog/2016/05/how-to-get-instagram-access-token/ and then request user's feed as like this

https://api.instagram.com/v1/users/{USER-ID}/media/recent/?access_token={YOUR-ACCESS-TOKEN}

If you want to deserialize your JSON object to c#, please use this service - http://json2csharp.com for generating your class and then using Newtownsoft library:

JsonConvert.DeserializeObject<RootObject>(yourClass)

Good luck.


问:
Pure JavaScript JSON compare array
I have to compare some JSON data and return index of position. I use pure JavaScript.

I have data below:

```<code> NAMES
 [
    {
      "someName" : Name1,
      "secondData" : "aaaa1",
      "thirdData" : bbbb1
    },
    {
      "someName" : Name2,
      "secondData" : "aaaa2",
      "thirdData" : bbbb2
    },
    {
      "someName" : Name3,
      "secondData" : "aaaa3",
      "thirdData" : bbbb3
    },
        {
      "someName" : Name4,
      "secondData" : "aaaa4",
      "thirdData" : bbbb4
    }
]
</code>```

and JSON SEATS

```<code>[
  {
    "seats" : 0,
    "someName" : "Name4",
    omeData" : null,
    "someData" : null
  },
  {
    "seats" : 1,
    "someName" : "Name3",
    "someData" : null,
    "someData" : null
  },
  {
    "seats" : 2,
    "someName" : "Name1",
    "someData" : null,
    "someData" : null
  },
  {
    "seats" : 3,
    "someName" : "Name2",
    "someData" : null,
    "someData" : null
  }
]
</code>```

All what I want to do is compare this JSON like this:

```<code>Take someName from NAMES.someName and search the same name in SEATS.someName if is the same create new array RESULTS. Index in RESULTS array shuldbe SEATS.seats and data from NAMES.
</code>```

Example below

```<code>RESULTS[0] = NAMES[{"someName" : Name4,"secondData" : "aaaa4","thirdData" : bbbb4}]
RESULTS[1] = NAMES[{"someName" : Name3,"secondData" : "aaaa3","thirdData" : bbbb3}]
RESULTS[2] = NAMES[{"someName" : Name1,"secondData" : "aaaa1","thirdData" : bbbb1}]
RESULTS[3] = NAMES[{"someName" : Name2,"secondData" : "aaaa2","thirdData" : bbbb2}]
</code>```

I start do this like this but I stack

```<code>for(i=0;i<=459; i++) {
  if(mergeData[i][2] == jsonData[4].rows[i].find(compareElement)) {
  }
}
function compareElement(element) {
  return element.someName == i;
}
</code>```

Problem is if I use find like this I have some error and program stop I can't find way how to solve this.

答:
```<code>var result = [];

NAMES.forEach(function(name) {
  var found = SEATS.find(function(seat) {
    return name.someName === seat.someName
  });

  if (found) {
    result[found.seats] = name;
  }
});
</code>```

Title: Pure JavaScript JSON compare array

Body:
I have to compare some JSON data and return index of position. I use pure JavaScript.

I have data below:

 NAMES
 [
    {
      "someName" : Name1,
      "secondData" : "aaaa1",
      "thirdData" : bbbb1
    },
    {
      "someName" : Name2,
      "secondData" : "aaaa2",
      "thirdData" : bbbb2
    },
    {
      "someName" : Name3,
      "secondData" : "aaaa3",
      "thirdData" : bbbb3
    },
        {
      "someName" : Name4,
      "secondData" : "aaaa4",
      "thirdData" : bbbb4
    }
]

and JSON SEATS

[
  {
    "seats" : 0,
    "someName" : "Name4",
    omeData" : null,
    "someData" : null
  },
  {
    "seats" : 1,
    "someName" : "Name3",
    "someData" : null,
    "someData" : null
  },
  {
    "seats" : 2,
    "someName" : "Name1",
    "someData" : null,
    "someData" : null
  },
  {
    "seats" : 3,
    "someName" : "Name2",
    "someData" : null,
    "someData" : null
  }
]

All what I want to do is compare this JSON like this:

Take someName from NAMES.someName and search the same name in SEATS.someName if is the same create new array RESULTS. Index in RESULTS array shuldbe SEATS.seats and data from NAMES.

Example below

RESULTS[0] = NAMES[{"someName" : Name4,"secondData" : "aaaa4","thirdData" : bbbb4}]
RESULTS[1] = NAMES[{"someName" : Name3,"secondData" : "aaaa3","thirdData" : bbbb3}]
RESULTS[2] = NAMES[{"someName" : Name1,"secondData" : "aaaa1","thirdData" : bbbb1}]
RESULTS[3] = NAMES[{"someName" : Name2,"secondData" : "aaaa2","thirdData" : bbbb2}]

I start do this like this but I stack

for(i=0;i<=459; i++) {
  if(mergeData[i][2] == jsonData[4].rows[i].find(compareElement)) {
  }
}
function compareElement(element) {
  return element.someName == i;
}

Problem is if I use find like this I have some error and program stop I can't find way how to solve this.


问:
Options Menu null at runtime
I am changing the drawable of a specific menu item when certain actions are made within my app.

Everything works as it should except for when I try and do this in the onCreate method of my Activity.

I am using the following method:

```<code>menu.findItem(R.id.favorite).setIcon(R.drawable.ic_action_icons8_star_filled_100);
</code>```

In an onClick event and it works flawlessly.

But when I use the same method in my onCreate, it gives me the following eror:

```<code>java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference
</code>```

This is the code I am using to inflate the menu

```<code>private Menu menu;

--------------------

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.image_details, menu);

        this.menu = menu;

        return super.onCreateOptionsMenu(menu);
    }
</code>```

Any ideas? thanks.

答:
You can use onPrepareOptionsMenu(this will get a call whenever the menu will about to visible). You are getting null pointer because onCreateOptionsMenu will call after onCreate so your menu object will be null.</p>

```<code>@Override
 public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem favoriteItem = menu.findItem(R.id.favorite);

    favoriteItem.setIcon(getResources().getDrawable(R.drawable.drawable.ic_action_icons8_star_filled_100));

    return super.onPrepareOptionsMenu(menu);
 }
</code>```

Title: Options Menu null at runtime

Body:
I am changing the drawable of a specific menu item when certain actions are made within my app.

Everything works as it should except for when I try and do this in the onCreate method of my Activity.

I am using the following method:

menu.findItem(R.id.favorite).setIcon(R.drawable.ic_action_icons8_star_filled_100);

In an onClick event and it works flawlessly.

But when I use the same method in my onCreate, it gives me the following eror:

java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference

This is the code I am using to inflate the menu

private Menu menu;

--------------------

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.image_details, menu);

        this.menu = menu;

        return super.onCreateOptionsMenu(menu);
    }

Any ideas? thanks.

Body:
You can use onPrepareOptionsMenu(this will get a call whenever the menu will about to visible). You are getting null pointer because onCreateOptionsMenu will call after onCreate so your menu object will be null.

@Override
 public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem favoriteItem = menu.findItem(R.id.favorite);

    favoriteItem.setIcon(getResources().getDrawable(R.drawable.drawable.ic_action_icons8_star_filled_100));

    return super.onPrepareOptionsMenu(menu);
 }


问:
Capture and return function scope

Question

How do I automate a function to return all variables defined inside its scope?

Motivation

When using Python for scientific work my scripts tend to be very linear (algorithm like) but quite long. When working interactively with the script I want to keep the calculated variables to further explore or use them.

I could just skip using a main() function inside my scripts and do everything globally. However that would prohibit behavior like in the example below and prohibit me from modifying the script from an interactive python console prior to execution.

Example

Inside script.py:

```<code>def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return parse_scope()
</code>```

Inside the interactive console:

```<code>>>> import script
>>> script.main(c=3)
{'a': 1, 'b': 2, 'c': 3}
</code>```

parse_scope() captures the function scope and returns it as a dict, list,...

Ideas

```<code>def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return {name: eval(name) for name in dir()}
</code>```

Gives NameError: name 'a' is not defined.

答:
After writing this question I found the answer:

```<code>def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return locals()
</code>```

seems to do the trick.

My previous example doesn't work because eval(expression, globals=None, locals=None) would need to be given a scope with a, b, c.

Title: Capture and return function scope

Body:
Question

How do I automate a function to return all variables defined inside its scope?

Motivation

When using Python for scientific work my scripts tend to be very linear (algorithm like) but quite long. When working interactively with the script I want to keep the calculated variables to further explore or use them.

I could just skip using a main() function inside my scripts and do everything globally. However that would prohibit behavior like in the example below and prohibit me from modifying the script from an interactive python console prior to execution.

Example

Inside script.py:

def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return parse_scope()

Inside the interactive console:

>>> import script
>>> script.main(c=3)
{'a': 1, 'b': 2, 'c': 3}

parse_scope() captures the function scope and returns it as a dict, list,...

Ideas

def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return {name: eval(name) for name in dir()}

Gives NameError: name 'a' is not defined.

Body:
After writing this question I found the answer:

def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return locals()

seems to do the trick.

My previous example doesn't work because eval(expression, globals=None, locals=None) would need to be given a scope with a, b, c.


问:
how to reuse JDBC Statements and automatic close back resultsets?
iam working on an project that will have many statements connected to DB
and i want to reuse statements instead of create new one every connect
and the most important thing that i don't want to close every resultset after use

i want to close back resultsets on statement before reuse it

my code look like this

```<code>ArrayList<Statement> BackStatements = new ArrayList();
int lastStatementIndex = 0;

private Statement GetStatement() throws SQLException {
    Statement SM;
    int MaxStatements = 5;
    if (BackStatements.size() < MaxStatements) {
        SM = Connection.createStatement();
        BackStatements.add(SM);
        lastStatementIndex = BackStatements.size() - 1;
    } else {
        lastStatementIndex = lastStatementIndex + 1;
        if (lastStatementIndex == MaxStatements) {
            lastStatementIndex = 0;
        }
        SM = BackStatements.get(lastStatementIndex);
     /// i want to close resultset generated by SM now and i do this before return this SM
        SM.getResultSet().close();

    }

    System.out.println("Last Index:" + lastStatementIndex + "---- Size:" + BackStatements.size());
    return SM;
}
</code>```

but this method return this error by logger

```<code>Caused by: java.sql.SQLException: ResultSet already requested
</code>```

答: Instead of building your own statement cache you should use the one provided by the driver. For example in the Oracle JDBC thin driver there is an implicit statement cache that will take care of optimizing how statements and cursors are allocated and freed. It needs to be turned on. The doc is here. To enable it just set the property "oracle.jdbc.implicitStatementCacheSize" to a value for example "10" which is usually a good size for the statement cache.

Body:
iam working on an project that will have many statements connected to DB
and i want to reuse statements instead of create new one every connect
and the most important thing that i don't want to close every resultset after use

i want to close back resultsets on statement before reuse it

my code look like this

ArrayList<Statement> BackStatements = new ArrayList();
int lastStatementIndex = 0;

private Statement GetStatement() throws SQLException {
    Statement SM;
    int MaxStatements = 5;
    if (BackStatements.size() < MaxStatements) {
        SM = Connection.createStatement();
        BackStatements.add(SM);
        lastStatementIndex = BackStatements.size() - 1;
    } else {
        lastStatementIndex = lastStatementIndex + 1;
        if (lastStatementIndex == MaxStatements) {
            lastStatementIndex = 0;
        }
        SM = BackStatements.get(lastStatementIndex);
     /// i want to close resultset generated by SM now and i do this before return this SM
        SM.getResultSet().close();

    }

    System.out.println("Last Index:" + lastStatementIndex + "---- Size:" + BackStatements.size());
    return SM;
}

but this method return this error by logger

Caused by: java.sql.SQLException: ResultSet already requested


问:
UPDATE MySQL Query taking a long time to execute - ways to optimize
I have a doubt with the following query.

```<code>update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
inner join waardeklasse_average b use index (waardeklasse)
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
where b.waardeklasse_new = a.waardeklasse;
</code>```

I am trying to update a new column 'woz_val' in the 'src_woz_waardeklasse_2011' table using the 'average' values from the 'waardeklasse_average' table. I am joining using the 'waaderklasse' numbers in both the tables. But the 'src_woz_waardeklasse_2011' table is nearly 7 million records and the 'waardeklasee_average' table is 46 records. So the query is taking a really long time. 25 minutes and counting.

Is there a way to optimize it? I am sure it's taking a long time as I am trying to compare values between a large table and a small table. I have included the table structure of both the tables below.

```<code>src_woz_waardeklasse_2011
+----------------------+---------------------------+------+-----+---------+-
---------------+
| Field                | Type                      | Null | Key | Default |
Extra          |
+----------------------+---------------------------+------+-----+---------+-
---------------+
| id                   | int(11) unsigned          | NO   | PRI | NULL    |
auto_increment |
| postcode             | varchar(150)              | YES  | MUL | NULL    |
|
| huisnummeraanduiding | varchar(150)              | YES  |     | NULL    |
|
| huisletter           | varchar(150)              | YES  |     | NULL    |
|
 soort_woonobject     | varchar(150)              | YES  |     | NULL    |
|
| bouwjaar             | varchar(150)              | YES  |     | NULL    |
|
| bouwjaarsklasse      | varchar(150)              | YES  |     | NULL    |
|
| inhoud               | varchar(150)              | YES  |     | NULL    |
|
| reg_oppervlak        | varchar(150)              | YES  |     | NULL    |
|
| woz_value            | int(15) unsigned zerofill | YES  | UNI | NULL    |
|
| reg_oppervlak_bn     | varchar(150)              | YES  |     | NULL    |
|
| waardeklasse         | int(10)                   | NO   | PRI | NULL    |
|
| waardepeildatum      | varchar(150)              | YES  |     | NULL    |
|
| zipandnumber         | varchar(150)              | YES  |     | NULL    |
|
+----------------------+---------------------------+------+-----+---------+-
---------------+

waardeklasse_average
+-------------------------+---------+------+-----+---------+-------+
| Field                   | Type    | Null | Key | Default | Extra |
+-------------------------+---------+------+-----+---------+-------+
| waardeklasse_average_id | int(11) | NO   |     | NULL    |       |
| waardeklasse_new        | int(10) | NO   | PRI | NULL    |       |
| lower                   | int(11) | NO   |     | NULL    |       |
| higher                  | int(11) | NO   |     | NULL    |       |
| average                 | int(11) | NO   | PRI | NULL    |       |
+-------------------------+---------+------+-----+---------+-------+
</code>```

答:
```<code>update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
inner join waardeklasse_average b use index (waardeklasse)
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
</code>```

Where condition is not needed. As you had already mention that condition in On clause.

Try above query.

Body:
I have a doubt with the following query.

update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
inner join waardeklasse_average b use index (waardeklasse)
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
where b.waardeklasse_new = a.waardeklasse;

I am trying to update a new column 'woz_val' in the 'src_woz_waardeklasse_2011' table using the 'average' values from the 'waardeklasse_average' table. I am joining using the 'waaderklasse' numbers in both the tables. But the 'src_woz_waardeklasse_2011' table is nearly 7 million records and the 'waardeklasee_average' table is 46 records. So the query is taking a really long time. 25 minutes and counting.

Is there a way to optimize it? I am sure it's taking a long time as I am trying to compare values between a large table and a small table. I have included the table structure of both the tables below.

src_woz_waardeklasse_2011
+----------------------+---------------------------+------+-----+---------+-
---------------+
| Field                | Type                      | Null | Key | Default |
Extra          |
+----------------------+---------------------------+------+-----+---------+-
---------------+
| id                   | int(11) unsigned          | NO   | PRI | NULL    |
auto_increment |
| postcode             | varchar(150)              | YES  | MUL | NULL    |
|
| huisnummeraanduiding | varchar(150)              | YES  |     | NULL    |
|
| huisletter           | varchar(150)              | YES  |     | NULL    |
|
 soort_woonobject     | varchar(150)              | YES  |     | NULL    |
|
| bouwjaar             | varchar(150)              | YES  |     | NULL    |
|
| bouwjaarsklasse      | varchar(150)              | YES  |     | NULL    |
|
| inhoud               | varchar(150)              | YES  |     | NULL    |
|
| reg_oppervlak        | varchar(150)              | YES  |     | NULL    |
|
| woz_value            | int(15) unsigned zerofill | YES  | UNI | NULL    |
|
| reg_oppervlak_bn     | varchar(150)              | YES  |     | NULL    |
|
| waardeklasse         | int(10)                   | NO   | PRI | NULL    |
|
| waardepeildatum      | varchar(150)              | YES  |     | NULL    |
|
| zipandnumber         | varchar(150)              | YES  |     | NULL    |
|
+----------------------+---------------------------+------+-----+---------+-
---------------+

waardeklasse_average
+-------------------------+---------+------+-----+---------+-------+
| Field                   | Type    | Null | Key | Default | Extra |
+-------------------------+---------+------+-----+---------+-------+
| waardeklasse_average_id | int(11) | NO   |     | NULL    |       |
| waardeklasse_new        | int(10) | NO   | PRI | NULL    |       |
| lower                   | int(11) | NO   |     | NULL    |       |
| higher                  | int(11) | NO   |     | NULL    |       |
| average                 | int(11) | NO   | PRI | NULL    |       |
+-------------------------+---------+------+-----+---------+-------+

Body:
update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
inner join waardeklasse_average b use index (waardeklasse)
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average

Where condition is not needed. As you had already mention that condition in On clause.

Try above query.


问:
export parameterized variables in shellscript using sshpass
I have a use case similar to the below code. Need to export parameterized variables/identifier to remote shell script from a shell script. I used the below code but I cannot export the value. Please suggest how to do it.

A.sh (script 1)

```<code>#!/bin/bash
sshpass -p asdf ssh rock@host.com<<'ENDSSH'
export directory="$1"
sh /../B.sh
ENDSSH
</code>```

B.sh (script 2)

```<code>#!/bin/bash
echo directory=$directory
mkdir $directory

#Execution
sh A.sh '/data/2017-7-7/'

#output
directory=
</code>```

I get the value in the remote shell script when I hard code the value.

```<code>export directory='/data/2017-7-7/'
</code>```

I want to export parameterized variable, please suggest how to implement this.Thanks

答:
Just remove quotes from the first ENDSSH:

```<code>sshpass -p asdf ssh rock@host.com << ENDSSH
export directory="$1"
sh /../B.sh
ENDSSH
</code>```

According to the bash manual:

Here Documents

[...]

The format of here-documents is:

```<code>[n]<<[-]word
    here-document
delimiter
</code>```

No  parameter  and variable expansion, command substitution, arithmetic
  expansion, or pathname expansion is performed on word.  If any part  of
  word  is  quoted, the delimiter is the result of quote removal on word,
  and the lines in the  here-document  are  not  expanded.   If  word  is
  unquoted,  all  lines  of  the here-document are subjected to parameter
  expansion, command substitution, and arithmetic expansion, the  character
  sequence  \<newline>  is  ignored, and \ must be used to quote the
  characters \, $, and `.

[...]

Body:
I have a use case similar to the below code. Need to export parameterized variables/identifier to remote shell script from a shell script. I used the below code but I cannot export the value. Please suggest how to do it.

A.sh (script 1)

#!/bin/bash
sshpass -p asdf ssh rock@host.com<<'ENDSSH'
export directory="$1"
sh /../B.sh
ENDSSH

B.sh (script 2)

#!/bin/bash
echo directory=$directory
mkdir $directory

#Execution
sh A.sh '/data/2017-7-7/'

#output
directory=

I get the value in the remote shell script when I hard code the value.

export directory='/data/2017-7-7/'

I want to export parameterized variable, please suggest how to implement this.Thanks

Body:
Just remove quotes from the first ENDSSH:

sshpass -p asdf ssh rock@host.com << ENDSSH
export directory="$1"
sh /../B.sh
ENDSSH

According to the bash manual:

Here Documents

[...]

The format of here-documents is:

[n]<<[-]word
    here-document
delimiter

No  parameter  and variable expansion, command substitution, arithmetic
  expansion, or pathname expansion is performed on word.  If any part  of
  word  is  quoted, the delimiter is the result of quote removal on word,
  and the lines in the  here-document  are  not  expanded.   If  word  is
  unquoted,  all  lines  of  the here-document are subjected to parameter
  expansion, command substitution, and arithmetic expansion, the  character
  sequence  \<newline>  is  ignored, and \ must be used to quote the
  characters \, $, and `.

[...]


问:
How to check the overlapping time intervals from one type 2 SCD dimension
I have one problem identifying and fixing some records having overlapping time intervals, for one scd type 2 dimension.
   What I have is:

```<code>Bkey   Uid  startDate                       endDate
'John'  1   1990-01-01 (some time stamp)    2017-01-10 (some time stamp)
'John'  2   2016-11=03 (some time stamp)    2016-11-14 (some time stamp)
'John'  3   2016-11-14 (some time stamp)    2016-12-29 (some time stamp)
'John'  4   2016-12-29 (some time stamp)    2017-01-10 (some time stamp)
'John'  5   2017-01-10 (some time stamp)    2017-04-22 (some time stamp)
......
</code>```

I want to find (first) which are all the Johns having overlapping time periods, for a table having lots and lots of Johns and then to figure out a way to correct those overlapping time periods. For the latest I know there are some function LAGG, LEAD, which can handle that, but it eludes me how to find those over lappings.
Any hints?
Regards,

答:
[ 1 ] Following query will return overlapping time ranges:

```<code>SELECT  *,
        (
            SELECT  *
            FROM    @Dimension1 y
            WHERE   x.Bkey = y.Bkey
            AND     x.Uid <> y.Uid
            AND     NOT(x.startDate > y.endDate OR x.endDate < y.startDate)
            FOR XML RAW, ROOT, TYPE
        ) OverlappingTimeRanges
FROM    @Dimension1 x
</code>```

Full script:

```<code>DECLARE @Dimension1 TABLE (
    Bkey        VARCHAR(50) NOT NULL,
    Uid         INT NOT NULL,
    startDate   DATE NOT NULL,
    endDate     DATE NOT NULL,
        CHECK(startDate < endDate)
);
INSERT  @Dimension1
SELECT 'John',  1,   '1990-01-01', '2017-01-10' UNION ALL
SELECT 'John',  2,   '2016-11-03', '2016-11-14' UNION ALL
SELECT 'John',  3,   '2016-11-14', '2016-12-29' UNION ALL
SELECT 'John',  4,   '2016-12-29', '2017-01-10' UNION ALL
SELECT 'John',  5,   '2017-01-11', '2017-04-22';

SELECT  *,
        (
            SELECT  *
            FROM    @Dimension1 y
            WHERE   x.Bkey = y.Bkey
            AND     x.Uid <> y.Uid
            AND     NOT(x.startDate > y.endDate OR x.endDate < y.startDate)
            FOR XML RAW, ROOT, TYPE
        ) OverlappingTimeRanges
FROM    @Dimension1 x
</code>```

Demo here

[ 2 ] In order to find distinct groups of time ranges with overlapping original rows I would use following approach:

```<code>-- Edit 1
DECLARE @Groups TABLE (
    Bkey            VARCHAR(50) NOT NULL,
    Uid             INT NOT NULL,
    startDateNew    DATE NOT NULL,
    endDateNew      DATE NOT NULL,
        CHECK(startDateNew < endDateNew)
);
INSERT  @Groups
SELECT  x.Bkey, x.Uid, z.startDateNew, z.endDateNew
FROM    @Dimension1 x
OUTER APPLY (
    SELECT  MIN(y.startDate) AS startDateNew, MAX(y.endDate) AS endDateNew
    FROM    @Dimension1 y
    WHERE   x.Bkey = y.Bkey
    AND     NOT(x.startDate > y.endDate OR x.endDate < y.startDate)
) z
-- End of Edit 1

-- This returns distinct groups identified by DistinctGroupId together with all overlapping Uid(s) from current group
SELECT  *
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY b.Bkey, b.startDateNew, b.endDateNew) AS DistinctGroupId, b.*
    FROM (
        SELECT  DISTINCT a.Bkey, a.startDateNew, a.endDateNew
        FROM    @Groups a
    ) b
) c
OUTER APPLY (
    SELECT  d.Uid AS Overlapping_Uid
    FROM    @Groups d
    WHERE   c.Bkey = d.Bkey
    AND     c.startDateNew = d.startDateNew
    AND     c.endDateNew = d.endDateNew
) e

-- This returns distinct groups identified by DistinctGroupId together with an XML (XmlCol) which includes overlapping Uid(s)
SELECT  *
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY b.Bkey, b.startDateNew, b.endDateNew) AS DistinctGroupId, b.*
    FROM (
        SELECT  DISTINCT a.Bkey, a.startDateNew, a.endDateNew
        FROM    @Groups a
    ) b
) c
OUTER APPLY (
    SELECT (
    SELECT  d.Uid AS Overlapping_Uid
    FROM    @Groups d
    WHERE   c.Bkey = d.Bkey
    AND     c.startDateNew = d.startDateNew
    AND     c.endDateNew = d.endDateNew
    FOR XML RAW, TYPE
    ) AS XmlCol
) e
</code>```

Note: Last range used in my example is 'John',  5,   '2017-01-11', '2017-04-22'; and not 'John',  5,   '2017-01-10', '2017-04-22';. Also, data type used is DATE and not DATETIME[2][OFFSET].

Body:
I have one problem identifying and fixing some records having overlapping time intervals, for one scd type 2 dimension.
   What I have is:

Bkey   Uid  startDate                       endDate
'John'  1   1990-01-01 (some time stamp)    2017-01-10 (some time stamp)
'John'  2   2016-11=03 (some time stamp)    2016-11-14 (some time stamp)
'John'  3   2016-11-14 (some time stamp)    2016-12-29 (some time stamp)
'John'  4   2016-12-29 (some time stamp)    2017-01-10 (some time stamp)
'John'  5   2017-01-10 (some time stamp)    2017-04-22 (some time stamp)
......

I want to find (first) which are all the Johns having overlapping time periods, for a table having lots and lots of Johns and then to figure out a way to correct those overlapping time periods. For the latest I know there are some function LAGG, LEAD, which can handle that, but it eludes me how to find those over lappings.
Any hints?
Regards,

Body:
[ 1 ] Following query will return overlapping time ranges:

SELECT  *,
        (
            SELECT  *
            FROM    @Dimension1 y
            WHERE   x.Bkey = y.Bkey
            AND     x.Uid <> y.Uid
            AND     NOT(x.startDate > y.endDate OR x.endDate < y.startDate)
            FOR XML RAW, ROOT, TYPE
        ) OverlappingTimeRanges
FROM    @Dimension1 x

Full script:

DECLARE @Dimension1 TABLE (
    Bkey        VARCHAR(50) NOT NULL,
    Uid         INT NOT NULL,
    startDate   DATE NOT NULL,
    endDate     DATE NOT NULL,
        CHECK(startDate < endDate)
);
INSERT  @Dimension1
SELECT 'John',  1,   '1990-01-01', '2017-01-10' UNION ALL
SELECT 'John',  2,   '2016-11-03', '2016-11-14' UNION ALL
SELECT 'John',  3,   '2016-11-14', '2016-12-29' UNION ALL
SELECT 'John',  4,   '2016-12-29', '2017-01-10' UNION ALL
SELECT 'John',  5,   '2017-01-11', '2017-04-22';

SELECT  *,
        (
            SELECT  *
            FROM    @Dimension1 y
            WHERE   x.Bkey = y.Bkey
            AND     x.Uid <> y.Uid
            AND     NOT(x.startDate > y.endDate OR x.endDate < y.startDate)
            FOR XML RAW, ROOT, TYPE
        ) OverlappingTimeRanges
FROM    @Dimension1 x

Demo here

[ 2 ] In order to find distinct groups of time ranges with overlapping original rows I would use following approach:

-- Edit 1
DECLARE @Groups TABLE (
    Bkey            VARCHAR(50) NOT NULL,
    Uid             INT NOT NULL,
    startDateNew    DATE NOT NULL,
    endDateNew      DATE NOT NULL,
        CHECK(startDateNew < endDateNew)
);
INSERT  @Groups
SELECT  x.Bkey, x.Uid, z.startDateNew, z.endDateNew
FROM    @Dimension1 x
OUTER APPLY (
    SELECT  MIN(y.startDate) AS startDateNew, MAX(y.endDate) AS endDateNew
    FROM    @Dimension1 y
    WHERE   x.Bkey = y.Bkey
    AND     NOT(x.startDate > y.endDate OR x.endDate < y.startDate)
) z
-- End of Edit 1

-- This returns distinct groups identified by DistinctGroupId together with all overlapping Uid(s) from current group
SELECT  *
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY b.Bkey, b.startDateNew, b.endDateNew) AS DistinctGroupId, b.*
    FROM (
        SELECT  DISTINCT a.Bkey, a.startDateNew, a.endDateNew
        FROM    @Groups a
    ) b
) c
OUTER APPLY (
    SELECT  d.Uid AS Overlapping_Uid
    FROM    @Groups d
    WHERE   c.Bkey = d.Bkey
    AND     c.startDateNew = d.startDateNew
    AND     c.endDateNew = d.endDateNew
) e

-- This returns distinct groups identified by DistinctGroupId together with an XML (XmlCol) which includes overlapping Uid(s)
SELECT  *
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY b.Bkey, b.startDateNew, b.endDateNew) AS DistinctGroupId, b.*
    FROM (
        SELECT  DISTINCT a.Bkey, a.startDateNew, a.endDateNew
        FROM    @Groups a
    ) b
) c
OUTER APPLY (
    SELECT (
    SELECT  d.Uid AS Overlapping_Uid
    FROM    @Groups d
    WHERE   c.Bkey = d.Bkey
    AND     c.startDateNew = d.startDateNew
    AND     c.endDateNew = d.endDateNew
    FOR XML RAW, TYPE
    ) AS XmlCol
) e

Note: Last range used in my example is 'John',  5,   '2017-01-11', '2017-04-22'; and not 'John',  5,   '2017-01-10', '2017-04-22';. Also, data type used is DATE and not DATETIME[2][OFFSET].


问:
Apache Passenger + Rails + assets are not getting reflected
I am running rails application on Apache Passenger in development environment.
I wanted to add some css and javascript libraries in application.
So i added css in application.css, and javascript in application.js files.

Assets are not getting loaded.

I have also precompiled the assets by running -
rake assets:precompile
and then i restarted the server.

Is there anything which i am missing?

答:
You should try
bundle exec rake assets:clean

bundle exec rake assets:precompile

and then restart your server

Note: Please do a cross check in your application.css that you are requiring that file if not then add
*= require your_file_name.css


问:
Removing the second "|" on the last position
Here are some examples from my data:

```<code>a <-c("sp|Q9Y6W5|","sp|Q9HB90|,sp|Q9NQL2|","orf|NCBIAAYI_c_1_1023|",
     "orf|NCBIACEN_c_10_906|,orf|NCBIACEO_c_5_1142|",
      "orf|NCBIAAYI_c_258|,orf|aot172_c_6_302|,orf|aot180_c_2_405|")
</code>```

For a: The individual strings can contain even more entries of "sp|" and "orf"

The results have to be like this:

```<code>[1] "sp|Q9Y6W5" "sp|Q9HB90,sp|Q9NQL2" "orf|NCBIAAYI_c_1_1023"
   "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142"
   "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405"
</code>```

So the aim is to remove the last "|" for each "sp|" and "orf|" entry. It seems that "|" is a special challenge because it is a metacharacter in regular expressions. Furthermore, the length and composition of the "orf|" entries varying a lot. The only things they have in common is "orf|" or "sp|" at the beginning and that "|" is on the last position. I tried different things with gsub() but also with the stringr package or regexpr() or [:punct:], but nothing really worked. Maybe it was just the wrong combination.

答:
An easy alternative that might work. You need to escape the "|" using "\\|".

```<code># Input
a <-c("sp|Q9Y6W5|","sp|Q9HB90|,sp|Q9NQL2|","orf|NCBIAAYI_c_1_1023|",
      "orf|NCBIACEN_c_10_906|,orf|NCBIACEO_c_5_1142|",
      "orf|NCBIAAYI_c_258|,orf|aot172_c_6_302|,orf|aot180_c_2_405|")

# Expected output
b <- c("sp|Q9Y6W5", "sp|Q9HB90,sp|Q9NQL2", "orf|NCBIAAYI_c_1_1023" ,
       "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142" ,
       "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405")

res <- gsub("\\|,", ",", gsub("\\|$", "", a))

all(res == b)
#[1] TRUE
</code>```

You could construct a single regex call to gsub, but this is simple and easy to understand. The inner gsub looks for | and the end of the string and removes it. The outer gsub looks for ,| and replaces with ,.

Body:
Here are some examples from my data:

a <-c("sp|Q9Y6W5|","sp|Q9HB90|,sp|Q9NQL2|","orf|NCBIAAYI_c_1_1023|",
     "orf|NCBIACEN_c_10_906|,orf|NCBIACEO_c_5_1142|",
      "orf|NCBIAAYI_c_258|,orf|aot172_c_6_302|,orf|aot180_c_2_405|")

For a: The individual strings can contain even more entries of "sp|" and "orf"

The results have to be like this:

[1] "sp|Q9Y6W5" "sp|Q9HB90,sp|Q9NQL2" "orf|NCBIAAYI_c_1_1023"
   "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142"
   "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405"

So the aim is to remove the last "|" for each "sp|" and "orf|" entry. It seems that "|" is a special challenge because it is a metacharacter in regular expressions. Furthermore, the length and composition of the "orf|" entries varying a lot. The only things they have in common is "orf|" or "sp|" at the beginning and that "|" is on the last position. I tried different things with gsub() but also with the stringr package or regexpr() or [:punct:], but nothing really worked. Maybe it was just the wrong combination.

Body:
An easy alternative that might work. You need to escape the "|" using "\\|".

# Input
a <-c("sp|Q9Y6W5|","sp|Q9HB90|,sp|Q9NQL2|","orf|NCBIAAYI_c_1_1023|",
      "orf|NCBIACEN_c_10_906|,orf|NCBIACEO_c_5_1142|",
      "orf|NCBIAAYI_c_258|,orf|aot172_c_6_302|,orf|aot180_c_2_405|")

# Expected output
b <- c("sp|Q9Y6W5", "sp|Q9HB90,sp|Q9NQL2", "orf|NCBIAAYI_c_1_1023" ,
       "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142" ,
       "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405")

res <- gsub("\\|,", ",", gsub("\\|$", "", a))

all(res == b)
#[1] TRUE

You could construct a single regex call to gsub, but this is simple and easy to understand. The inner gsub looks for | and the end of the string and removes it. The outer gsub looks for ,| and replaces with ,.


问:
-event- can only appear on the left hand side of += or -=
I have an event in a loop. I am trying to prevent the same method being added to an event more than once. I've implemented the add and remove accessors.

However, I get an error stating that:

ItemsProcessed can only appear on the left hand side of += or -=

When I try to call them, even within the same class.

```<code>ItemsProcessed(this, new EventArgs()); // Produces error

public event EventHandler ItemsProcessed
{
    add
    {
        ItemsProcessed -= value;
        ItemsProcessed += value;
    }
    remove
    {
        ItemsProcessed -= value;
    }
}
</code>```

答:
With an explicit event, you need to provide your own backing store - either a delegate field or something like EventHandlerList. The current code is recursive. Try:

```<code>private EventHandler itemsProcessed;
public event EventHandler ItemsProcessed
{
    add
    {
        itemsProcessed-= value;
        itemsProcessed+= value;
    }

    remove
    {
        itemsProcessed-= value;
    }
}
</code>```

Then (and noting I'm being a little cautious about the "about to turn null" edge-case re threading):

```<code>var snapshot = itemsProcessed;
if(snapshot != null) snapshot(this, EventArgs.Empty);
</code>```

With more recent C# versions, this can be simplified:

```<code>itemsProcessed?.Invoke(this, EventArgs.Empty);
</code>```

Body:
I have an event in a loop. I am trying to prevent the same method being added to an event more than once. I've implemented the add and remove accessors.

However, I get an error stating that:

ItemsProcessed can only appear on the left hand side of += or -=

When I try to call them, even within the same class.

ItemsProcessed(this, new EventArgs()); // Produces error

public event EventHandler ItemsProcessed
{
    add
    {
        ItemsProcessed -= value;
        ItemsProcessed += value;
    }
    remove
    {
        ItemsProcessed -= value;
    }
}

Body:
With an explicit event, you need to provide your own backing store - either a delegate field or something like EventHandlerList. The current code is recursive. Try:

private EventHandler itemsProcessed;
public event EventHandler ItemsProcessed
{
    add
    {
        itemsProcessed-= value;
        itemsProcessed+= value;
    }

    remove
    {
        itemsProcessed-= value;
    }
}

Then (and noting I'm being a little cautious about the "about to turn null" edge-case re threading):

var snapshot = itemsProcessed;
if(snapshot != null) snapshot(this, EventArgs.Empty);

With more recent C# versions, this can be simplified:

itemsProcessed?.Invoke(this, EventArgs.Empty);


问:
Chrome on MacOS stopped trusting cert issued by self-signed CA
I am running a local development website. The certificate securing it is issued by my own internal certificate authority. I have added the certificate authority to the MacOS keychain and marked it as trusted.

This used to work. Over the weekend, it stopped working. I would love to say that I've changed nothing, but obviously something has changed. Nothing specific comes to mind (perhaps a Chrome auto-update after a restart?)

I am on Chrome Version 59.0.3071.115 (Official Build) (64-bit)

I have checked the local site with Opera and Firefox and it loads securely as intended. (I have added the CA cert to the respective trusted roots for each browser). Safari works well too. Only Chrome is giving me grief.

If I look at the developer tools, the security panel is sending mixed messages. It says the cert is valid, but complains that the page is not secure. It is not possible to view the cert:

答:
@dorian is right. The issue is explained in https://bugs.chromium.org/p/chromium/issues/detail?id=715969 . It was not the TeleText string bug that is described in the beginning. Rather, it was that I had generated a version 1 SSL cert, while it should have been a version 3 cert.

Instructions for creating version3 certs with OpenSSL:

Creating an x509 v3 user certificate by signing CSR


问:
Use simulate dates for today in Fluid
TYPO3 has the nice "simulate date" option in the admin panel.

But this doesn't propagate to fluid as in

```<code>{f:format.date(date: 'today' format: 'Y-m-d')}
</code>```

Apparently, this is php at work, not the TYPO3 API.

Is there a simple possibility to simulate a virtual "today" date and pass it to fluid?

答:
You could use install the PHP timecop extension and set the date initially in index.php.

Alternatively, open a feature request to fluid to support the simulated time.

Title: Use simulate dates for today in Fluid

Body:
TYPO3 has the nice "simulate date" option in the admin panel.

But this doesn't propagate to fluid as in

{f:format.date(date: 'today' format: 'Y-m-d')}

Apparently, this is php at work, not the TYPO3 API.

Is there a simple possibility to simulate a virtual "today" date and pass it to fluid?


问:
Fade out character by character in text using jQuery
In the code below I have a line of text "A B C" that I would like to fade out character by character, i.e. C is faded out first, then B and finally A. The code works, but I think that my solution is very clumpsy. If the text has more letters, then the code must be extended for each letter with callback after callback...

Can this be solved in a more neat way? Can the fadeOuts be placed in sequence instead of nested callbacks?

My final goal is to fade out a text character by character and then fade in a new text, character by character... Just like a Powerpoint animation :)

$(document).ready(function() {
  $("button").click(function() {
    $("#C").fadeOut(300, function() {
      $("#B").fadeOut(300, function() {
        $("#A").fadeOut(300);
      });
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <button>Click to fade out character by character</button><br><br>

  <div>
    <span id="A">A</span>
    <span id="B">B</span>
    <span id="C">C</span>
  </div></code>```

答:
You can first select span's in reversed order and then use each loop and inside use delay with (time * index) on fadeOut()

$('button').click(function() {
  $($("span").get().reverse()).each(function(i) {
    $(this).delay(400 * i).fadeOut(300)
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click to fade out character by character</button><br><br>

<div>
  <span id="A">A</span>
  <span id="B">B</span>
  <span id="C">C</span>
</div></code>```

Body:
In the code below I have a line of text "A B C" that I would like to fade out character by character, i.e. C is faded out first, then B and finally A. The code works, but I think that my solution is very clumpsy. If the text has more letters, then the code must be extended for each letter with callback after callback...

Can this be solved in a more neat way? Can the fadeOuts be placed in sequence instead of nested callbacks?

My final goal is to fade out a text character by character and then fade in a new text, character by character... Just like a Powerpoint animation :)

$(document).ready(function() {
  $("button").click(function() {
    $("#C").fadeOut(300, function() {
      $("#B").fadeOut(300, function() {
        $("#A").fadeOut(300);
      });
    });
  });
});

  <button>Click to fade out character by character</button>

    A
    B
    C

Body:
You can first select span's in reversed order and then use each loop and inside use delay with (time * index) on fadeOut()

$('button').click(function() {
  $($("span").get().reverse()).each(function(i) {
    $(this).delay(400 * i).fadeOut(300)
  })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click to fade out character by character</button><br><br>

<div>
  <span id="A">A</span>
  <span id="B">B</span>
  <span id="C">C</span>
</div>


问:
function returning a string of zeros in c
i trying to create a function that return an array of zeros us a char array
and print this array in a file text but when i return a string an addition char was returned

this the text file string the program wrote

this my fuction :

```<code> char *zeros_maker (int kj,int kj1)
{
     char *zeros;
    zeros = (char *) malloc(sizeof(char)*(kj-kj1));
    int i;
    for(i =0;i<kj-kj1;i++)
        zeros[i]='0';
    printf("%s\n",zeros);
    return zeros;
}
</code>```

the instruction i used when i printed in the file

```<code>fprintf(pFile,"%c%s%c &",34,zeros_maker(added_zeros,0),34);
</code>```

Thanks in advance

答:
Your code has a few basic issues, the main one is that it fails to terminate the string (and include space for the terminator).

Here's a fixed and cleaned-up version:

```<code>char * zeros_maker(size_t length)
{
  char *s = malloc(length + 1);
  if(s != NULL)
  {
    memset(s, '0', length);
    s[length - 1] = '\0';
  }
  return s;
}
</code>```

This has the following improvements over your code:

It simplifies the interface, just taking the number of zeroes that should be returned (the length of the returned string). Do the subtraction at the call site, where those two values make sense.

No cast of the return value from malloc(), and no scaling by sizeof (char) since I consider that pointless.

Check for NULL being returned by malloc() before using the memory.

Use memset() to set a range of bytes to a single value, that's a standard C function and much easier to know and verify than a custom loop.

Terminate the string, of course.

Call it like so:

```<code>char *zs = zeros_maker(kj - kj1);
puts(s);
free(s);
</code>```

Remember to free() the string once you're done with it.

Body:
i trying to create a function that return an array of zeros us a char array
and print this array in a file text but when i return a string an addition char was returned

this the text file string the program wrote

this my fuction :

 char *zeros_maker (int kj,int kj1)
{
     char *zeros;
    zeros = (char *) malloc(sizeof(char)*(kj-kj1));
    int i;
    for(i =0;i<kj-kj1;i++)
        zeros[i]='0';
    printf("%s\n",zeros);
    return zeros;
}

the instruction i used when i printed in the file

fprintf(pFile,"%c%s%c &",34,zeros_maker(added_zeros,0),34);

Thanks in advance

Body:
Your code has a few basic issues, the main one is that it fails to terminate the string (and include space for the terminator).

Here's a fixed and cleaned-up version:

char * zeros_maker(size_t length)
{
  char *s = malloc(length + 1);
  if(s != NULL)
  {
    memset(s, '0', length);
    s[length - 1] = '\0';
  }
  return s;
}

This has the following improvements over your code:

It simplifies the interface, just taking the number of zeroes that should be returned (the length of the returned string). Do the subtraction at the call site, where those two values make sense.

No cast of the return value from malloc(), and no scaling by sizeof (char) since I consider that pointless.

Check for NULL being returned by malloc() before using the memory.

Use memset() to set a range of bytes to a single value, that's a standard C function and much easier to know and verify than a custom loop.

Terminate the string, of course.

Call it like so:

char *zs = zeros_maker(kj - kj1);
puts(s);
free(s);

Remember to free() the string once you're done with it.


问:
Why does this sql query not work in pdo?
i'm trying to retrieve info from my database using PDO.

The code i'm using is

```<code>$input = $_GET['input'];

$inputvalue = $_GET['inputvalue'];

$db = DB::get_instance();
$query = $db->prepare('SELECT * FROM hwidex7 WHERE :input=:inputvalue');
$query->bindParam(':inputvalue', $inputvalue);
$query->bindParam(':input', $input);
$query->execute();
</code>```

答:
Both ways are wrong.

```<code>SELECT * FROM hwidex7 WHERE `HWID`='3087793810'
</code>```

Just try above query.

You will get Idea for same.

Body:
i'm trying to retrieve info from my database using PDO.

The code i'm using is

$input = $_GET['input'];

$inputvalue = $_GET['inputvalue'];

$db = DB::get_instance();
$query = $db->prepare('SELECT * FROM hwidex7 WHERE :input=:inputvalue');
$query->bindParam(':inputvalue', $inputvalue);
$query->bindParam(':input', $input);
$query->execute();

Body:
Both ways are wrong.

SELECT * FROM hwidex7 WHERE `HWID`='3087793810'

Just try above query.

You will get Idea for same.