问:
Angular 2, Event from enum
I have a problem I do not know how to make invisible the value 2 of the "Titulo" enum and that when I click on the value "no" (1) of the radio button "existio contacto" of coincidence.component.html is visible

This is coincidence html

        <md-card class="cards">
          {{titulo}}

    Number matching
                  3333333333

    existio contacto
                  <md-radio-group class="radio-vertical" [(ngModel)]="valorRadio" (change)="opcionNoExistioContacto($event)">
                    <md-radio-button value="0">Yes</md-radio-button>
                    <md-radio-button value="1">No</md-radio-button>
                    <md-radio-button value="2">Yes third</md-radio-button>
                  </md-radio-group>

                <md-select *ngIf="valorRadio == 1" placeholder="Causal" class="select_100">
                  <md-option value="0">Does not answer</md-option>
                  <md-option value="1">
                    Occupied phone</md-option>
                </md-select>
                <md-select *ngIf="valorRadio == 2" placeholder="No Contacto" [(ngModel)]="valorOpcion" class="select_100">
                  <md-option value="0">
                    Third does not provide new contact number but serves as reference</md-option>
                  <md-option value="1">
                    Third does not provide information</md-option>
                </md-select>

                    phone
                    <input type="tel" maxlength="10">

        </md-card>

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

<p>This is coincidence ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter
} from '@angular/core';
import {
  MdRadioChange
} from "@angular/material";

import {
  ValorGestionTelefonica
} from "app/dto/datos";

@Component({
  selector: 'app-coincidence',
  templateUrl: './coincidence.component.html',
  styleUrls: ['./coincidence.component.css']
})
export class CoincidenceComponent implements OnInit {
  @Input() titulo: number;
  @Input() indice: number;
  @Output() evaluarOpciones = new EventEmitter < ValorGestionTelefonica > ();

  constructor() {}

  ngOnInit() {}

  opcionNoExistioContacto(evento: MdRadioChange) {
    if (evento.source) {
      let valor = new ValorGestionTelefonica();
      valor.indice = this.indice;
      valor.valor = evento["value"];

      this.evaluarOpciones.emit(valor);
    }
  }
}</code>```

This is panel tres html

<app-coincidence *ngFor="let a of titulos; let i = index" [indice]=i [titulo]=a (evaluarOpciones)="evaluarOpciones($event)"></app-coincidence>```
</div>
</div>
</p>

<p>This is panel tres ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
  Component,
  OnInit,
  Input,
  Provider
} from '@angular/core';
import {
  ValorGestionTelefonica
} from '../../dto/datos';

enum Titulo {
  'Celular Coincidente con Reconocer' = 1, 'Primer Celular Reconocer' = 2
}
@Component({
  selector: 'app-panel-tres',
  templateUrl: './panel-tres.component.html',
  styleUrls: ['./panel-tres.component.css']
})
export class PanelTresComponent implements OnInit {

  titulos: string[];

  constructor() {}

  ngOnInit() {
    let titulos = Object.keys(Titulo);
    this.titulos = titulos.slice(titulos.length / 2);
    console.log(titulos);
    console.log("titulos");

  }

  evaluarOpciones(valor: ValorGestionTelefonica): void {
    console.log(valor.valor + "--" + valor.indice);
  }

}</code>```

class ValorGestionTelefonica

export class ValorGestionTelefonica {
  valor: any;
  indice: number;
}```

答:
To summarize your issue to ensure I have it correct

You are iterating across an enum of 2 keys in an ngFor. You want the second to appear only after some event occurs on the first.

1) If the enum is always 2 items long, why bother with any of this? You could very simply just directly code the two elements and tie them around in ngIf or something

```<code><coincidence [indice]=1 [titulo]='first title' (click)="showSecond = true"></coincidence>
<coincidence [indice]=2 [titulo]='second title' *ngIf="showSecond></coincidence>
</code>```

2) If your enum is of a dynamic length or you want to manage it programmatically, then I would handle it by putting your titles over in an object which contains a showMe boolean flag. For example,

In your panel-tres.ts

```<code>let titulosKeys = Object.keys(Titulo);
let titulosList = titulos.slice(titulos.length / 2);
this.titulos = [];
titulosList.forEach(titulo => {

  let showMe;
  if(titulo == 'Celular Coincidente con Reconocer') showMe = true;
  else showMe = false;

  this.titulos.push({
     titulo: titulo,
     showMe: showMe
  });

});
</code>```

then update your coincidence.html template to reflect that change

```<code><div class="row" *ngIf="titulo.showMe">
  <div class="small-12 columns">
  <md-card class="cards">
    <span>{{titulo.titulo}}</span>
    <div class="row">
  ...
</code>```

Then capture the click event and change the showMe var of the item you want to show or hide (might need to bubble up the event back to panel-tres via an EventEmitter or something)

You might want to play around with the typings involved but that will get you setup

Title: Angular 2, Event from enum

Body:
I have a problem I do not know how to make invisible the value 2 of the "Titulo" enum and that when I click on the value "no" (1) of the radio button "existio contacto" of coincidence.component.html is visible

This is coincidence html

        <md-card class="cards">
          {{titulo}}

    Number matching
                  3333333333

    existio contacto
                  <md-radio-group class="radio-vertical" [(ngModel)]="valorRadio" (change)="opcionNoExistioContacto($event)">
                    <md-radio-button value="0">Yes</md-radio-button>
                    <md-radio-button value="1">No</md-radio-button>
                    <md-radio-button value="2">Yes third</md-radio-button>
                  </md-radio-group>

                <md-select *ngIf="valorRadio == 1" placeholder="Causal" class="select_100">
                  <md-option value="0">Does not answer</md-option>
                  <md-option value="1">
                    Occupied phone</md-option>
                </md-select>
                <md-select *ngIf="valorRadio == 2" placeholder="No Contacto" [(ngModel)]="valorOpcion" class="select_100">
                  <md-option value="0">
                    Third does not provide new contact number but serves as reference</md-option>
                  <md-option value="1">
                    Third does not provide information</md-option>
                </md-select>

                    phone
                    <input type="tel" maxlength="10">

        </md-card>

This is coincidence ts

import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter
} from '@angular/core';
import {
  MdRadioChange
} from "@angular/material";

import {
  ValorGestionTelefonica
} from "app/dto/datos";

@Component({
  selector: 'app-coincidence',
  templateUrl: './coincidence.component.html',
  styleUrls: ['./coincidence.component.css']
})
export class CoincidenceComponent implements OnInit {
  @Input() titulo: number;
  @Input() indice: number;
  @Output() evaluarOpciones = new EventEmitter < ValorGestionTelefonica > ();

  constructor() {}

  ngOnInit() {}

  opcionNoExistioContacto(evento: MdRadioChange) {
    if (evento.source) {
      let valor = new ValorGestionTelefonica();
      valor.indice = this.indice;
      valor.valor = evento["value"];

      this.evaluarOpciones.emit(valor);
    }
  }
}

This is panel tres html

<app-coincidence *ngFor="let a of titulos; let i = index" [indice]=i [titulo]=a (evaluarOpciones)="evaluarOpciones($event)"></app-coincidence>

This is panel tres ts

import {
  Component,
  OnInit,
  Input,
  Provider
} from '@angular/core';
import {
  ValorGestionTelefonica
} from '../../dto/datos';

enum Titulo {
  'Celular Coincidente con Reconocer' = 1, 'Primer Celular Reconocer' = 2
}
@Component({
  selector: 'app-panel-tres',
  templateUrl: './panel-tres.component.html',
  styleUrls: ['./panel-tres.component.css']
})
export class PanelTresComponent implements OnInit {

  titulos: string[];

  constructor() {}

  ngOnInit() {
    let titulos = Object.keys(Titulo);
    this.titulos = titulos.slice(titulos.length / 2);
    console.log(titulos);
    console.log("titulos");

  }

  evaluarOpciones(valor: ValorGestionTelefonica): void {
    console.log(valor.valor + "--" + valor.indice);
  }

}

class ValorGestionTelefonica

export class ValorGestionTelefonica {
  valor: any;
  indice: number;
}

Body:
To summarize your issue to ensure I have it correct

You are iterating across an enum of 2 keys in an ngFor. You want the second to appear only after some event occurs on the first.

1) If the enum is always 2 items long, why bother with any of this? You could very simply just directly code the two elements and tie them around in ngIf or something

<coincidence [indice]=1 [titulo]='first title' (click)="showSecond = true"></coincidence>
<coincidence [indice]=2 [titulo]='second title' *ngIf="showSecond></coincidence>

2) If your enum is of a dynamic length or you want to manage it programmatically, then I would handle it by putting your titles over in an object which contains a showMe boolean flag. For example,

In your panel-tres.ts

let titulosKeys = Object.keys(Titulo);
let titulosList = titulos.slice(titulos.length / 2);
this.titulos = [];
titulosList.forEach(titulo => {

  let showMe;
  if(titulo == 'Celular Coincidente con Reconocer') showMe = true;
  else showMe = false;

  this.titulos.push({
     titulo: titulo,
     showMe: showMe
  });

});

then update your coincidence.html template to reflect that change

<div class="row" *ngIf="titulo.showMe">
  <div class="small-12 columns">
  <md-card class="cards">
    <span>{{titulo.titulo}}</span>
    <div class="row">
  ...

Then capture the click event and change the showMe var of the item you want to show or hide (might need to bubble up the event back to panel-tres via an EventEmitter or something)

You might want to play around with the typings involved but that will get you setup


来源: stackexchange

问:
Make outer div be automatically the same height as its floating content
I want the outer div, which is black to wrap its divs floating within it. I dont want to use style='height: 200px in the div with the outerdiv id as I want it to be automatically the height of its content (eg, the floating divs).

```<code><div id='outerdiv' style='border: 1px solid black;background-color: black;'>
<div style='width=300px;border: red 1px dashed;float: left;'>
    <p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>

<div style='width=300px;border: red 1px dashed;float: right;'>
    <p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
</div>
</code>```

How to achieve this?

答:
Use jQuery:

Set Parent Height = Child offsetHeight.

```<code>$(document).ready(function() {
    $(parent).css("height", $(child).attr("offsetHeight"));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want the outer div, which is black to wrap its divs floating within it. I dont want to use style='height: 200px in the div with the outerdiv id as I want it to be automatically the height of its content (eg, the floating divs).

xxxxxxxxxxxxxxxxxxxxxxxxxxxxx

zzzzzzzzzzzzzzzzzzzzzzzzzzzzz

How to achieve this?

Body:
Use jQuery:

Set Parent Height = Child offsetHeight.

$(document).ready(function() {
    $(parent).css("height", $(child).attr("offsetHeight"));
}


问:
Redirecting to a new tab in PHP
I have seen this question being asked many times here, but I couldn't get an answer that works!

i am trying to redirect to a load.php TO A NEW TAB using the following script:

```<code>echo '<script>window.open("load.php","_blank)</script>';
</code>```

for some reason it is not working and it stays on the same page.

i am using chrome!

is there any possible way to redirect to a new tab?
thanks a lot

答:
You're missing a quote mark after _blank.

Try this:

```<code>echo '<script>window.open("load.php","_blank")</script>';
</code>```

Title: Redirecting to a new tab in PHP

Body:
I have seen this question being asked many times here, but I couldn't get an answer that works!

i am trying to redirect to a load.php TO A NEW TAB using the following script:

echo '';

for some reason it is not working and it stays on the same page.

i am using chrome!

is there any possible way to redirect to a new tab?
thanks a lot

Body:
You're missing a quote mark after _blank.

Try this:

echo '<script>window.open("load.php","_blank")</script>';


问:
Timing a single block in Jupyter with one line of code
How do you time a single block of a Jupyter notebook with a single line of. Python code?

%time and %timeit don't cut it, but there must be a way to do this!

```<code>%time
%timeit
start = time.time()

## Create a Pandas dataframe from reader
df = pd.DataFrame(reader.readrows())
end = time.time()
print('Time taken ', end-start,' seconds')
</code>```

Thanks, Nic

答:
Use the cell magic %%timeit (with two %) to time a whole jupyter cell, instead of just a single line. The cell magic must come before any python code in the cell.

http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-timeit

Body:
How do you time a single block of a Jupyter notebook with a single line of. Python code?

%time and %timeit don't cut it, but there must be a way to do this!

%time
%timeit
start = time.time()

## Create a Pandas dataframe from reader
df = pd.DataFrame(reader.readrows())
end = time.time()
print('Time taken ', end-start,' seconds')

Thanks, Nic


问:
Always get a certain DIV, even if the children div is clicked
I have a div called box, within inside another div called container.

When the div box is clicked I always get its own ID and everything is perfect, but when the container div is clicked, I want to get the box's id and not the container.

How can I manage it?
I'm new in web developing, thanks for any help!

P.S. I'm coding most in Angular, and if it really needed in JQuery

The code is 1000+ rows...

The main code I'm talking about is:

```<code><div id='box' style='width:200px; height:300px;'>
 <div id='container'> A table or some text </div>
</div>
</code>```

When one of the two divs are clicked, after getting the position of the click, I get the element's id by position, but sometimes I get the id "box" and other times I get the id "container".
The point is that I always want to get the "box" id, and never the container, even if the container has been clicked, I want to get the id of the box that contain that "container"

Hope it's clear..

答:
I think what your referring to is event bubbling, take a look at the example on the razden link which will have a fully working example (very clear and simple one)

Here is some further detailed explaination on how it works:
http://www.radzen.com/blog/angular-event-bubbling/

If the below was wrapped in a component

```<code>`<div><button>click me</button></div>`
</code>```

Then you could add a click handler to it in order to perform a specific task of your liking.

Body:
I have a div called box, within inside another div called container.

When the div box is clicked I always get its own ID and everything is perfect, but when the container div is clicked, I want to get the box's id and not the container.

How can I manage it?
I'm new in web developing, thanks for any help!

P.S. I'm coding most in Angular, and if it really needed in JQuery

The code is 1000+ rows...

The main code I'm talking about is:

 A table or some text

When one of the two divs are clicked, after getting the position of the click, I get the element's id by position, but sometimes I get the id "box" and other times I get the id "container".
The point is that I always want to get the "box" id, and never the container, even if the container has been clicked, I want to get the id of the box that contain that "container"

Hope it's clear..

Body:
I think what your referring to is event bubbling, take a look at the example on the razden link which will have a fully working example (very clear and simple one)

Here is some further detailed explaination on how it works:
http://www.radzen.com/blog/angular-event-bubbling/

If the below was wrapped in a component

`<div><button>click me</button></div>`

Then you could add a click handler to it in order to perform a specific task of your liking.


问:
Expanding / Collapsing Cards in Recycler View sometimes result in whitespaces and drawing bugs

The Problem

I have a recycler view with card items. These card items contain only text and are expandable.It looks like this Collapsed Expanded

Now I expand and collapse one of them sometimes and scroll around and somehow there appears now more whitespace between the cards:
Whitespace between cards

Moreover, for cards with long text when I click to collapse them, this appears:
Big Cards

The Code

xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.ramotion.foldingcell.FoldingCell
        android:id="@+id/folding_cell"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        app:backSideColor="#F5F5F5">

        <FrameLayout
            android:id="@+id/cell_content_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="300dp"
            android:visibility="gone">

            <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:cardview="http://schemas.android.com/apk/res-auto"
                xmlns:custom="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:id="@+id/movie_card2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:foreground="?attr/selectableItemBackground"
                android:minHeight="300dp"
                cardview:cardBackgroundColor="@color/card_background"
                cardview:cardCornerRadius="1dp"
                cardview:cardElevation="4dp"
                cardview:cardUseCompatPadding="true">

                <RelativeLayout
                    android:id="@+id/review_item2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:orientation="vertical">

                    <View
                        android:id="@+id/review_detail_header"
                        android:layout_width="match_parent"
                        android:layout_height="50dp"
                        android:background="@color/material_red_400" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@id/review_detail_header"
                        android:layout_alignTop="@id/review_detail_header"
                        android:layout_centerHorizontal="true"
                        android:gravity="center"
                        android:text="Review Details"
                        android:textColor="@color/text_secondary" />

                    <ImageView
                        android:id="@+id/ic"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/review_detail_header"
                        android:layout_marginTop="@dimen/material_layout_keylines_horizontal_margin"
                        android:adjustViewBounds="true"
                        android:paddingLeft="@dimen/material_layout_keylines_horizontal_margin"
                        android:paddingRight="@dimen/material_layout_keylines_horizontal_margin"
                        android:src="@drawable/ic_account_circle_white_24dp"
                        android:tint="@color/accent"
                        tools:ignore="ContentDescription" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_author2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/review_detail_header"
                        android:layout_gravity="center_vertical"
                        android:layout_marginTop="@dimen/material_layout_keylines_horizontal_margin"
                        android:layout_toRightOf="@id/ic"
                        android:textSize="14sp"
                        custom:robotoType="bold"
                        tools:text="User Name" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_body2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/review_author2"
                        android:layout_marginBottom="@dimen/material_layout_keylines_horizontal_margin"
                        android:layout_marginLeft="56dp"
                        android:layout_marginRight="24dp"
                        android:layout_marginTop="@dimen/material_layout_vertical_spacing_between_content_areas"
                        android:layout_weight="1"
                        android:ellipsize="none"
                        android:maxLines="100"
                        android:scrollHorizontally="false"
                        android:textSize="14sp"
                        custom:robotoType="regular"
                        tools:text="The movie's review goes here..." />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_spoiler2"
                        style="@style/ReviewBodyStyle"
                        android:text="@string/reviews_alert"
                        android:textColor="@color/primary"
                        android:visibility="gone"
                        custom:robotoType="bold" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_time2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:layout_below="@+id/review_body2"
                        android:layout_margin="@dimen/material_layout_keylines_horizontal_margin"
                        android:textSize="@dimen/material_layout_keylines_horizontal_margin"
                        android:visibility="gone"
                        custom:robotoType="regular"
                        tools:text="01 Jan 2016" />

                </RelativeLayout>

            </android.support.v7.widget.CardView>

        </FrameLayout>

        <FrameLayout
            android:id="@+id/cell_title_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:cardview="http://schemas.android.com/apk/res-auto"
                xmlns:custom="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:id="@+id/movie_card"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:foreground="?attr/selectableItemBackground"
                cardview:cardBackgroundColor="@color/card_background"
                cardview:cardCornerRadius="1dp"
                cardview:cardElevation="4dp"
                cardview:cardUseCompatPadding="true">

                <RelativeLayout
                    android:id="@+id/review_item"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="?attr/selectableItemBackground"
                    android:clickable="true"
                    android:orientation="vertical"
                    android:padding="@dimen/material_layout_keylines_horizontal_margin">

                    <ImageView
                        android:id="@+id/ic2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentStart="true"
                        android:adjustViewBounds="true"
                        android:src="@drawable/ic_account_circle_white_24dp"
                        android:tint="@color/accent"
                        tools:ignore="ContentDescription" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_author"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/material_layout_keylines_horizontal_margin"
                        android:layout_toRightOf="@+id/ic2"
                        custom:robotoType="bold"
                        android:textSize="14sp"
                        tools:text="User Name" />

                    <!-- Review open icon -->
                    <ImageView
                        android:id="@+id/review_open"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:adjustViewBounds="true"
                        android:src="@drawable/ic_open_in_new_white_24dp"
                        android:tint="@color/accent"
                        tools:ignore="contentDescription" />

                    <!-- Review Body -->

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_body"
                        style="@style/ReviewBodyStyle"
                        android:layout_marginLeft="40dp"
                        android:layout_marginRight="8dp"
                        android:layout_below="@+id/review_spoiler"
                        custom:robotoType="regular"
                        tools:text="The movie's review goes here..." />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_spoiler"
                        style="@style/ReviewBodyStyle"
                        android:layout_below="@id/review_open"
                        android:text="@string/reviews_alert"
                        android:textColor="@color/primary"
                        android:layout_marginLeft="40dp"
                        android:layout_marginRight="8dp"
                        android:visibility="gone"
                        custom:robotoType="bold" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_time"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:layout_below="@+id/review_body"
                        android:layout_margin="@dimen/material_layout_keylines_horizontal_margin"
                        android:textSize="@dimen/material_layout_keylines_horizontal_margin"
                        android:visibility="gone"
                        custom:robotoType="regular"
                        tools:text="01 Jan 2016" />

                </RelativeLayout>

            </android.support.v7.widget.CardView>

        </FrameLayout>
    </com.ramotion.foldingcell.FoldingCell>
</layout>
</code>```

The adapter:

```<code>public class ReviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public ArrayList<Review> reviewList;
    public int foldingCellPosition = -1;
    public FoldingCell currentFoldingCell;
    // Constructor
    public ReviewAdapter(ArrayList<Review> reviewList) {
        this.reviewList = reviewList;
    }

    // RecyclerView methods
    @Override
    public int getItemCount() {
        return reviewList.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_review, parent, false);
        return new ReviewViewHolder(v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        Review review = reviewList.get(position);
        ReviewViewHolder holder = (ReviewViewHolder) viewHolder;
        if (position == foldingCellPosition) {
            holder.binding.foldingCell.unfold(true);
            holder.binding.reviewBody2.setText(review.getComment());
            holder.binding.reviewAuthor2.setText(review.getUsername());
            return;
        }

        holder.binding.foldingCell.fold(true);
        holder.binding.reviewAuthor.setText(review.getUsername());
        if (review.isHasSpoiler()) {
            holder.binding.reviewBody.setVisibility(View.GONE);
            holder.binding.reviewSpoiler.setVisibility(View.VISIBLE);
        } else {
            holder.binding.reviewBody.setText(review.getComment());
            holder.binding.reviewBody.setVisibility(View.VISIBLE);
            holder.binding.reviewSpoiler.setVisibility(View.GONE);
        }
        holder.binding.reviewTime.setText(review.getCreatedAt());
    }

    // ViewHolder
    public class ReviewViewHolder extends RecyclerView.ViewHolder {
        ItemListReviewBinding binding;

        public ReviewViewHolder(final ViewGroup itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);

            binding.reviewItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //       onReviewClickListener.onReviewClicked(getAdapterPosition());
                    Log.e("TEST", "CLIKC");

                    if (foldingCellPosition != -1) {
                        currentFoldingCell.fold(false);
                    }
                    currentFoldingCell = binding.foldingCell;
                    binding.reviewBody2.setText(reviewList.get(getAdapterPosition()).getComment());
                    binding.reviewAuthor2.setText(reviewList.get(getAdapterPosition()).getUsername());
                    binding.foldingCell.toggle(false);
                    foldingCellPosition = getAdapterPosition();

                }
            });

            binding.reviewItem2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    binding.reviewItem2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            foldingCellPosition = -1;
                            binding.foldingCell.fold(false);
                        }
                    });
                }
            });

        }
    }
}
</code>```

How the recycler view is created:

```<code>  layoutManager = new LinearLayoutManager(getContext());
     mBinding.movieDetailReviewListRvReviews.setHasFixedSize(true);
     mBinding.movieDetailReviewListRvReviews.setLayoutManager(layoutManager);
     mBinding.movieDetailReviewListRvReviews.setAdapter(adapter);
</code>```

What I tried so far

I really dont have any idea why this happens.
However I tried notifyDataSetChanged() after each collapse/expand as well as invalidate().

Edit

For the collapsing / expanding effect I use this library:https://github.com/Juriv/folding-cell-android

答:
Actually there were a lot of problems with my code. First of all, as rom4ek mentioned, I had to change foldingCellPosition = getAdapterPosition() to foldingCellPosition = getLayoutPosition(). The next Problem, was this call:

```<code>if(foldingCellPosition != -1) {
     currentFoldingCell.fold(false);
}
</code>```

Not visible views should fold, which resulted in strange behaviour, so I added this code:

```<code>  public void checkForHide(int first, int last){
        if(foldingCellPosition != -1){
            if(foldingCellPosition < first || foldingCellPosition > last){
                foldingCellPosition = -1;
            }
        }
    }
</code>```

If the unfolded view is not visible the folding cellposition will set to -1 instead of folding it manually.

It is called from the Fragment here:

```<code>  mBinding.movieDetailReviewListRvReviews.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // Load more data if reached the end of the list
                adapter.checkForHide(layoutManager.findFirstVisibleItemPosition(), layoutManager.findLastVisibleItemPosition());

                if (layoutManager.findLastVisibleItemPosition() == adapter.reviewList.size() - 1 && !isLoadingLocked && !isLoading) {
                    if (pageToDownload < totalPages) {
                        mBinding.layoutContent.pbLoadingMore.setVisibility(View.VISIBLE);
                        downloadMovieReviews();
                    }
                }
            }
        });
</code>```

Body:
The Problem

I have a recycler view with card items. These card items contain only text and are expandable.It looks like this Collapsed Expanded

Now I expand and collapse one of them sometimes and scroll around and somehow there appears now more whitespace between the cards:
Whitespace between cards

Moreover, for cards with long text when I click to collapse them, this appears:
Big Cards

The Code

xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.ramotion.foldingcell.FoldingCell
        android:id="@+id/folding_cell"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        app:backSideColor="#F5F5F5">

        <FrameLayout
            android:id="@+id/cell_content_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="300dp"
            android:visibility="gone">

            <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:cardview="http://schemas.android.com/apk/res-auto"
                xmlns:custom="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:id="@+id/movie_card2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:foreground="?attr/selectableItemBackground"
                android:minHeight="300dp"
                cardview:cardBackgroundColor="@color/card_background"
                cardview:cardCornerRadius="1dp"
                cardview:cardElevation="4dp"
                cardview:cardUseCompatPadding="true">

                <RelativeLayout
                    android:id="@+id/review_item2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:orientation="vertical">

                    <View
                        android:id="@+id/review_detail_header"
                        android:layout_width="match_parent"
                        android:layout_height="50dp"
                        android:background="@color/material_red_400" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@id/review_detail_header"
                        android:layout_alignTop="@id/review_detail_header"
                        android:layout_centerHorizontal="true"
                        android:gravity="center"
                        android:text="Review Details"
                        android:textColor="@color/text_secondary" />

                    <ImageView
                        android:id="@+id/ic"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/review_detail_header"
                        android:layout_marginTop="@dimen/material_layout_keylines_horizontal_margin"
                        android:adjustViewBounds="true"
                        android:paddingLeft="@dimen/material_layout_keylines_horizontal_margin"
                        android:paddingRight="@dimen/material_layout_keylines_horizontal_margin"
                        android:src="@drawable/ic_account_circle_white_24dp"
                        android:tint="@color/accent"
                        tools:ignore="ContentDescription" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_author2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/review_detail_header"
                        android:layout_gravity="center_vertical"
                        android:layout_marginTop="@dimen/material_layout_keylines_horizontal_margin"
                        android:layout_toRightOf="@id/ic"
                        android:textSize="14sp"
                        custom:robotoType="bold"
                        tools:text="User Name" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_body2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/review_author2"
                        android:layout_marginBottom="@dimen/material_layout_keylines_horizontal_margin"
                        android:layout_marginLeft="56dp"
                        android:layout_marginRight="24dp"
                        android:layout_marginTop="@dimen/material_layout_vertical_spacing_between_content_areas"
                        android:layout_weight="1"
                        android:ellipsize="none"
                        android:maxLines="100"
                        android:scrollHorizontally="false"
                        android:textSize="14sp"
                        custom:robotoType="regular"
                        tools:text="The movie's review goes here..." />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_spoiler2"
                        style="@style/ReviewBodyStyle"
                        android:text="@string/reviews_alert"
                        android:textColor="@color/primary"
                        android:visibility="gone"
                        custom:robotoType="bold" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_time2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:layout_below="@+id/review_body2"
                        android:layout_margin="@dimen/material_layout_keylines_horizontal_margin"
                        android:textSize="@dimen/material_layout_keylines_horizontal_margin"
                        android:visibility="gone"
                        custom:robotoType="regular"
                        tools:text="01 Jan 2016" />

                </RelativeLayout>

            </android.support.v7.widget.CardView>

        </FrameLayout>

        <FrameLayout
            android:id="@+id/cell_title_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:cardview="http://schemas.android.com/apk/res-auto"
                xmlns:custom="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:id="@+id/movie_card"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:foreground="?attr/selectableItemBackground"
                cardview:cardBackgroundColor="@color/card_background"
                cardview:cardCornerRadius="1dp"
                cardview:cardElevation="4dp"
                cardview:cardUseCompatPadding="true">

                <RelativeLayout
                    android:id="@+id/review_item"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="?attr/selectableItemBackground"
                    android:clickable="true"
                    android:orientation="vertical"
                    android:padding="@dimen/material_layout_keylines_horizontal_margin">

                    <ImageView
                        android:id="@+id/ic2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentStart="true"
                        android:adjustViewBounds="true"
                        android:src="@drawable/ic_account_circle_white_24dp"
                        android:tint="@color/accent"
                        tools:ignore="ContentDescription" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_author"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/material_layout_keylines_horizontal_margin"
                        android:layout_toRightOf="@+id/ic2"
                        custom:robotoType="bold"
                        android:textSize="14sp"
                        tools:text="User Name" />

                    <ImageView
                        android:id="@+id/review_open"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:adjustViewBounds="true"
                        android:src="@drawable/ic_open_in_new_white_24dp"
                        android:tint="@color/accent"
                        tools:ignore="contentDescription" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_body"
                        style="@style/ReviewBodyStyle"
                        android:layout_marginLeft="40dp"
                        android:layout_marginRight="8dp"
                        android:layout_below="@+id/review_spoiler"
                        custom:robotoType="regular"
                        tools:text="The movie's review goes here..." />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_spoiler"
                        style="@style/ReviewBodyStyle"
                        android:layout_below="@id/review_open"
                        android:text="@string/reviews_alert"
                        android:textColor="@color/primary"
                        android:layout_marginLeft="40dp"
                        android:layout_marginRight="8dp"
                        android:visibility="gone"
                        custom:robotoType="bold" />

                    <com.mt.moviesiwanttowatch.ui.widget.TextViewRoboto
                        android:id="@+id/review_time"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:layout_below="@+id/review_body"
                        android:layout_margin="@dimen/material_layout_keylines_horizontal_margin"
                        android:textSize="@dimen/material_layout_keylines_horizontal_margin"
                        android:visibility="gone"
                        custom:robotoType="regular"
                        tools:text="01 Jan 2016" />

                </RelativeLayout>

            </android.support.v7.widget.CardView>

        </FrameLayout>
    </com.ramotion.foldingcell.FoldingCell>
</layout>

The adapter:

public class ReviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public ArrayList<Review> reviewList;
    public int foldingCellPosition = -1;
    public FoldingCell currentFoldingCell;
    // Constructor
    public ReviewAdapter(ArrayList<Review> reviewList) {
        this.reviewList = reviewList;
    }

    // RecyclerView methods
    @Override
    public int getItemCount() {
        return reviewList.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ViewGroup v = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_review, parent, false);
        return new ReviewViewHolder(v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        Review review = reviewList.get(position);
        ReviewViewHolder holder = (ReviewViewHolder) viewHolder;
        if (position == foldingCellPosition) {
            holder.binding.foldingCell.unfold(true);
            holder.binding.reviewBody2.setText(review.getComment());
            holder.binding.reviewAuthor2.setText(review.getUsername());
            return;
        }

        holder.binding.foldingCell.fold(true);
        holder.binding.reviewAuthor.setText(review.getUsername());
        if (review.isHasSpoiler()) {
            holder.binding.reviewBody.setVisibility(View.GONE);
            holder.binding.reviewSpoiler.setVisibility(View.VISIBLE);
        } else {
            holder.binding.reviewBody.setText(review.getComment());
            holder.binding.reviewBody.setVisibility(View.VISIBLE);
            holder.binding.reviewSpoiler.setVisibility(View.GONE);
        }
        holder.binding.reviewTime.setText(review.getCreatedAt());
    }

    // ViewHolder
    public class ReviewViewHolder extends RecyclerView.ViewHolder {
        ItemListReviewBinding binding;

        public ReviewViewHolder(final ViewGroup itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);

            binding.reviewItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //       onReviewClickListener.onReviewClicked(getAdapterPosition());
                    Log.e("TEST", "CLIKC");

                    if (foldingCellPosition != -1) {
                        currentFoldingCell.fold(false);
                    }
                    currentFoldingCell = binding.foldingCell;
                    binding.reviewBody2.setText(reviewList.get(getAdapterPosition()).getComment());
                    binding.reviewAuthor2.setText(reviewList.get(getAdapterPosition()).getUsername());
                    binding.foldingCell.toggle(false);
                    foldingCellPosition = getAdapterPosition();

                }
            });

            binding.reviewItem2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    binding.reviewItem2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            foldingCellPosition = -1;
                            binding.foldingCell.fold(false);
                        }
                    });
                }
            });

        }
    }
}

How the recycler view is created:

  layoutManager = new LinearLayoutManager(getContext());
     mBinding.movieDetailReviewListRvReviews.setHasFixedSize(true);
     mBinding.movieDetailReviewListRvReviews.setLayoutManager(layoutManager);
     mBinding.movieDetailReviewListRvReviews.setAdapter(adapter);

What I tried so far

I really dont have any idea why this happens.
However I tried notifyDataSetChanged() after each collapse/expand as well as invalidate().

Edit

For the collapsing / expanding effect I use this library:https://github.com/Juriv/folding-cell-android

Body:
Actually there were a lot of problems with my code. First of all, as rom4ek mentioned, I had to change foldingCellPosition = getAdapterPosition() to foldingCellPosition = getLayoutPosition(). The next Problem, was this call:

if(foldingCellPosition != -1) {
     currentFoldingCell.fold(false);
}

Not visible views should fold, which resulted in strange behaviour, so I added this code:

  public void checkForHide(int first, int last){
        if(foldingCellPosition != -1){
            if(foldingCellPosition < first || foldingCellPosition > last){
                foldingCellPosition = -1;
            }
        }
    }

If the unfolded view is not visible the folding cellposition will set to -1 instead of folding it manually.

It is called from the Fragment here:

  mBinding.movieDetailReviewListRvReviews.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // Load more data if reached the end of the list
                adapter.checkForHide(layoutManager.findFirstVisibleItemPosition(), layoutManager.findLastVisibleItemPosition());

                if (layoutManager.findLastVisibleItemPosition() == adapter.reviewList.size() - 1 && !isLoadingLocked && !isLoading) {
                    if (pageToDownload < totalPages) {
                        mBinding.layoutContent.pbLoadingMore.setVisibility(View.VISIBLE);
                        downloadMovieReviews();
                    }
                }
            }
        });


问:
forwarding reference with containers
It's possible that give std::vector<T> e.g to function by forwarding reference?
I know that

```<code>template<typename T>
void f(const std::vector<T>&&){} // is rvalue
template<typename T>
void f(const std::vector<T>&){} // is lvalue
</code>```

but how I can make function for lvalue and rvalue (with std::vector as parametr)?

答:
I think you want</p>

```<code>// traits for detecting std::vector
template <typename> struct is_std_vector : std::false_type {};
template <typename T, typename A>
struct is_std_vector<std::vector<T, A>> : std::true_type {};

template<typename T>
std::enable_if_t<is_std_vector<std::decay_t<T>>::value>
f(T&&); // Take any std::vector
</code>```

Title: forwarding reference with containers

Body:
It's possible that give std::vector<T> e.g to function by forwarding reference?
I know that

template<typename T>
void f(const std::vector<T>&&){} // is rvalue
template<typename T>
void f(const std::vector<T>&){} // is lvalue

but how I can make function for lvalue and rvalue (with std::vector as parametr)?

Body:
I think you want

// traits for detecting std::vector
template <typename> struct is_std_vector : std::false_type {};
template <typename T, typename A>
struct is_std_vector<std::vector<T, A>> : std::true_type {};

template<typename T>
std::enable_if_t<is_std_vector<std::decay_t<T>>::value>
f(T&&); // Take any std::vector


问:
while loop does not break out
Doing an exercise and I can't figure out why my while loop isn't escaping, it keeps saying that the values aren't valid even when only digits are entered. Any ideas?

// 31. Karvonen Heart Rate
var age, restingPulse, targetRate, numCheckAge, numCheckPulse, valid;

    valid = false;
    numCheckAge = /^\d+$/.test(age);
    numCheckPulse = /^\d+$/.test(restingPulse);

    while(valid === false) {
      age = parseFloat(prompt("Enter your age:"));
      restingPulse = parseFloat(prompt("Enter your resting heart rate:"));
      if(numCheckAge === true && numCheckPulse === true) {
        valid = true;
      } else {
        alert("Sorry. That's not a valid input, please enter numbers.");
      }
    }

    for (var i = 0.55; i < 1; i+=0.05){
      targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
      document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "
");
    }```

答:
At the point where where you test the regular expressions, those variables age and restingPulse are undefined. You'll have to move the code for testing to within the loop, after those variables have received values from user input:

```<code>while(!valid) {
  age = parseFloat(prompt("Enter your age:"));
  restingPulse = parseFloat(prompt("Enter your resting heart rate:"));

  numCheckAge = /^\d+$/.test(age);
  numCheckPulse = /^\d+$/.test(restingPulse);
  if(numCheckAge && numCheckPulse) {
    valid = true;
  }
  else {
    alert("Sorry. That's not a valid input, please enter numbers.");
  }
}
</code>```

Also, you can drop the === true bits, and use the truth value of the variable directly for testing.

ContentLicense: CC BY-SA 4.0

Title: while loop does not break out

Body:
At the point where where you test the regular expressions, those variables age and restingPulse are undefined. You'll have to move the code for testing to within the loop, after those variables have received values from user input:

while(!valid) {
  age = parseFloat(prompt("Enter your age:"));
  restingPulse = parseFloat(prompt("Enter your resting heart rate:"));

  numCheckAge = /^\d+$/.test(age);
  numCheckPulse = /^\d+$/.test(restingPulse);
  if(numCheckAge && numCheckPulse) {
    valid = true;
  }
  else {
    alert("Sorry. That's not a valid input, please enter numbers.");
  }
}

Also, you can drop the === true bits, and use the truth value of the variable directly for testing.


答:
I've simplified and flexified Your code ;)

Check this out:

function requireNumericPrompt(text) {
  var value;
  while(true) {
    if(/^\d+$/.test(value = prompt(text))) {
      return value;
    }
    alert("Sorry. Please enter valid (numeric) value.");
  }
}

var age = parseInt(requireNumericPrompt("Enter your age:"));
var restingPulse = parseInt(requireNumericPrompt("Enter your resting heart rate:"));

document.write('Age: ' + age + '
');
document.write('Resting pulse: ' + restingPulse + '
');
for (var targetRate, i = 0.55; i < 1; i+=0.05){
  targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
  document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "
");
}```

Title: while loop does not break out

Body:
Doing an exercise and I can't figure out why my while loop isn't escaping, it keeps saying that the values aren't valid even when only digits are entered. Any ideas?

// 31. Karvonen Heart Rate
var age, restingPulse, targetRate, numCheckAge, numCheckPulse, valid;

    valid = false;
    numCheckAge = /^\d+$/.test(age);
    numCheckPulse = /^\d+$/.test(restingPulse);

    while(valid === false) {
      age = parseFloat(prompt("Enter your age:"));
      restingPulse = parseFloat(prompt("Enter your resting heart rate:"));
      if(numCheckAge === true && numCheckPulse === true) {
        valid = true;
      } else {
        alert("Sorry. That's not a valid input, please enter numbers.");
      }
    }

    for (var i = 0.55; i < 1; i+=0.05){
      targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
      document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "
");
    }

Body:
I've simplified and flexified Your code ;)

Check this out:

function requireNumericPrompt(text) {
  var value;
  while(true) {
    if(/^\d+$/.test(value = prompt(text))) {
      return value;
    }
    alert("Sorry. Please enter valid (numeric) value.");
  }
}

var age = parseInt(requireNumericPrompt("Enter your age:"));
var restingPulse = parseInt(requireNumericPrompt("Enter your resting heart rate:"));

document.write('Age: ' + age + '<br/>');
document.write('Resting pulse: ' + restingPulse + '<br/>');
for (var targetRate, i = 0.55; i < 1; i+=0.05){
  targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
  document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "<br>");
}


问:
Laravel eloquent get most common value in a database column
From a table animals I have the following values in the animal_name column

cat
 dog
 cat

I want to pull the word cat from that because it is the most popular/common word in that column. How do I do that using laravel eloquent?

答:
Eloquent:

App\Animal::select('name')
    ->groupBy('name')
    ->orderByRaw('COUNT(*) DESC')
    ->limit(1)
    ->get();
```

<p>Output:</p>

```
=> Illuminate\Database\Eloquent\Collection {#711
     all: [
       App\Animal {#725
         name: "cat",
       },
     ],
   }
```

<hr>

<p>Same thing with Query Builder:</p>

<pre class="lang-php prettyprint-override"><code>DB::table('animals')
    ->select('name')
    ->groupBy('name')
    ->orderByRaw('COUNT(*) DESC')
    ->limit(1)
    ->get();
</code>```

Output:

```
=> Illuminate\Support\Collection {#734
     all: [
       {#738
         +"name": "cat",
       },
     ],
   }
```

Any way to also fetch the "cat" count in the same query?

Sure there is

```<code>App\Animal::select('name')
    ->selectRaw('COUNT(*) AS count')
    ->groupBy('name')
    ->orderByDesc('count')
    ->limit(1)
    ->get();
</code>```

```
=> Illuminate\Database\Eloquent\Collection {#711
     all: [
       App\Animal {#725
         name: "cat",
         count: 123
       },
     ],
   }
```

Body:
Eloquent:

App\Animal::select('name')
    ->groupBy('name')
    ->orderByRaw('COUNT(*) DESC')
    ->limit(1)
    ->get();

Output:

=> Illuminate\Database\Eloquent\Collection {#711
     all: [
       App\Animal {#725
         name: "cat",
       },
     ],
   }

Same thing with Query Builder:

DB::table('animals')
    ->select('name')
    ->groupBy('name')
    ->orderByRaw('COUNT(*) DESC')
    ->limit(1)
    ->get();

Output:

=> Illuminate\Support\Collection {#734
     all: [
       {#738
         +"name": "cat",
       },
     ],
   }

Any way to also fetch the "cat" count in the same query?

Sure there is

App\Animal::select('name')
    ->selectRaw('COUNT(*) AS count')
    ->groupBy('name')
    ->orderByDesc('count')
    ->limit(1)
    ->get();

=> Illuminate\Database\Eloquent\Collection {#711
     all: [
       App\Animal {#725
         name: "cat",
         count: 123
       },
     ],
   }


问:
Conditionally Change a List Item Attribute with Javascript
I'm a super beginner with javascript so forgive me if this is pretty basic, but I've several hours searching for a solution and can't figure out what I'm doing wrong. Basically, I'd like to hide a single list item identified by the id="change" items if a particular condition is met. However, it doesn't seem like the javascript code below is doing anything as the "Hide Me" list item continues to appear.</p>

```<code><script>
      var x = 1;
      if(x == 1) {
      document.getElementById("change").style.display = "none";
      }
</script>

<style>
    .default{display: block;}
</style>

<ul>
    <li class="default">Show Me</li>
    <li id="change" class="default">Hide Me</li>
</ul>
</code>```

答:
One way to debug your code is to try and see where the error begins. Right now, try to run the following code:

```<code>alert(document.getElementById("change"));
</code>```

By doing that, you will see that it outputs "null" meaning that it couldn't find anything with the id "change."

This occurs because the script is at the very beginning, before any of your html, and specifically before the item with the "change" id. You want to move the entire script part to the very end like this:

```<code><style>
    .default{display: block;}
</style>

<ul>
    <li class="default">Show Me</li>
    <li id="change" class="default">Hide Me</li>
</ul>

<script>
    var x = 1;
    if(x == 1) {
         document.getElementById("change").style.display = "none";
    }
</script>
</code>```

Body:
I'm a super beginner with javascript so forgive me if this is pretty basic, but I've several hours searching for a solution and can't figure out what I'm doing wrong. Basically, I'd like to hide a single list item identified by the id="change" items if a particular condition is met. However, it doesn't seem like the javascript code below is doing anything as the "Hide Me" list item continues to appear.

Show Me

Hide Me

Body:
One way to debug your code is to try and see where the error begins. Right now, try to run the following code:

alert(document.getElementById("change"));

By doing that, you will see that it outputs "null" meaning that it couldn't find anything with the id "change."

This occurs because the script is at the very beginning, before any of your html, and specifically before the item with the "change" id. You want to move the entire script part to the very end like this:

<style>
    .default{display: block;}
</style>

<ul>
    <li class="default">Show Me</li>
    <li id="change" class="default">Hide Me</li>
</ul>

<script>
    var x = 1;
    if(x == 1) {
         document.getElementById("change").style.display = "none";
    }
</script>


问:
asp.net mvc page redirected to login page after a few days
I have an ASP.NET MVC page which refreshes every 5 minutes. This page is used to display data only. The PC used to host this page goes days without any interaction. The page will refresh just fine for a few days, but then (on its own) this page will be redirected to the login page after 2, 4 or 5 days randomly.

Any idea as to whats going on?

I added the following attribute to Web.config for this page only as i thought maybe it was timing out while the database was running backups over night or something odd like that.

```<code><location path="~/Views/Production/WIPScanStationViewer.aspx">
<system.web>
  <httpRuntime executionTimeout="1000" maxRequestLength="2048576"/>
</system.web>
</location>
</code>```

答:
It seems like your session cookie is expiring. Try opening that page, press F12 to open the dev. tools and go to the "Application" tab. Once there, expand the "Cookies" node and search for your session cookie. The "Expires/Max-Age" column should display the expiration date, so you'll be able to know if that's the reason behind your problem.

If that's the problem and the web browser loading that page is never getting closed, you could change the value to "Session", meaning that it will not have an expiration date, and instead of that, the cookie will expire as soon as the web browser gets closed.

You could also set the cookie to expire after X days or even months, but honestly, I'm not a big fan of cookies with a really long lifetime, especially because if the cookie gets compromised at any point, the attacker will have access to your session for as long as the cookie doesn't expire.

Body:
I have an ASP.NET MVC page which refreshes every 5 minutes. This page is used to display data only. The PC used to host this page goes days without any interaction. The page will refresh just fine for a few days, but then (on its own) this page will be redirected to the login page after 2, 4 or 5 days randomly.

Any idea as to whats going on?

I added the following attribute to Web.config for this page only as i thought maybe it was timing out while the database was running backups over night or something odd like that.

<location path="~/Views/Production/WIPScanStationViewer.aspx">
<system.web>
  <httpRuntime executionTimeout="1000" maxRequestLength="2048576"/>
</system.web>
</location>


问:
ASP.NET jQuery: how to remove div element outside another div element when dropdown has changed?
this is my div structures

```<code> <div class="row-fluid">
        <div class="span12">
            <div style="overflow: auto; width: 90%;" class="goleft">
                <div style="display: inline-block; width: 200px;">
                    <p>
                        <select name="DropDownList3" id="DropDownList3" class="form-control show-tick">
                            <option value="--Pilih Periode--">--Pilih Periode--</option>
                            <option value="Juni, 2017">Juni, 2017</option>
                            <option value="Juli, 2017">Juli, 2017</option>
                        </select>
                    </p>
                </div>
                <div style="display: inline-block; width: 150px;">
                    <a id="LinkButton3" class="btn btn-primary btn-link-2 btn-block btReload-3 has-spinners" href="javascript:__doPostBack('LinkButton3','')">Muat Ulang</a>
                </div>
            </div>
        </div>
    </div>
    <div id="bar_chart_container">
        <p>Chart total</p>
        <canvas id="bar_chart" height="250" class="chart"></canvas>
    </div>
</code>```

when the id="DropDownList3"
has changed then, i want to remove the canvas with ID id="bar_chart" inside the div with ID id="bar_chart_container" located at the last of div that not group in the
, and appending the new canvas with same ID. how its done with jQuery?

here i was going so far but didn't work perfectly as expected

var cvs = $('#bar_chart').find(':last-child').not(':only-child').remove();
$('#bar_chart').remove();
$('#bar_chart_container').append('<canvas id="bar_chart" height="250" class="chart"><canvas>');
var ctx = $("#bar_chart").get(0).getContext('2d');

答:
You shouldn't need to remove the element and then re-create the same element, as you'll just be back in the same place as when you started.

Assuming all you want to do is simply hide the canvas on changing the dropdown, all you have to do is attach an onchange event handler to the <select> box, and then tie this in to a function that hides the desired element. Here, I'm creating a funciton called dropdownChange(), and calling onchange="dropdownChange()". I've added a slight border to the canvas to aid in clarity.

function dropdownChange() {
  document.getElementById('bar_chart').style.display = 'none';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#bar_chart {
  border: 1px solid black;
}</code>```

          <select name="DropDownList3" id="DropDownList3" class="form-control show-tick" onchange="dropdownChange()">
            <option value="--Pilih Periode--">--Pilih Periode--</option>
            <option value="Juni, 2017">Juni, 2017</option>
            <option value="Juli, 2017">Juli, 2017</option>
          </select>

        Muat Ulang

Chart total

  <canvas id="bar_chart" height="250" class="chart"></canvas>

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

<p>To actually remove the element and re-create it, you can use <code>document.createElement("canvas");</code> to create a brand new element, and then <code>$('#bar_chart_container').append();</code> to insert the newly-created canvas as follows:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function dropdownChange() {
  document.getElementById('bar_chart').style.display = 'none';
  var new_canvas = document.createElement("canvas"); // Create a <div> node
  new_canvas.style.border = "thick solid #0000FF";
  $('#bar_chart_container').append(new_canvas);
}</code>```

#bar_chart {
  border: 1px solid black;
}```
<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>
<div class="row-fluid">
  <div class="span12">
    <div style="overflow: auto; width: 90%;" class="goleft">
      <div style="display: inline-block; width: 200px;">
        <p>
          <select name="DropDownList3" id="DropDownList3" class="form-control show-tick" onchange="dropdownChange()">
            <option value="--Pilih Periode--">--Pilih Periode--</option>
            <option value="Juni, 2017">Juni, 2017</option>
            <option value="Juli, 2017">Juli, 2017</option>
          </select>
        </p>
      </div>
      <div style="display: inline-block; width: 150px;">
        Muat Ulang
      </div>
    </div>
  </div>
</div>
<div id="bar_chart_container">
  <p>Chart total</p>
  <canvas id="bar_chart" height="250" class="chart"></canvas>
</div></code>```

Hope this helps! :)

Body:
this is my div structures

                        <select name="DropDownList3" id="DropDownList3" class="form-control show-tick">
                            <option value="--Pilih Periode--">--Pilih Periode--</option>
                            <option value="Juni, 2017">Juni, 2017</option>
                            <option value="Juli, 2017">Juli, 2017</option>
                        </select>

                    Muat Ulang

Chart total

        <canvas id="bar_chart" height="250" class="chart"></canvas>

when the id="DropDownList3"
has changed then, i want to remove the canvas with ID id="bar_chart" inside the div with ID id="bar_chart_container" located at the last of div that not group in the
, and appending the new canvas with same ID. how its done with jQuery?

here i was going so far but didn't work perfectly as expected

var cvs = $('#bar_chart').find(':last-child').not(':only-child').remove();
$('#bar_chart').remove();
$('#bar_chart_container').append('<canvas id="bar_chart" height="250" class="chart"><canvas>');
var ctx = $("#bar_chart").get(0).getContext('2d');

Body:
You shouldn't need to remove the element and then re-create the same element, as you'll just be back in the same place as when you started.

Assuming all you want to do is simply hide the canvas on changing the dropdown, all you have to do is attach an onchange event handler to the <select> box, and then tie this in to a function that hides the desired element. Here, I'm creating a funciton called dropdownChange(), and calling onchange="dropdownChange()". I've added a slight border to the canvas to aid in clarity.

function dropdownChange() {
  document.getElementById('bar_chart').style.display = 'none';
}

#bar_chart {
  border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row-fluid">
  <div class="span12">
    <div style="overflow: auto; width: 90%;" class="goleft">
      <div style="display: inline-block; width: 200px;">
        <p>
          <select name="DropDownList3" id="DropDownList3" class="form-control show-tick" onchange="dropdownChange()">
            <option value="--Pilih Periode--">--Pilih Periode--</option>
            <option value="Juni, 2017">Juni, 2017</option>
            <option value="Juli, 2017">Juli, 2017</option>
          </select>
        </p>
      </div>
      <div style="display: inline-block; width: 150px;">
        <a id="LinkButton3" class="btn btn-primary btn-link-2 btn-block btReload-3 has-spinners" href="javascript:__doPostBack(&#39;LinkButton3&#39;,&#39;&#39;)">Muat Ulang</a>
      </div>
    </div>
  </div>
</div>
<div id="bar_chart_container">
  <p>Chart total</p>
  <canvas id="bar_chart" height="250" class="chart"></canvas>
</div>

To actually remove the element and re-create it, you can use document.createElement("canvas"); to create a brand new element, and then $('#bar_chart_container').append(); to insert the newly-created canvas as follows:

function dropdownChange() {
  document.getElementById('bar_chart').style.display = 'none';
  var new_canvas = document.createElement("canvas"); // Create a <div> node
  new_canvas.style.border = "thick solid #0000FF";
  $('#bar_chart_container').append(new_canvas);
}

#bar_chart {
  border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row-fluid">
  <div class="span12">
    <div style="overflow: auto; width: 90%;" class="goleft">
      <div style="display: inline-block; width: 200px;">
        <p>
          <select name="DropDownList3" id="DropDownList3" class="form-control show-tick" onchange="dropdownChange()">
            <option value="--Pilih Periode--">--Pilih Periode--</option>
            <option value="Juni, 2017">Juni, 2017</option>
            <option value="Juli, 2017">Juli, 2017</option>
          </select>
        </p>
      </div>
      <div style="display: inline-block; width: 150px;">
        <a id="LinkButton3" class="btn btn-primary btn-link-2 btn-block btReload-3 has-spinners" href="javascript:__doPostBack(&#39;LinkButton3&#39;,&#39;&#39;)">Muat Ulang</a>
      </div>
    </div>
  </div>
</div>
<div id="bar_chart_container">
  <p>Chart total</p>
  <canvas id="bar_chart" height="250" class="chart"></canvas>
</div>

Hope this helps! :)


问:
Deploy .Net AppEngine
I have a .Net AppEngine application working in Google Cloud Platform, and I can deploy it from the command line using my own credentials. I now want to deploy it from my Appveyor CI pipeline. I have encrypted the service account json file and want to use it in my deploy script. Naively I tried the following script in the deploy_script section of appveyor.yml:

```<code>    dotnet publish -c Release

    gcloud auth activate-service-account xxx@appspot.gserviceaccount.com --key-file="xxx.json"

    gcloud beta app deploy src/kinetics.webapi/bin/Release/netcoreapp1.1/publish/app.yaml
</code>```

Appveyor has no idea about the Google SDK, as I get the error

gcloud auth activate-service-account xxx@appspot.gserviceaccount.com --key-file="xxx.json"
  'gcloud' is not recognized as an internal or external command,
  operable program or batch file.

How do I use gcloud in Appveyor? I suppose I could install the entire Google SDK using Nuget, but that seems a bit time consuming for a CI server. Is there a more lightweight approach?

答:
Following ilyaf's suggestion, I used Chocolatey to install the Google Cloud SDK. It does work and doing the AppEngine deploy takes so long it's less of a big deal to do this in AppVeyor. Note that there are a couple more steps that are needed to run gcloud: refreshing to pick up the environment variables and using python to run in non-interactive mode. For anyone interested, the following install section installed the tool correctly :</p>

```<code>install:
  - nuget install secure-file -ExcludeVersion
  - choco install gcloudsdk
  - refreshenv
  - gcloud.cmd components copy-bundled-python>>python_path.txt && SET /p CLOUDSDK_PYTHON=<python_path.txt && DEL python_path.txt
  - gcloud.cmd components update --quiet
  - gcloud.cmd components install beta --quiet
  - secure-file\tools\secure-file -decrypt "xxx.json.enc" -secret %gcp_app_engine_service_account%
deploy_script:
- cmd: >-

    dotnet publish -c Release

    gcloud config set project xxx

    gcloud auth activate-service-account xxx@appspot.gserviceaccount.com --key-file="xxx.json"

    gcloud beta app deploy src/kinetics.webapi/bin/Release/netcoreapp1.1/publish/app.yaml --quiet
</code>```

Title: Deploy .Net AppEngine

Body:
I have a .Net AppEngine application working in Google Cloud Platform, and I can deploy it from the command line using my own credentials. I now want to deploy it from my Appveyor CI pipeline. I have encrypted the service account json file and want to use it in my deploy script. Naively I tried the following script in the deploy_script section of appveyor.yml:

    dotnet publish -c Release

    gcloud auth activate-service-account xxx@appspot.gserviceaccount.com --key-file="xxx.json"

    gcloud beta app deploy src/kinetics.webapi/bin/Release/netcoreapp1.1/publish/app.yaml

Appveyor has no idea about the Google SDK, as I get the error

gcloud auth activate-service-account xxx@appspot.gserviceaccount.com --key-file="xxx.json"
  'gcloud' is not recognized as an internal or external command,
  operable program or batch file.

How do I use gcloud in Appveyor? I suppose I could install the entire Google SDK using Nuget, but that seems a bit time consuming for a CI server. Is there a more lightweight approach?

Body:
Following ilyaf's suggestion, I used Chocolatey to install the Google Cloud SDK. It does work and doing the AppEngine deploy takes so long it's less of a big deal to do this in AppVeyor. Note that there are a couple more steps that are needed to run gcloud: refreshing to pick up the environment variables and using python to run in non-interactive mode. For anyone interested, the following install section installed the tool correctly :

install:
  - nuget install secure-file -ExcludeVersion
  - choco install gcloudsdk
  - refreshenv
  - gcloud.cmd components copy-bundled-python>>python_path.txt && SET /p CLOUDSDK_PYTHON=<python_path.txt && DEL python_path.txt
  - gcloud.cmd components update --quiet
  - gcloud.cmd components install beta --quiet
  - secure-file\tools\secure-file -decrypt "xxx.json.enc" -secret %gcp_app_engine_service_account%
deploy_script:
- cmd: >-

    dotnet publish -c Release

    gcloud config set project xxx

    gcloud auth activate-service-account xxx@appspot.gserviceaccount.com --key-file="xxx.json"

    gcloud beta app deploy src/kinetics.webapi/bin/Release/netcoreapp1.1/publish/app.yaml --quiet


问:
SpringMVC exception message not returned to client
My SpringMVC code has an exception handler, something like this:

```<code>@ExceptionHandler(SomeException.class)
@ResponseBody
public ResponseEntity<String> handleSomeException(SomeException e)
{
    logExceptionMessage(e);
    return new ResponseEntity<>("custom message", 401);
}
</code>```

I am reading the code on the client, something like:

```<code>reader = new BufferedReader(new InputStreamReader(contentStream, "UTF-8"));
</code>```

The exception is a simple subclass of:

```<code>public class SomeException extends RuntimeException
{
    public SomeException(String message)
    {
        super(message);
    }

    public SomeException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public SomeException(Throwable cause)
    {
        super(cause);
    }
}
</code>```

When there are no server errors, everything works fine.

When the server throws the exception handler, the client is correctly receiving the error status code (in this case 401) but instead of returning the custom error message, it is returning

```<code>Server returned HTTP response code: 401 for URL: http://myUrl.json
</code>```

How can I get the custom error message??

答:
I see the issue, I was looking at the error message in the thrown exception.
If I explicitly read the actual message I can see the server message:

```<code>private static String getErrorMessage(HttpURLConnection connection)
{
    StringBuilder message = new StringBuilder();
    BufferedReader reader;
    try (InputStream errorStream = connection.getErrorStream())
    {
        reader = new BufferedReader(new InputStreamReader(errorStream));
        while (true)
        {
            String line = reader.readLine();
            if (line == null)
            {
                break;
            } else
            {
                message.append(line);
            }
        }
    } catch (IOException e)
    {
        logger.warn("Error reading server error message", e);
    }
    return message.toString();
}
</code>```

I don't know if there is a more concise way (using Java 7), but this is working for me

Body:
My SpringMVC code has an exception handler, something like this:

@ExceptionHandler(SomeException.class)
@ResponseBody
public ResponseEntity<String> handleSomeException(SomeException e)
{
    logExceptionMessage(e);
    return new ResponseEntity<>("custom message", 401);
}

I am reading the code on the client, something like:

reader = new BufferedReader(new InputStreamReader(contentStream, "UTF-8"));

The exception is a simple subclass of:

public class SomeException extends RuntimeException
{
    public SomeException(String message)
    {
        super(message);
    }

    public SomeException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public SomeException(Throwable cause)
    {
        super(cause);
    }
}

When there are no server errors, everything works fine.

When the server throws the exception handler, the client is correctly receiving the error status code (in this case 401) but instead of returning the custom error message, it is returning

Server returned HTTP response code: 401 for URL: http://myUrl.json

How can I get the custom error message??

Body:
I see the issue, I was looking at the error message in the thrown exception.
If I explicitly read the actual message I can see the server message:

private static String getErrorMessage(HttpURLConnection connection)
{
    StringBuilder message = new StringBuilder();
    BufferedReader reader;
    try (InputStream errorStream = connection.getErrorStream())
    {
        reader = new BufferedReader(new InputStreamReader(errorStream));
        while (true)
        {
            String line = reader.readLine();
            if (line == null)
            {
                break;
            } else
            {
                message.append(line);
            }
        }
    } catch (IOException e)
    {
        logger.warn("Error reading server error message", e);
    }
    return message.toString();
}

I don't know if there is a more concise way (using Java 7), but this is working for me


问:
Angular2 filter/pipe using radio buttons to filter
I'm looking for a filtering solution that will live filter a repeated set of elements. I have a basic pipe solution found in the answers here.

What I've found is that <input [(ngModel)]='query'/> will only work if it's within the same component.

However - I need to have the filter value coming from pre populated radio buttons within another component.

Here is my code so far.

filter.component

```<code><div class="topic" *ngFor="let topic of topics">
  {{topic.term}}
  <input [(ngModel)]="query" type="radio" name="topicFilter" [value]="topic.term"/>
</div>
</code>```

grid.component

```<code><router-outlet></router-outlet> // this pulls in the filter.component

<input [(ngModel)]="query"> // this is a text input that works as wanted ( for showing what I'm wanting to achieve )

<grid-item *ngFor="let user of users | topicFilterPipe: 'topic':query">
  <a [routerLink]="['user-story', user.uid]">
    <h1>{{user.fname}}</h1>
  </a>
  {{user.topic}}
</grid-item>
</code>```

filter.pipe

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'topicFilterPipe'
})
export class TopicFilterPipePipe implements PipeTransform {

  public transform(value: Array<any>, keys: string, term: string) {
    console.log('pipe has run');
    if (!term) return value;
    return (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));

  }

}
</code>```

Basically - trying to implement the same method that the text input does, but with the selected radio that is within the filter.component. However I'm struggling to pass the selected value into the pipe & then filter using ngModel. Thank you!

NOTE: I'm VERY new to angular2 + The filter component must remain in a seperate component

答:
You could build a service with a method like this:

```<code>performFilter(filterBy: string): IProduct[] {
    filterBy = filterBy.toLocaleLowerCase();
    return this.products.filter((product: IProduct) =>
          product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}
</code>```

This is filtering a list of products ... but you could tailor it to filter whatever you need. And since this would need to be in a service so it could be shared, you will most likely need to pass in the list to be filtered. So more like this:

```<code>performFilter(products: IProduct[], filterBy: string): IProduct[] {
    filterBy = filterBy.toLocaleLowerCase();
    return products.filter((product: IProduct) =>
          product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}
</code>```

Body:
I'm looking for a filtering solution that will live filter a repeated set of elements. I have a basic pipe solution found in the answers here.

What I've found is that <input [(ngModel)]='query'/> will only work if it's within the same component.

However - I need to have the filter value coming from pre populated radio buttons within another component.

Here is my code so far.

filter.component

  {{topic.term}}
  <input [(ngModel)]="query" type="radio" name="topicFilter" [value]="topic.term"/>

grid.component

<router-outlet></router-outlet> // this pulls in the filter.component

<input [(ngModel)]="query"> // this is a text input that works as wanted ( for showing what I'm wanting to achieve )

<grid-item *ngFor="let user of users | topicFilterPipe: 'topic':query">

{{user.fname}}

  {{user.topic}}
</grid-item>

filter.pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'topicFilterPipe'
})
export class TopicFilterPipePipe implements PipeTransform {

  public transform(value: Array<any>, keys: string, term: string) {
    console.log('pipe has run');
    if (!term) return value;
    return (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));

  }

}

Basically - trying to implement the same method that the text input does, but with the selected radio that is within the filter.component. However I'm struggling to pass the selected value into the pipe & then filter using ngModel. Thank you!

NOTE: I'm VERY new to angular2 + The filter component must remain in a seperate component

Body:
You could build a service with a method like this:

performFilter(filterBy: string): IProduct[] {
    filterBy = filterBy.toLocaleLowerCase();
    return this.products.filter((product: IProduct) =>
          product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}

This is filtering a list of products ... but you could tailor it to filter whatever you need. And since this would need to be in a service so it could be shared, you will most likely need to pass in the list to be filtered. So more like this:

performFilter(products: IProduct[], filterBy: string): IProduct[] {
    filterBy = filterBy.toLocaleLowerCase();
    return products.filter((product: IProduct) =>
          product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}


问:
ng-repeat a single element over nested objects
Say I have an object with keys corresponding to products and values corresponding to objects which in turn have keys corresponding to price points at which those products have sold, and values corresponding to amount sold.

For example, if I sold 10 widgets at $1 and 5 widgets at $2, I'd have the data structure:

```<code>{ 'widget': {'1': 10, '2': 5} }
</code>```

I'd like to loop over this structure and generate rows in a table such as this one:

```<code>thing   price  amount
---------------------
widget  $1     10
widget  $2     5
</code>```

In Python it's possible to nest list comprehensions to traverse lists data structures like this. Would such a thing be possible using ng-repeat?

答:
I used a simple directive which has a recursive function to loop over my nested object and create nested elements. This way you can keep your nested object structure.

Code:

angular.module('nerd').directive('nestedItems', ['$rootScope', '$compile', function($rootScope, $compile) {
    return {
        restrict: 'E',
        scope: false,
        link: function(scope, element, attrs, fn) {

            scope.addElement = function(elem, objAr) {

                var ulElement = angular.element("

");

                if (objAr ==  undefined || objAr.length == 0) {
                    return [];
                }

                objAr.forEach(function(arrayItem) {
                    var newElement = angular.element("
"+arrayItem.val+"
");
                    ulElement.append(newElement);
                    scope.addElement(newElement,arrayItem.sub);
                });

                elem.append(ulElement);
            };

            scope.addElement(element,scope.elements);

        }
    };
}]);```
</div>
</div>
</p>

<p>My Object :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$scope.elements = [

      {
          id: 1,
          val: "First Level",
          sub: [

              {
                  id: 2,
                  val: "Second Level - Item 1"
              },
              {
                  id: 3,
                  val: "Second Level - Item 2",
                  sub: [{
                      id: 4,
                      val: "Third Level - Item 1"
                  }]
              }
          ]
      }
  ];</code>```

My HTML

<nested-items></nested-items>```

Body:
Say I have an object with keys corresponding to products and values corresponding to objects which in turn have keys corresponding to price points at which those products have sold, and values corresponding to amount sold.

For example, if I sold 10 widgets at $1 and 5 widgets at $2, I'd have the data structure:

{ 'widget': {'1': 10, '2': 5} }

I'd like to loop over this structure and generate rows in a table such as this one:

thing   price  amount
---------------------
widget  $1     10
widget  $2     5

In Python it's possible to nest list comprehensions to traverse lists data structures like this. Would such a thing be possible using ng-repeat?

Body:
I used a simple directive which has a recursive function to loop over my nested object and create nested elements. This way you can keep your nested object structure.

Code:

angular.module('nerd').directive('nestedItems', ['$rootScope', '$compile', function($rootScope, $compile) {
    return {
        restrict: 'E',
        scope: false,
        link: function(scope, element, attrs, fn) {

            scope.addElement = function(elem, objAr) {

                var ulElement = angular.element("<ul></ul>");

                if (objAr ==  undefined || objAr.length == 0) {
                    return [];
                }

                objAr.forEach(function(arrayItem) {
                    var newElement = angular.element("<li>"+arrayItem.val+"</li>");
                    ulElement.append(newElement);
                    scope.addElement(newElement,arrayItem.sub);
                });

                elem.append(ulElement);
            };

            scope.addElement(element,scope.elements);

        }
    };
}]);

My Object :

$scope.elements = [

      {
          id: 1,
          val: "First Level",
          sub: [

              {
                  id: 2,
                  val: "Second Level - Item 1"
              },
              {
                  id: 3,
                  val: "Second Level - Item 2",
                  sub: [{
                      id: 4,
                      val: "Third Level - Item 1"
                  }]
              }
          ]
      }
  ];

My HTML

<nested-items></nested-items>


问:
Android PendingIntent and how I should handle its action in the main Activity
I've been trying for a couple of days to create a notification (with a button) on Android and handle its action on the main activity. Everything works just fine, but there's an issue I can't figure out:

When the activity is opened by the PendingIntent, it shows a dialog after checking if the action is the one from the notification (getIntent().getAction().equals("action")).

So far so good, but when the user clicks on recent apps and then gets back to the activity, the action is processed again.

I tried doing the check on the onCreate() method, but it's being called every time since the activity is flagged as noHistory=true in the Manifest.

Because of this, the activity is re-created every time so I can't use a boolean flag to show the dialog only once either. I thought of using a broadcast in the PendingIntent but I'll need to launch the main activity anyway (this is a business requirement).

Even if I remove the noHistory attribute, when pressing the back button, finish() is called and the activity is destroyed, but it can be re-run from the recent apps menu and everything starts over with the notification action in place.

Could anyone please give me a hint on how to handle this? Please keep in mind that the action validation method is called from the onCreate() and the latter is being called every time the app leaves foreground, because of the noHistory and also when the user clicks the back button (the finish() call is made) and the onCreate() will be called again next time the user brings the app to foreground from the recent menu (I should not disable it since it's required by the app).

To make myself even clearer, the issue is that the user keeps seeing the dialog every time the app goes to background and gets chosen from the recent apps menu or the recent apps button is clicked and the user choose my activity.

答:
A dirty way would be to store the state (flag) on disk and check on startup whether to fire the dialog or not.
If you wanna go that route, I'd recommend SharedPreferences https://developer.android.com/reference/android/content/SharedPreferences.html.


答:
var age, restingPulse, targetRate, numCheckAge, numCheckPulse, valid;

valid = false;
numCheckAge =function(a) {
 return /^\d+$/.test(a);
}
numCheckPulse = function(a){
 return /^\d+$/.test(restingPulse);
}

while(valid === false) {
  age = parseFloat(prompt("Enter your age:"));
  restingPulse = parseFloat(prompt("Enter your resting heart rate:"));
  if(numCheckAge(age) && numCheckPulse(restingPulse)) {
    valid = true;
  } else {
    alert("Sorry. That's not a valid input, please enter numbers.");
  }
}

for (var i = 0.55; i < 1; i+=0.05){
  targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
  document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "
");
}```

you need to convert your check code to a function instead a variable.

Title: while loop does not break out

Body:
var age, restingPulse, targetRate, numCheckAge, numCheckPulse, valid;

valid = false;
numCheckAge =function(a) {
 return /^\d+$/.test(a);
}
numCheckPulse = function(a){
 return /^\d+$/.test(restingPulse);
}

while(valid === false) {
  age = parseFloat(prompt("Enter your age:"));
  restingPulse = parseFloat(prompt("Enter your resting heart rate:"));
  if(numCheckAge(age) && numCheckPulse(restingPulse)) {
    valid = true;
  } else {
    alert("Sorry. That's not a valid input, please enter numbers.");
  }
}

for (var i = 0.55; i < 1; i+=0.05){
  targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
  document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "<br>");
}

you need to convert your check code to a function instead a variable.


问:
BLE writeCharacteristic and readCharacteristic issue
I am a beginner of BLE in my case BLE write characteristic true but BLE readCharacteristic failed.I followed this working example but I changed the service UUID and getCharacteristic UUID.But till i receive the read failed.Kindly help anyone i tried many ways thanks..

答: Without any code to work with, or the device you are trying to connect with is hard to tell what's going on. My bet is that the device you are trying to use doesn't have the custom characteristic you are trying to write. I recommend that you download the BLE scanner app for android and use it to identify the services availdable in your BLE device.</p>


问:
SQL: How to get the row count of a certain record
For example, if I store 150 phone numbers in the table phone_numbers. How will I go about retrieving the row number containing 555-555-5555? I checked out many different queries, but seems I have to loop through all the data to find it.</p>

答:
Use the ROW_NUMBER() function ... use the sql API definition to know more about the function

Good luck

EDIT:

Example you have a table called 'testTable', and column called 'testId' and a column called 'testName'

```<code>SELECT testId , tesName, (
     SELECT COUNT(*) FROM testTable AS a
            WHERE a.testName <= b.Name) AS row_Num
           FROM testTable AS b
     ORDER BY testName, testId;
</code>```

I hope I'm right this time

thanks and let me know please if it works or not I'm trying my best

Body:
Use the ROW_NUMBER() function ... use the sql API definition to know more about the function

Good luck

EDIT:

Example you have a table called 'testTable', and column called 'testId' and a column called 'testName'

SELECT testId , tesName, (
     SELECT COUNT(*) FROM testTable AS a
            WHERE a.testName <= b.Name) AS row_Num
           FROM testTable AS b
     ORDER BY testName, testId;

I hope I'm right this time

thanks and let me know please if it works or not I'm trying my best