问:
How to shrink a ScrollView's height keeping the other view(Button) fixed in place?
I have a ScrollView and a Button side by side in a vertical orientation(both children of ConstraintLayout's weighted chain with weight 1 and 0 respectively for ScrollView and the Button. BTW, you can optionally assume them to be children of a LinearLayout instead of a ConstraintLayout because a weighted ConstraintLayout chain works almost the same as a LinearLayout).

This is one of those typical use cases where you create the ScrollView with a list of certain items(children) and at the bottom have a big Button that searches your database based on the values filled in the ScollView children. Something like below:

The red-color encircled portion is where the Button is supposed to be(it is there but not visible).

Now the problem.

I want the button to be visible at all times irrespective of the ScrollView(if that implies shrinking of ScrollView's height, so be it because it is scrollable after all) but since the contents of ScrollView take enough space to hide the Button, by default it gets hidden. The solution(I think) would entail having to shrink the ScrollView's height just the amount that the Button is visible in the remaining space below.

Note that, I don't want the arrangement to end up like having the Button overlay the ScrollView's area. This is the case where no shrinkage of height would be required to ScrollView but rather the Button is made to float above it at the bottom, hiding some of its area. I want to force the ScrollView to adjust to the Button. Also, having weights of 1 and 0 respectively didn't help.

EDIT: Code for layout. (The Button is with id search_button)

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="8dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    >

    <ScrollView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:id="@+id/scrollView2"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintVertical_weight="1"
        app:layout_constraintBottom_toTopOf="@+id/search_button"
        app:layout_constraintVertical_chainStyle="spread_inside">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="4dp"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:layout_marginStart="4dp"
            android:layout_marginTop="8dp"
            android:background="@android:drawable/dialog_holo_light_frame"
            android:paddingEnd="8dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingStart="8dp"
            android:paddingTop="8dp">

            <LinearLayout
                android:layout_height="wrap_content"
                android:layout_width="0dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginRight="8dp"
                android:layout_marginEnd="8dp"
                android:orientation="vertical"
                app:layout_constraintRight_toRightOf="parent"
                android:id="@+id/frameLayout">

                <include layout="@layout/layout_subject_search" />

            </LinearLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:background="?android:attr/listDivider"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginRight="8dp"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/frameLayout"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginTop="8dp"
                android:id="@+id/view" />

            <LinearLayout
                android:layout_height="wrap_content"
                android:layout_width="0dp"
                android:layout_marginTop="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginRight="8dp"
                android:layout_marginEnd="8dp"
                android:orientation="vertical"
                app:layout_constraintRight_toRightOf="parent"
                android:id="@+id/frameLayout1"
                app:layout_constraintTop_toBottomOf="@+id/view">

                <include layout="@layout/layout_qualification_search" />

            </LinearLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="2dp"
                android:background="?android:attr/listDivider"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/frameLayout1"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:id="@+id/view2" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/search_by_location_label"
                android:textSize="15sp"
                android:textStyle="bold"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/view2"
                android:layout_marginStart="8dp" />

            <Switch
                android:id="@+id/location_toggle_switch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:text=""
                android:layout_marginTop="16dp"
                app:layout_constraintTop_toBottomOf="@+id/view2"
                android:layout_marginRight="16dp"
                app:layout_constraintRight_toRightOf="parent"
                android:layout_marginEnd="16dp" />

            <FrameLayout
                android:id="@+id/map_search_fragment"
                android:layout_width="0dp"
                android:layout_height="240dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/textView"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:background="@android:drawable/dialog_holo_light_frame"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/location_toggle_switch"
                app:layout_constraintVertical_bias="0.0">

            </FrameLayout>

        </android.support.constraint.ConstraintLayout>

    </ScrollView>

    <Button
        android:id="@+id/search_button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="@string/search_tutors_string"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="4dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintVertical_weight="0"
        app:layout_constraintTop_toBottomOf="@+id/scrollView2" />

    <ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>
</code>```

EDIT 2: As asked by @marshmallow 's,

// include layout="@layout/layout_subject_search"

```<code><merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search_by_subject_label"
        android:textStyle="bold"
        android:textSize="15sp"/>

    <com.learncity.learner.search.SubjectMultiAutoCompleteTextView
        android:id="@+id/subject_multi_auto_complete_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        android:ems="10"/>

</merge>
</code>```

// include layout="@layout/layout_qualification_search"

```<code><merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search_by_qualification_label"
        android:textStyle="bold"
        android:textSize="15sp"/>

    <com.learncity.learner.search.QualificationMultiAutoCompleteTextView
        android:id="@+id/qualification_multi_auto_complete_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        android:ems="10"/>

</merge>
</code>```

答:
First of all, thanks to @marshmallow for suggesting the wrap_content strategy as well as repeatedly testing and replying with updated solutions.

The solution is bit of a twist on his suggestion:

Make layout_height for Button to be wrap_content. Why? We want to declare button's height as a reference for ScrollView to adjust its size and the true height of the button is obtained by using wrap_content.

Now, we want to tell the ScrollView to adjust its size as per button. To do this, we use layout_height as 0dp which translates to, "Use available constraints to adjust your size rather than asserting any fixed size of your own". For the same reason, Button's height is not 0dp.

Next, we establish a weighted chain relationship between the two with weight of 1 for ScrollView and 0 for Button(it doesn't effectively work for Button because width is not 0dp/match constraints; so just a pointer to ScrollView to take up space remaining other than Button)

With this, the final solution becomes:(The solution tested for both portrait and landscape modes)

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="8dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    >

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="4dp"
        app:layout_constraintBottom_toTopOf="@+id/search_button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:layout_constraintVertical_chainStyle="spread_inside"
        app:layout_constraintVertical_weight="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="4dp"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:layout_marginStart="4dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:background="@android:drawable/dialog_holo_light_frame"
            android:paddingEnd="8dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingStart="8dp"
            android:paddingTop="8dp">

            <LinearLayout
                android:id="@+id/frameLayout"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:orientation="vertical"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <include layout="@layout/layout_subject_search" />

            </LinearLayout>

            <View
                android:id="@+id/view"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:background="?android:attr/listDivider"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/frameLayout" />

            <LinearLayout
                android:id="@+id/frameLayout1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:orientation="vertical"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/view">

                <include layout="@layout/layout_qualification_search" />

            </LinearLayout>

            <View
                android:id="@+id/view2"
                android:layout_width="0dp"
                android:layout_height="2dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:background="?android:attr/listDivider"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/frameLayout1" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:text="@string/search_by_location_label"
                android:textSize="15sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/view2" />

            <Switch
                android:id="@+id/location_toggle_switch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="16dp"
                android:text=""
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/view2" />

            <FrameLayout
                android:id="@+id/map_search_fragment"
                android:layout_width="0dp"
                android:layout_height="240dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/textView"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:background="@android:drawable/dialog_holo_light_frame"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/location_toggle_switch"
                app:layout_constraintVertical_bias="0.0">

            </FrameLayout>

        </android.support.constraint.ConstraintLayout>

    </ScrollView>

    <Button
        android:id="@+id/search_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginTop="4dp"
        android:text="@string/search_tutors_string"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/scrollView2"
        app:layout_constraintVertical_weight="0" />

    <ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I have a ScrollView and a Button side by side in a vertical orientation(both children of ConstraintLayout's weighted chain with weight 1 and 0 respectively for ScrollView and the Button. BTW, you can optionally assume them to be children of a LinearLayout instead of a ConstraintLayout because a weighted ConstraintLayout chain works almost the same as a LinearLayout).

This is one of those typical use cases where you create the ScrollView with a list of certain items(children) and at the bottom have a big Button that searches your database based on the values filled in the ScollView children. Something like below:

The red-color encircled portion is where the Button is supposed to be(it is there but not visible).

Now the problem.

I want the button to be visible at all times irrespective of the ScrollView(if that implies shrinking of ScrollView's height, so be it because it is scrollable after all) but since the contents of ScrollView take enough space to hide the Button, by default it gets hidden. The solution(I think) would entail having to shrink the ScrollView's height just the amount that the Button is visible in the remaining space below.

Note that, I don't want the arrangement to end up like having the Button overlay the ScrollView's area. This is the case where no shrinkage of height would be required to ScrollView but rather the Button is made to float above it at the bottom, hiding some of its area. I want to force the ScrollView to adjust to the Button. Also, having weights of 1 and 0 respectively didn't help.

EDIT: Code for layout. (The Button is with id search_button)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="8dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    >

    <ScrollView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:id="@+id/scrollView2"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintVertical_weight="1"
        app:layout_constraintBottom_toTopOf="@+id/search_button"
        app:layout_constraintVertical_chainStyle="spread_inside">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="4dp"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:layout_marginStart="4dp"
            android:layout_marginTop="8dp"
            android:background="@android:drawable/dialog_holo_light_frame"
            android:paddingEnd="8dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingStart="8dp"
            android:paddingTop="8dp">

            <LinearLayout
                android:layout_height="wrap_content"
                android:layout_width="0dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginRight="8dp"
                android:layout_marginEnd="8dp"
                android:orientation="vertical"
                app:layout_constraintRight_toRightOf="parent"
                android:id="@+id/frameLayout">

                <include layout="@layout/layout_subject_search" />

            </LinearLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:background="?android:attr/listDivider"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginRight="8dp"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/frameLayout"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginTop="8dp"
                android:id="@+id/view" />

            <LinearLayout
                android:layout_height="wrap_content"
                android:layout_width="0dp"
                android:layout_marginTop="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginRight="8dp"
                android:layout_marginEnd="8dp"
                android:orientation="vertical"
                app:layout_constraintRight_toRightOf="parent"
                android:id="@+id/frameLayout1"
                app:layout_constraintTop_toBottomOf="@+id/view">

                <include layout="@layout/layout_qualification_search" />

            </LinearLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="2dp"
                android:background="?android:attr/listDivider"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/frameLayout1"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:id="@+id/view2" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/search_by_location_label"
                android:textSize="15sp"
                android:textStyle="bold"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/view2"
                android:layout_marginStart="8dp" />

            <Switch
                android:id="@+id/location_toggle_switch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:text=""
                android:layout_marginTop="16dp"
                app:layout_constraintTop_toBottomOf="@+id/view2"
                android:layout_marginRight="16dp"
                app:layout_constraintRight_toRightOf="parent"
                android:layout_marginEnd="16dp" />

            <FrameLayout
                android:id="@+id/map_search_fragment"
                android:layout_width="0dp"
                android:layout_height="240dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/textView"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:background="@android:drawable/dialog_holo_light_frame"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/location_toggle_switch"
                app:layout_constraintVertical_bias="0.0">

            </FrameLayout>

        </android.support.constraint.ConstraintLayout>

    </ScrollView>

    <Button
        android:id="@+id/search_button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="@string/search_tutors_string"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="4dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintVertical_weight="0"
        app:layout_constraintTop_toBottomOf="@+id/scrollView2" />

    <ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>

EDIT 2: As asked by @marshmallow 's,

// include layout="@layout/layout_subject_search"

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search_by_subject_label"
        android:textStyle="bold"
        android:textSize="15sp"/>

    <com.learncity.learner.search.SubjectMultiAutoCompleteTextView
        android:id="@+id/subject_multi_auto_complete_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        android:ems="10"/>

</merge>

// include layout="@layout/layout_qualification_search"

<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search_by_qualification_label"
        android:textStyle="bold"
        android:textSize="15sp"/>

    <com.learncity.learner.search.QualificationMultiAutoCompleteTextView
        android:id="@+id/qualification_multi_auto_complete_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        android:ems="10"/>

</merge>

Body:
First of all, thanks to @marshmallow for suggesting the wrap_content strategy as well as repeatedly testing and replying with updated solutions.

The solution is bit of a twist on his suggestion:

Make layout_height for Button to be wrap_content. Why? We want to declare button's height as a reference for ScrollView to adjust its size and the true height of the button is obtained by using wrap_content.

Now, we want to tell the ScrollView to adjust its size as per button. To do this, we use layout_height as 0dp which translates to, "Use available constraints to adjust your size rather than asserting any fixed size of your own". For the same reason, Button's height is not 0dp.

Next, we establish a weighted chain relationship between the two with weight of 1 for ScrollView and 0 for Button(it doesn't effectively work for Button because width is not 0dp/match constraints; so just a pointer to ScrollView to take up space remaining other than Button)

With this, the final solution becomes:(The solution tested for both portrait and landscape modes)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="8dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    >

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="4dp"
        app:layout_constraintBottom_toTopOf="@+id/search_button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:layout_constraintVertical_chainStyle="spread_inside"
        app:layout_constraintVertical_weight="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="4dp"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:layout_marginStart="4dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:background="@android:drawable/dialog_holo_light_frame"
            android:paddingEnd="8dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingStart="8dp"
            android:paddingTop="8dp">

            <LinearLayout
                android:id="@+id/frameLayout"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:orientation="vertical"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <include layout="@layout/layout_subject_search" />

            </LinearLayout>

            <View
                android:id="@+id/view"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:background="?android:attr/listDivider"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/frameLayout" />

            <LinearLayout
                android:id="@+id/frameLayout1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:orientation="vertical"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/view">

                <include layout="@layout/layout_qualification_search" />

            </LinearLayout>

            <View
                android:id="@+id/view2"
                android:layout_width="0dp"
                android:layout_height="2dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:background="?android:attr/listDivider"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/frameLayout1" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:text="@string/search_by_location_label"
                android:textSize="15sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/view2" />

            <Switch
                android:id="@+id/location_toggle_switch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="16dp"
                android:text=""
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/view2" />

            <FrameLayout
                android:id="@+id/map_search_fragment"
                android:layout_width="0dp"
                android:layout_height="240dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/textView"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:background="@android:drawable/dialog_holo_light_frame"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/location_toggle_switch"
                app:layout_constraintVertical_bias="0.0">

            </FrameLayout>

        </android.support.constraint.ConstraintLayout>

    </ScrollView>

    <Button
        android:id="@+id/search_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginTop="4dp"
        android:text="@string/search_tutors_string"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/scrollView2"
        app:layout_constraintVertical_weight="0" />

    <ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>


来源: stackexchange

问:
Python tox and py.test: how to run just a single test rather than the whole test suite
I'm new to Django and testing so please bear with me.

Trying to run on the terminal a new test for code I developed in a Django project, but unfortunatly I inherited several test failures (already confirmed that by analyzing commits prior to mine). I'm trying to run/fix just my test/code. Not fix all the failling tests (at least not right now). Today we run the tests by just running tox in the main project folder, and tox ends up calling py.test, with a different database (in development/production we use Postgresql, but for tests we use SQLite). Here is the tox.ini configuration

```<code>[tox]
envlist = unit
skipsdist = True

[testenv:unit]
deps = -rrequirements/test.txt
commands =
    bash -c 'TESTING_DB=db.sqlite3 python manage.py initdb --settings telessaude.settings.test'
    py.test -n 4

passenv = *
setenv =
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
whitelist_externals =
    /bin/bash

[flake8]
max-line-length = 110

[pytest]
setenv=
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
python_files = **/tests.py **/tests/*.py **/tests.py
norecursedirs = requirements .tox media
</code>```

And here is my test, located at ~/project_name/servicos/tests.py

```<code># encoding: utf-8
from fluxos.tests import BaseFluxoTestCase
from core.tests import BaseTestCase
from servicos.models import Estomatologia

class EstomatologiaTestCase(BaseTestCase):

    def testa_formata_campos(self):
        estomato = Estomatologia()
        return_value = estomato.formata_campos()
        self.assertEquals(return_value['comorbidades_paciente'], '')

    ...
</code>```

What should I do with either tox or py.test to run just this newly created test? Thanks!

Update 1: Unfortunatly the suggested answers didn't worked. When I run a single test as suggested by phd and Windsooon, tox doesn't seem to be running any tests. I wrote a test that fails (on purpose) and when I run all tests with tox command, the error shows up:

```<code>    def test_formata_campos_para_estomatologia(self):
        estomatologia = Estomatologia()
        retorno = formata_campos(estomatologia)
>       self.assertIn('objetivos', retorno) E       AssertionError: 'objetivos' not found in {'comorbidades_paciente': '', 'tempo_transcorrido': '', 'sinais_e_sintomas_locais': ''}
</code>```

But when I run only the test individually, the test passes! I get this result:

```<code>tox -e py27 -- servicos.tests:FormatacaoDeCamposTestCase.test_formata_campos_para_estomatologia
py27 installed:
py27 runtests: PYTHONHASHSEED='3025337440'
______________________________________________________________ summary ______________________________________________________________
  py27: commands succeeded
  congratulations :)
</code>```

Digging around the internet, I found that I must have the {posargs} otherwise tox will ignore whatever I supply to it. However only the second line of my commands will use it. The first line will set the test database to SQLite (faster database set for testing). Can this be a bug on tox? Any idea on how to solve this?

Update 2: The answer from @phd was the closest one, but I had to adapt a few things:

Need to use 2 colon marks instead of one

Must use 2 colon marks instead of dot for separating method name from the class

Also had to drop the "-e" parameter, since that enviroment wasn't set on my tox.ini file.

Final command looks like this:

```<code>tox -- folder1/folder2/file_name.py::ClassName::test_method_name
</code>```

答:
Try</p>

```<code>tox -e py27 -- test_file_name_here.py:TestClassName.test_method_name
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to Django and testing so please bear with me.

Trying to run on the terminal a new test for code I developed in a Django project, but unfortunatly I inherited several test failures (already confirmed that by analyzing commits prior to mine). I'm trying to run/fix just my test/code. Not fix all the failling tests (at least not right now). Today we run the tests by just running tox in the main project folder, and tox ends up calling py.test, with a different database (in development/production we use Postgresql, but for tests we use SQLite). Here is the tox.ini configuration

[tox]
envlist = unit
skipsdist = True

[testenv:unit]
deps = -rrequirements/test.txt
commands =
    bash -c 'TESTING_DB=db.sqlite3 python manage.py initdb --settings telessaude.settings.test'
    py.test -n 4

passenv = *
setenv =
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
whitelist_externals =
    /bin/bash

[flake8]
max-line-length = 110

[pytest]
setenv=
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
python_files = **/tests.py **/tests/*.py **/tests.py
norecursedirs = requirements .tox media

And here is my test, located at ~/project_name/servicos/tests.py

# encoding: utf-8
from fluxos.tests import BaseFluxoTestCase
from core.tests import BaseTestCase
from servicos.models import Estomatologia

class EstomatologiaTestCase(BaseTestCase):

    def testa_formata_campos(self):
        estomato = Estomatologia()
        return_value = estomato.formata_campos()
        self.assertEquals(return_value['comorbidades_paciente'], '')

    ...

What should I do with either tox or py.test to run just this newly created test? Thanks!

Update 1: Unfortunatly the suggested answers didn't worked. When I run a single test as suggested by phd and Windsooon, tox doesn't seem to be running any tests. I wrote a test that fails (on purpose) and when I run all tests with tox command, the error shows up:

    def test_formata_campos_para_estomatologia(self):
        estomatologia = Estomatologia()
        retorno = formata_campos(estomatologia)
>       self.assertIn('objetivos', retorno) E       AssertionError: 'objetivos' not found in {'comorbidades_paciente': '', 'tempo_transcorrido': '', 'sinais_e_sintomas_locais': ''}

But when I run only the test individually, the test passes! I get this result:

tox -e py27 -- servicos.tests:FormatacaoDeCamposTestCase.test_formata_campos_para_estomatologia
py27 installed:
py27 runtests: PYTHONHASHSEED='3025337440'
______________________________________________________________ summary ______________________________________________________________
  py27: commands succeeded
  congratulations :)

Digging around the internet, I found that I must have the {posargs} otherwise tox will ignore whatever I supply to it. However only the second line of my commands will use it. The first line will set the test database to SQLite (faster database set for testing). Can this be a bug on tox? Any idea on how to solve this?

Update 2: The answer from @phd was the closest one, but I had to adapt a few things:

Need to use 2 colon marks instead of one

Must use 2 colon marks instead of dot for separating method name from the class

Also had to drop the "-e" parameter, since that enviroment wasn't set on my tox.ini file.

Final command looks like this:

tox -- folder1/folder2/file_name.py::ClassName::test_method_name

Body:
Try

tox -e py27 -- test_file_name_here.py:TestClassName.test_method_name


问:
Interpolate variables in a string
How can i interpolate the variable userName in the string.Im using C#.I added \ but it does not found</p>

```<code> String orderStr = String.Format(@"{
                  ""currency"":""MXN"",
                  ""customer_info"": {
                    ""name"": ""julio"",
                    ""phone"": ""Cabalos"",
                    ""email"": ""el@el.com""
                  },
                  ""line_items"": [{
                    ""name"": ""\'{0}\'"",
                    ""description"": ""descripc"",
                    ""unit_price"": 233,
                    ""quantity"": '1',
                    ""tags"": [""Transporte"", ""Logistic Cloud""],
                    ""type"": ""physical""
                  }],
                 ""charges"":[{
                    ""payment_method"": {
                      ""type"": ""oxxo_cash""
                    }
                  }]
               }", userName);
</code>```

答:
You have to escape the { and } with {{ and }}.
Also you can use interoplated string ($)

```<code>string userName = "userName";
String orderStr = $@"{{
      ""currency"":""MXN"",
      ""customer_info"": {{
        ""name"": ""julio"",
        ""phone"": ""Cabalos"",
        ""email"": ""el@el.com""
      }},
      ""line_items"": [{{
        ""name"": ""\'{userName}\'"",
        ""description"": ""descripc"",
        ""unit_price"": 233,
        ""quantity"": '1',
        ""tags"": [""Transporte"", ""Logistic Cloud""],
        ""type"": ""physical""
      }}],
     ""charges"":[{{
        ""payment_method"": {{
          ""type"": ""oxxo_cash""
        }}
      }}]
   }}";
</code>```

Title: Interpolate variables in a string

Body:
How can i interpolate the variable userName in the string.Im using C#.I added \ but it does not found

 String orderStr = String.Format(@"{
                  ""currency"":""MXN"",
                  ""customer_info"": {
                    ""name"": ""julio"",
                    ""phone"": ""Cabalos"",
                    ""email"": ""el@el.com""
                  },
                  ""line_items"": [{
                    ""name"": ""\'{0}\'"",
                    ""description"": ""descripc"",
                    ""unit_price"": 233,
                    ""quantity"": '1',
                    ""tags"": [""Transporte"", ""Logistic Cloud""],
                    ""type"": ""physical""
                  }],
                 ""charges"":[{
                    ""payment_method"": {
                      ""type"": ""oxxo_cash""
                    }
                  }]
               }", userName);

Body:
You have to escape the { and } with {{ and }}.
Also you can use interoplated string ($)

string userName = "userName";
String orderStr = $@"{{
      ""currency"":""MXN"",
      ""customer_info"": {{
        ""name"": ""julio"",
        ""phone"": ""Cabalos"",
        ""email"": ""el@el.com""
      }},
      ""line_items"": [{{
        ""name"": ""\'{userName}\'"",
        ""description"": ""descripc"",
        ""unit_price"": 233,
        ""quantity"": '1',
        ""tags"": [""Transporte"", ""Logistic Cloud""],
        ""type"": ""physical""
      }}],
     ""charges"":[{{
        ""payment_method"": {{
          ""type"": ""oxxo_cash""
        }}
      }}]
   }}";


问:
How to extend a Vec<String> as HashMap value?
I have a HashMap<String, Vec<String>>. I cannot figure out how to update the value by growing the Vec.  I thought the following would work:

```<code>fn add_employee(mut data: HashMap<String, Vec<String>>) -> HashMap<String, Vec<String>> {
    loop {
        println!("Please enter the name of the employee you would like to manage.");

        let mut employee = String::new();

        io::stdin().read_line(&mut employee).expect(
            "Failed to read line",
        );

        let employee = employee.trim();

        let mut department = String::new();

        println!("Please enter the name of the department you would like to add the employee to.");

        io::stdin().read_line(&mut department).expect(
            "Failed to read line",
        );

        let department = department.trim();

        data.entry(department.to_string())
            .extend(vec![employee.to_string()])
            .or_insert(vec![employee.to_string()]);
    }
}
</code>```

but it instead gives the error

error: no method named `extend` found for type `std::collections::hash_map::Entry<'_, std::string::String, std::vec::Vec<std::string::String>>` in the current scope
  --> src/main.rs:27:14
   |
27 |             .extend(vec![employee.to_string()])
   |              ^^^^^^
```

答:
After thinking about the entry API a little more I came up with the following solution:</p>

```<code>let val = data.entry(department.to_string())
                .or_insert(vec!());

        val.extend(vec!(employee.to_string()));
</code>```

Body:
I have a HashMap<String, Vec<String>>. I cannot figure out how to update the value by growing the Vec.  I thought the following would work:

fn add_employee(mut data: HashMap<String, Vec<String>>) -> HashMap<String, Vec<String>> {
    loop {
        println!("Please enter the name of the employee you would like to manage.");

        let mut employee = String::new();

        io::stdin().read_line(&mut employee).expect(
            "Failed to read line",
        );

        let employee = employee.trim();

        let mut department = String::new();

        println!("Please enter the name of the department you would like to add the employee to.");

        io::stdin().read_line(&mut department).expect(
            "Failed to read line",
        );

        let department = department.trim();

        data.entry(department.to_string())
            .extend(vec![employee.to_string()])
            .or_insert(vec![employee.to_string()]);
    }
}

but it instead gives the error

error: no method named `extend` found for type `std::collections::hash_map::Entry<'_, std::string::String, std::vec::Vec<std::string::String>>` in the current scope
  --> src/main.rs:27:14
   |
27 |             .extend(vec![employee.to_string()])
   |              ^^^^^^

Body:
After thinking about the entry API a little more I came up with the following solution:

let val = data.entry(department.to_string())
                .or_insert(vec!());

        val.extend(vec!(employee.to_string()));


问:
Progress Bar not showing in screen but showing in debugger
I am adding a Progress Bar when the user does a search query, and it will not show up in the screen. Here are the snippets:

```<code>    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button searchButton = (Button) findViewById(R.id.searchButton);
        setContentView(R.layout.activity_main); //main layout, which has a child layout called resultsLayout
        searchButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            EditText searchString = (EditText) findViewById(R.id.searchString);
            search(searchString.getText().toString());
        }
    });

    protected void search(String searchString){
        LinearLayout resultLayout = ((LinearLayout)    findViewById(R.id.resultsLayout));
        resultLayout.addView(DisplayResults.getLoadBar(getApplicationContext()));
        //do search
        resultLayout.removeAllViews();
    }

    public static ProgressBar getLoadBar(Context context){
        ProgressBar loadBar = new ProgressBar(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        loadBar.setLayoutParams(params);
        loadBar.setVisibility(View.VISIBLE);
        return loadBar;
    }
</code>```

I know some of it might not be needed, like the setVisibility right when creating, but I have tried several things and it not works. Perhaps there wasn't enough time to show up the bar?(It takes about 1.5sec for the search)

I have also debugged the application, and it shows the ProgressBar as a child of the layout, but I still cannot see it in the screen.

答:
```<code>ProgressDialog progressDialog; //Create a prog dialog object
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Button searchButton = (Button) findViewById(R.id.searchButton);
    progressDialog=new ProgressDialog(this); //init it
    searchButton.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
        progressDialog.show(); //show it when needed
        EditText searchString = (EditText) findViewById(R.id.searchString);
        search(searchString.getText().toString());
    }
});

protected void search(String searchString){
    progressDialog.dismiss();//dismiss it when the search is complete
    LinearLayout resultLayout = ((LinearLayout)    findViewById(R.id.resultsLayout));
    resultLayout.addView(DisplayResults.getLoadBar(getApplicationContext()));
    //do search
    resultLayout.removeAllViews();
}
</code>```

You could try this ProgressDialog object implementation.
https://developer.android.com/reference/android/app/ProgressDialog.html

Body:
I am adding a Progress Bar when the user does a search query, and it will not show up in the screen. Here are the snippets:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button searchButton = (Button) findViewById(R.id.searchButton);
        setContentView(R.layout.activity_main); //main layout, which has a child layout called resultsLayout
        searchButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            EditText searchString = (EditText) findViewById(R.id.searchString);
            search(searchString.getText().toString());
        }
    });

    protected void search(String searchString){
        LinearLayout resultLayout = ((LinearLayout)    findViewById(R.id.resultsLayout));
        resultLayout.addView(DisplayResults.getLoadBar(getApplicationContext()));
        //do search
        resultLayout.removeAllViews();
    }

    public static ProgressBar getLoadBar(Context context){
        ProgressBar loadBar = new ProgressBar(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        loadBar.setLayoutParams(params);
        loadBar.setVisibility(View.VISIBLE);
        return loadBar;
    }

I know some of it might not be needed, like the setVisibility right when creating, but I have tried several things and it not works. Perhaps there wasn't enough time to show up the bar?(It takes about 1.5sec for the search)

I have also debugged the application, and it shows the ProgressBar as a child of the layout, but I still cannot see it in the screen.

Body:
ProgressDialog progressDialog; //Create a prog dialog object
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Button searchButton = (Button) findViewById(R.id.searchButton);
    progressDialog=new ProgressDialog(this); //init it
    searchButton.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
        progressDialog.show(); //show it when needed
        EditText searchString = (EditText) findViewById(R.id.searchString);
        search(searchString.getText().toString());
    }
});

protected void search(String searchString){
    progressDialog.dismiss();//dismiss it when the search is complete
    LinearLayout resultLayout = ((LinearLayout)    findViewById(R.id.resultsLayout));
    resultLayout.addView(DisplayResults.getLoadBar(getApplicationContext()));
    //do search
    resultLayout.removeAllViews();
}

You could try this ProgressDialog object implementation.
https://developer.android.com/reference/android/app/ProgressDialog.html


问:
How to clean up my Git history
I'm still quite new to Git but have thus far been able to figure out how to do what I want to do with some searching. I'm trying to clean up my Git history and remove a previous commit and branch called bootstrap-v4 but haven't had any luck so far. Can someone suggest how to remove the branch and extra commit and keep my master branch clean?

答:
Your GUI is showing you your uncommitted changes, which is the merge of bootstrap-v4 branch to master. If you do not wish to commit those changes, that is what a git reset --hard origin/master would accomplish (alas, I am not familiar with the operation of your GUI, but it should offer you some way of doing a hard reset)

As for removing the remote branch, on the command line, it would be: git push origin :bootstrap-v4

Title: How to clean up my Git history


问:
Failing to search for full names while querying mysql with php
First time asking on SO. I currently am trying to search a database where the first and last names are seperate. Example:

```<code>player_id | first_name   | last_name
   191         John          Smith
   192         Larry         Citizen
   193         Benjamin      Example
</code>```

I am trying to allow users to search this list using a full name only. I currently have the following code once the user hits submit, it calls usersearch.php.

```<code>session_start();

include '../con.php';

$player = $_POST['name'];

$sql = "SELECT * FROM characters WHERE (concat(first_name,' ',last_name)) = ($player)";

$result = mysqli_query($conn, $sql);

if (!$row = mysqli_fetch_assoc($result)) {

    echo "Found no-one with the name $player. <a href='../search.php'>Try Again?</a>";

} else {

    $_SESSION['selplate'] = $row['plate'];
    $_SESSION['selname'] = $row['first_name, last_name'];

    header("Location: ../profile.php?player=$player");

}
</code>```

No matter the query it will not find users and always returns "Found no-one with the name $player. Try again?"

This was supposed to be the easy part of this project and I am pulling my hair out.

I have spent over an hour searching SO and Google to no avail so it must be my code? afaik it should work.

答:
I would change it to a fulltext index on both first and last name, change the word min on full text indexes. then I would search using  ( some guy as the name )</p>

```<code>  MATCH( first, last )AGAINST('+"some" +"guy"' IN BOOLEAN MODE )
</code>```

Body:
First time asking on SO. I currently am trying to search a database where the first and last names are seperate. Example:

player_id | first_name   | last_name
   191         John          Smith
   192         Larry         Citizen
   193         Benjamin      Example

I am trying to allow users to search this list using a full name only. I currently have the following code once the user hits submit, it calls usersearch.php.

session_start();

include '../con.php';

$player = $_POST['name'];

$sql = "SELECT * FROM characters WHERE (concat(first_name,' ',last_name)) = ($player)";

$result = mysqli_query($conn, $sql);

if (!$row = mysqli_fetch_assoc($result)) {

    echo "Found no-one with the name $player. Try Again?";

} else {

    $_SESSION['selplate'] = $row['plate'];
    $_SESSION['selname'] = $row['first_name, last_name'];

    header("Location: ../profile.php?player=$player");

}

No matter the query it will not find users and always returns "Found no-one with the name $player. Try again?"

This was supposed to be the easy part of this project and I am pulling my hair out.

I have spent over an hour searching SO and Google to no avail so it must be my code? afaik it should work.

Body:
I would change it to a fulltext index on both first and last name, change the word min on full text indexes. then I would search using  ( some guy as the name )

  MATCH( first, last )AGAINST('+"some" +"guy"' IN BOOLEAN MODE )


问:
What is the pythonic way to add type information to an object's attributes?
I'm building classes where I know the intended types of the attributes, but Python of course doesn't. While it's un-pythonic to want to tell it, supposing I do want to, is there an idiomatic way to do so?

Why: I'm reading in foreign-format data (without type information) involving objects-nested-inside-objects. It's easy to put it into nested dictionaries, but I want it in objects of my class-types, to get the right behaviours as well as the data. For instance: suppose my class Book has an attribute isbn which I will fill with an ISBNumber object. My data gives me the isbn as a string; I would like to be able to look at Book and say "That field should be filled by ISBNumber(theString)."

Bonus glee for me if the solution can be applied to classes I get from someone else without editing their code.

(I'm restricted to 2.6, although interested in solutions for 3.x if they exist.)

答:
There's two very nice libraries for this:

atom

traitlets

They both allow you to restrict attributes to a specific type and provide means of notification when an attribute changes.

```<code>from atom.api import Atom, Unicode, Range, Bool, observe
class Person(Atom):
    """ A simple class representing a person object.

    """
    last_name = Unicode()

    first_name = Unicode()

    age = Range(low=0)

    debug = Bool(False)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
There's two very nice libraries for this:

atom

traitlets

They both allow you to restrict attributes to a specific type and provide means of notification when an attribute changes.

from atom.api import Atom, Unicode, Range, Bool, observe
class Person(Atom):
    """ A simple class representing a person object.

    """
    last_name = Unicode()

    first_name = Unicode()

    age = Range(low=0)

    debug = Bool(False)


问:
Angular4 ng-content gets built when ngIf is false
I have a problem with the new ng-content transclusion.

Let's say I have a component my-component that, in its ngOnInit() function does some heavy operation on load (for now, just a console.log()).

I have a wrapper, that displays the content via transclusion (my-wrapper.component.html).

```<code><ng-content></ng-content>
</code>```

If I set the surroundings up like this, the log statement doesn't show:

```<code><my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>
</code>```

I assume, the my-wrapper component does not get built, so the content is ignored.

But if I try to move the logic into the my-wrapper component like this (my-wrapper.component.html):

```<code><ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>
</code>```

I always see the console.log() output. I guess, the my-component gets built and then stored away until the *ngIf becomes true inside my-wrapper.

The intention was to build a generic "list-item + detail" component. Say I have a list of N overview-elements (my-wrapper), that get rendered in a *ngFor loop. Every of those elements has its own detail component (my-component) that is supposed to load its own data, once I decide to show more infos to a specific item.

overview.html:

```<code><ng-container *ngFor="let item of items">
    <my-wrapper>
        <my-component id="item.id"></my-component>
    </my-wrapper>
</ng-container>
</code>```

my-wrapper.component.html:

```<code><div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail">
    <ng-content></ng-content>
</div>
</code>```

Is there a way to tell Angular, to ignore the transcluded content until it is necessary to be added to the page? Analogously to how it was in AngularJS.

答:
By doing this:

```<code><my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>
</code>```

You are not calling MyComponent component, because the *ngIf is false. that means, that not calling it you are not instancing it and, therefore, not passing through its ngOnInit. And that's why you are not getting the console log.

By doing this:

```<code><ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>
</code>```

You are inside the component, you are just limiting what to render in your template, but you already instanced your component and, therefore, you passed through your ngOnInit and you get your console log done.

If, you want to limit something (component call with selector or a ng-content or even a div) until you have some data available, you can do the following:

```<code>datasLoaded: Promise<boolean>;

this.getData().subscribe(
       (data) => {
            this.datasLoaded = Promise.resolve(true); // Setting the Promise as resolved after I have the needed data
       }
);
</code>```

And in your template:

```<code><ng-container *ngIf="datasLoaded | async">
   // stuff here
</ng-container>
</code>```

Or:

```<code><my-component *ngIf="datasLoaded | async">
   // Didn't test this one, but should follow the same logic. If it doesn't, wrap it and add the ngIf to the wrapper
</my-component>
</code>```

Body:
I have a problem with the new ng-content transclusion.

Let's say I have a component my-component that, in its ngOnInit() function does some heavy operation on load (for now, just a console.log()).

I have a wrapper, that displays the content via transclusion (my-wrapper.component.html).

<ng-content></ng-content>

If I set the surroundings up like this, the log statement doesn't show:

<my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>

I assume, the my-wrapper component does not get built, so the content is ignored.

But if I try to move the logic into the my-wrapper component like this (my-wrapper.component.html):

<ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>

I always see the console.log() output. I guess, the my-component gets built and then stored away until the *ngIf becomes true inside my-wrapper.

The intention was to build a generic "list-item + detail" component. Say I have a list of N overview-elements (my-wrapper), that get rendered in a *ngFor loop. Every of those elements has its own detail component (my-component) that is supposed to load its own data, once I decide to show more infos to a specific item.

overview.html:

<ng-container *ngFor="let item of items">
    <my-wrapper>
        <my-component id="item.id"></my-component>
    </my-wrapper>
</ng-container>

my-wrapper.component.html:

Click for more

    <ng-content></ng-content>

Is there a way to tell Angular, to ignore the transcluded content until it is necessary to be added to the page? Analogously to how it was in AngularJS.

Body:
By doing this:

<my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>

You are not calling MyComponent component, because the *ngIf is false. that means, that not calling it you are not instancing it and, therefore, not passing through its ngOnInit. And that's why you are not getting the console log.

By doing this:

<ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>

You are inside the component, you are just limiting what to render in your template, but you already instanced your component and, therefore, you passed through your ngOnInit and you get your console log done.

If, you want to limit something (component call with selector or a ng-content or even a div) until you have some data available, you can do the following:

datasLoaded: Promise<boolean>;

this.getData().subscribe(
       (data) => {
            this.datasLoaded = Promise.resolve(true); // Setting the Promise as resolved after I have the needed data
       }
);

And in your template:

<ng-container *ngIf="datasLoaded | async">
   // stuff here
</ng-container>

Or:

<my-component *ngIf="datasLoaded | async">
   // Didn't test this one, but should follow the same logic. If it doesn't, wrap it and add the ngIf to the wrapper
</my-component>


问:
How to set text a textview in drawer header from shared preference?
Sorry for my English,
I already set a text in drawer header from shared preferences
MainActivity.Java :

```<code> View header = navigationView.getHeaderView(0);
    setNama((TextView) header.findViewById(R.id.headerName));
    setEmail((TextView) header.findViewById(R.id.headerEmail));
    setGambar((CircleImageView)header.findViewById(R.id.gambar));
    gambarProfil=(CircleImageView)header.findViewById(R.id.gambar);
    sp = getApplicationContext().getSharedPreferences(name, mode);

    getNama().setText(sp.getString("fullname", ""));
    getEmail().setText(sp.getString("username", ""));

    Picasso.with(getApplicationContext()).load(base_url+"foto_user/"+sp.getString("username","")+".jpg")
            .placeholder(R.drawable.blank).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
            .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
            .into(gambarProfil);
</code>```

Then i have activity to change my fullname, username and picture profile

Change Profile.java :

```<code> private void saveProfilPreferences(){
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("fullname", fullname.getText().toString());
    editor.putString("no_hp",no_hp.getText().toString());
    editor.putString("foto",username.getText().toString());
    editor.commit();

    //nama.setText(fullname.getText().toString());
}
</code>```

My shared preferences value is already changed, but my drawer header keep storing an old value of my shared preferences, i think its because i must refresh the drawer but i don't know how to do that.

答:
You have to call this code:

```<code>View header = navigationView.getHeaderView(0);
    setNama((TextView) header.findViewById(R.id.headerName));
    setEmail((TextView) header.findViewById(R.id.headerEmail));
    setGambar((CircleImageView)header.findViewById(R.id.gambar));
    gambarProfil=(CircleImageView)header.findViewById(R.id.gambar);
    sp = getApplicationContext().getSharedPreferences(name, mode);

    getNama().setText(sp.getString("fullname", ""));
    getEmail().setText(sp.getString("username", ""));

    Picasso.with(getApplicationContext()).load(base_url+"foto_user/"+sp.getString("username","")+".jpg")
            .placeholder(R.drawable.blank).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
            .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
            .into(gambarProfil);
</code>```

after saving data in shared preferences

Body:
Sorry for my English,
I already set a text in drawer header from shared preferences
MainActivity.Java :

 View header = navigationView.getHeaderView(0);
    setNama((TextView) header.findViewById(R.id.headerName));
    setEmail((TextView) header.findViewById(R.id.headerEmail));
    setGambar((CircleImageView)header.findViewById(R.id.gambar));
    gambarProfil=(CircleImageView)header.findViewById(R.id.gambar);
    sp = getApplicationContext().getSharedPreferences(name, mode);

    getNama().setText(sp.getString("fullname", ""));
    getEmail().setText(sp.getString("username", ""));

    Picasso.with(getApplicationContext()).load(base_url+"foto_user/"+sp.getString("username","")+".jpg")
            .placeholder(R.drawable.blank).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
            .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
            .into(gambarProfil);

Then i have activity to change my fullname, username and picture profile

Change Profile.java :

 private void saveProfilPreferences(){
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("fullname", fullname.getText().toString());
    editor.putString("no_hp",no_hp.getText().toString());
    editor.putString("foto",username.getText().toString());
    editor.commit();

    //nama.setText(fullname.getText().toString());
}

My shared preferences value is already changed, but my drawer header keep storing an old value of my shared preferences, i think its because i must refresh the drawer but i don't know how to do that.

Body:
You have to call this code:

View header = navigationView.getHeaderView(0);
    setNama((TextView) header.findViewById(R.id.headerName));
    setEmail((TextView) header.findViewById(R.id.headerEmail));
    setGambar((CircleImageView)header.findViewById(R.id.gambar));
    gambarProfil=(CircleImageView)header.findViewById(R.id.gambar);
    sp = getApplicationContext().getSharedPreferences(name, mode);

    getNama().setText(sp.getString("fullname", ""));
    getEmail().setText(sp.getString("username", ""));

    Picasso.with(getApplicationContext()).load(base_url+"foto_user/"+sp.getString("username","")+".jpg")
            .placeholder(R.drawable.blank).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
            .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
            .into(gambarProfil);

after saving data in shared preferences


问:
JavaFx Canvas only resizes in height but not in width
I have started programming this app for ploting temperature data, when the screen gets resized, the canvas should resize as well. It initializes correctly but when I want to resize the window, the draw() method will only resize the height, according to the stackpanes height value it is bound to but it will ignore the width entirely. The Listener won't even fire. This I find very strange. Also I have to set the minSize for the StackPane, otherwise nothing will be draw at all. I'm not using FXML.

Does anybody have any ideas?

Edit I changed line 58 from setRight() to setCenter, as mentioned in the solution from InternetUnexplorer. But I was still curious about why it is so, so I did some research. I found this in the internet:

Top/Bottom area: Can shrink/expand horizontally and keep the height
unchanged.

Left/Right area: Can shrink/expand vertically and keep the    length
unchanged.

Center area: Can shrink/expand in both directions.

http://o7planning.org/en/10629/javafx-borderpane-layout-tutorial

Here my main class:

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class main extends Application {

    @Override
    public void start(Stage mainStage) throws Exception {
        TempViewerWindow view = new TempViewerWindow();
        ReadData controller = new ReadData(view);
        controller.selectAll();

        mainStage.setScene(new Scene(view));
        //mainStage.setMinWidth(500);
        //mainStage.setMinHeight(400);
        mainStage.setTitle("Temperature Viewer");
        mainStage.show();
    }

    public static void main(String[] args) {

        launch(args);

    }

}
</code>```

And here my view class:

```<code>import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

public class TempViewerWindow extends BorderPane {

    public TableView<TempData> tableView;
    public Canvas canvas;
    public GraphicsContext gc;
    public StackPane holder;

    public TempViewerWindow() {
        tableView = new TableView<>();
        TableColumn<TempData, String> col_date = new TableColumn<>("Date");
        TableColumn<TempData, Float> col_temperature = new TableColumn<>("Temperature");

        col_date.setCellValueFactory(e -> e.getValue()
                                           .dateProperty());
        col_temperature.setCellValueFactory(e -> e.getValue()
                                                  .temperatureProperty()
                                                  .asObject());

        tableView.getColumns()
                 .addAll(col_date, col_temperature);

        setLeft(tableView);

        holder = new StackPane();
        holder.setMinSize(400, 400); // must be here for some reason

        canvas = new Canvas();

        gc = canvas.getGraphicsContext2D();

        canvas.widthProperty()
              .bind(holder.widthProperty()
                          .subtract(10));
        canvas.heightProperty()
              .bind(holder.heightProperty()
                          .subtract(10));

        canvas.widthProperty()
              .addListener(observable -> redraw(gc));
        canvas.heightProperty()
              .addListener(observable -> redraw(gc));

        holder.getChildren()
              .add(canvas);

        setCenter(holder); //here was the bug

    }

    private void redraw(GraphicsContext gc) {
        gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        gc.setFill(Color.WHITE);
        gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
        System.out.println("redraw!");

    }

}
</code>```

答:
You're using a BorderPane as parent for holder. The holder is used as right child of the BorderPane. However the right/left children are resized to their preferred widths and are resized to fill the height between the top and bottom nodes. (See javadoc)

The left and right children will be resized to their preferred widths and extend the length between the top and bottom nodes.

If you'd use holder as center, it's width would be adjusted the way you expect it.

Alternatively you could use a HBox as base class for TempViewerWindow to achieve this kind of behavior.

```<code>public TempViewerWindow() {
    ...
    this.getChildren().addAll(tableView, holder);
    HBox.setHgrow(holder, Priority.ALWAYS);
    HBox.setHgrow(tableView, Priority.NEVER);
    this.setFillHeight(true);
}
</code>```

Body:
I have started programming this app for ploting temperature data, when the screen gets resized, the canvas should resize as well. It initializes correctly but when I want to resize the window, the draw() method will only resize the height, according to the stackpanes height value it is bound to but it will ignore the width entirely. The Listener won't even fire. This I find very strange. Also I have to set the minSize for the StackPane, otherwise nothing will be draw at all. I'm not using FXML.

Does anybody have any ideas?

Edit I changed line 58 from setRight() to setCenter, as mentioned in the solution from InternetUnexplorer. But I was still curious about why it is so, so I did some research. I found this in the internet:

Top/Bottom area: Can shrink/expand horizontally and keep the height
unchanged.

Left/Right area: Can shrink/expand vertically and keep the    length
unchanged.

Center area: Can shrink/expand in both directions.

http://o7planning.org/en/10629/javafx-borderpane-layout-tutorial

Here my main class:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class main extends Application {

    @Override
    public void start(Stage mainStage) throws Exception {
        TempViewerWindow view = new TempViewerWindow();
        ReadData controller = new ReadData(view);
        controller.selectAll();

        mainStage.setScene(new Scene(view));
        //mainStage.setMinWidth(500);
        //mainStage.setMinHeight(400);
        mainStage.setTitle("Temperature Viewer");
        mainStage.show();
    }

    public static void main(String[] args) {

        launch(args);

    }

}

And here my view class:

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

public class TempViewerWindow extends BorderPane {

    public TableView<TempData> tableView;
    public Canvas canvas;
    public GraphicsContext gc;
    public StackPane holder;

    public TempViewerWindow() {
        tableView = new TableView<>();
        TableColumn<TempData, String> col_date = new TableColumn<>("Date");
        TableColumn<TempData, Float> col_temperature = new TableColumn<>("Temperature");

        col_date.setCellValueFactory(e -> e.getValue()
                                           .dateProperty());
        col_temperature.setCellValueFactory(e -> e.getValue()
                                                  .temperatureProperty()
                                                  .asObject());

        tableView.getColumns()
                 .addAll(col_date, col_temperature);

        setLeft(tableView);

        holder = new StackPane();
        holder.setMinSize(400, 400); // must be here for some reason

        canvas = new Canvas();

        gc = canvas.getGraphicsContext2D();

        canvas.widthProperty()
              .bind(holder.widthProperty()
                          .subtract(10));
        canvas.heightProperty()
              .bind(holder.heightProperty()
                          .subtract(10));

        canvas.widthProperty()
              .addListener(observable -> redraw(gc));
        canvas.heightProperty()
              .addListener(observable -> redraw(gc));

        holder.getChildren()
              .add(canvas);

        setCenter(holder); //here was the bug

    }

    private void redraw(GraphicsContext gc) {
        gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        gc.setFill(Color.WHITE);
        gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
        System.out.println("redraw!");

    }

}

Body:
You're using a BorderPane as parent for holder. The holder is used as right child of the BorderPane. However the right/left children are resized to their preferred widths and are resized to fill the height between the top and bottom nodes. (See javadoc)

The left and right children will be resized to their preferred widths and extend the length between the top and bottom nodes.

If you'd use holder as center, it's width would be adjusted the way you expect it.

Alternatively you could use a HBox as base class for TempViewerWindow to achieve this kind of behavior.

public TempViewerWindow() {
    ...
    this.getChildren().addAll(tableView, holder);
    HBox.setHgrow(holder, Priority.ALWAYS);
    HBox.setHgrow(tableView, Priority.NEVER);
    this.setFillHeight(true);
}


问:
How to do Push Notification in Xamarin Forms
I am working on Xamarin forms. I had been searching for Push notification in Xamarin forms, some said there is no such implementation for Xamarin forms but there are Xamarin.iOS and Xamarin.Android. I am a newbie I may miss many development news on this subject.

I would like to know:

1) Is there any latest development for Xamarin forms for Push Notification?

2) Any sample app to learn from , any tutorial for xamarin form?

3) What are requirements to build this kind of app, what SDK or tools required.

Please help

答:
Push Notifications have slightly different requirements for each platform. You will need to write platform specific code for each of the platforms you wish to target in your Xamarin.Forms App.

The best way to achieve this is with a DependencyService. There is a great overview of how to do this with a number of examples in the Xamarin.Forms guides.

Unfortunately one of the examples is not for Push Notifications. However, there is a great (free) book that contains loads of useful walkthroughs and examples for Xamarin.Forms including a chapter (5) on Push Notifications. There are code recipes for Android, iOS and Windows which should provide you with what you need.

For SDKs/tools I would recommend using an Azure Notification Hub, this can be integrated with each of the major platforms notifications services:

APNS for iOS

Firebase for Android

WNS for Windows

Once configured, this will allow you to send the same notifications to multiple users without worrying which platform they are on.


问:
Dynamically creating asp.net with c# pages
I am struggling with finding clear answers to dynamically creating the same page over and over.  The questions and samples I have found seem to be all over the board on this topic.  I have studied the life cycle and still seem to not have a clear answer as to where code should go.

I have a master page and a content page.  All the content in the content area needs to be dynamically created (text boxes, ddl's, page tabs, buttons/onclick etc.).

After a user fills in data and clicks a submit button, I need to read the values off the form and rebuild the page completely again (not add/remove controls to current content).

My question is then.
Where do I put my code to build the page?
Will this area allow me to use IsPostBack so I can rebuild content with Request.Form values?
Will my buttons _Click events work?
Are there any working samples out there you could direct me to?

Thank you very much for the feedback...

答:
I don't know all the answers to your questions, but I hope this may get you started.  When dynamically generating the UI through code, this happens in Init.  Controls dynamically loaded on Init is key because between init and load, on postback, viewstate is loaded for these controls.

This means you need, on every postback, recreate the page as is to match the previous control tree, then deconstruct it after init and recreate the new UI, if something is supposed to change UI wise.  This is because it validates the tree structure to determine its the same UI.  Now, if you don't need viewstate, this may not be as much of an issue.  I haven't verified this without viewstate to see if it behaves different.

It depends how dynamic you need it, whether you need viewstate (is a big factor).

HTH.


问:
Hiding all elements that doesn't have a particular class nested deep in them
In this very webpage, have about 70 elements, all with the class "card".

Some of the about 70 elements holds another element with the class "pro-content", which is nested deep inside them.

In this image you could see 2 elements. One with the "pro-content" class and an one without, from left to right.

My aim is to hide all elements with this "pro-content" class and keep all others that doesn't have it.

Given the elements with "pro-content" are childNodes, I tried to use the following for...of loop:

```<code>let cardoo = document.querySelectorAll(".card");

for ( const element of cardoo ) {
    if ( !$(element).hasClass('pro-content') ) {
        element.style.display = "none";
    }
}
</code>```

Yet, this code doesn't work properly - It deletes all elements, instead just these without the "pro-content" class.

Note: I would have proffered a pure vanilla ES16 solution, especially to practice more of the ES16-DOMapi relations but if there is no other option, I would use a pure jQuery/ES16-jQuery solution.

答:
After a look in the source Code i think this oneliner makes the job:</p>

```<code>document.querySelectorAll('.pro-content').forEach(el => el.parentNode.parentNode.style.display='none');
</code>```

Body:
In this very webpage, have about 70 elements, all with the class "card".

Some of the about 70 elements holds another element with the class "pro-content", which is nested deep inside them.

In this image you could see 2 elements. One with the "pro-content" class and an one without, from left to right.

My aim is to hide all elements with this "pro-content" class and keep all others that doesn't have it.

Given the elements with "pro-content" are childNodes, I tried to use the following for...of loop:

let cardoo = document.querySelectorAll(".card");

for ( const element of cardoo ) {
    if ( !$(element).hasClass('pro-content') ) {
        element.style.display = "none";
    }
}

Yet, this code doesn't work properly - It deletes all elements, instead just these without the "pro-content" class.

Note: I would have proffered a pure vanilla ES16 solution, especially to practice more of the ES16-DOMapi relations but if there is no other option, I would use a pure jQuery/ES16-jQuery solution.

Body:
After a look in the source Code i think this oneliner makes the job:

document.querySelectorAll('.pro-content').forEach(el => el.parentNode.parentNode.style.display='none');


问:
Ensuring the latest SQL record is always chosen for a calculation
We have a financial log of transactions made by our customers stored in a database table, the table includes information on:

Transaction ID

Customer ID

Date/time of transaction

Amount

Balance

The balance of a new transaction is calculated by taking the latest, previous transaction (using date/time of a transaction) with the same customer ID and summing this with the amount of the new transaction.

As this is a transaction log, none of the details can be modified by a user.

We are using SQL Server's GETDATE to derive the customer's current balance. Is this sufficient to ensure we are always choosing the customer's latest transaction to do the balance calculation? Important for us to do this since if we pick the incorrect transaction, the customers' transaction log would not add up.

Example of what the table could look like (an image since it doesn't look like I can use markdown to create the table):

Our system also has screens to do bulk add of transactions, here we insert the transactions as a SQL batch. Are these any possibilities here where two or more transactions entered for a customer could have same date/time and therefore cause problems with our balance calculations for subsequent transactions?

答:
I think you can query as below windowing function:</p>

```<code>Select *, Balance = sum(Amount) over( partition by CustomerId order by TransactionDate)
    from #Transaction
</code>```

Body:
I think you can query as below windowing function:

Select *, Balance = sum(Amount) over( partition by CustomerId order by TransactionDate)
    from #Transaction


问:
Large vendor.js in Angular CLI
I'm running ng build --prod, and i'm getting a vendor module size of 1.42MB (which is after AOT compiling, default for the cli w/ --prod flag, and uglify, also default for --prod flag)

Not sure what the issue is here. I want to learn more about what goes into that vendor module, and if I'm using AOT compiling, why's it so large?

Thanks!

答:
In order to view the content of your bundle you can use source-map-explorer

All you have to do is run  source-map-explorer vendor.bundle.js

Title: Large vendor.js in Angular CLI


问:
What code analysis tools do you use for your Java projects?
What code analysis tools do you use on your Java projects?

I am interested in all kinds

static code analysis tools (FindBugs, PMD, and any others)

code coverage tools (Cobertura, Emma, and any others)

any other instrumentation-based tools

anything else, if I'm missing something

If applicable, also state what build tools you use and how well these tools integrate with both your IDEs and build tools.

If a tool is only available a specific way (as an IDE plugin, or, say, a build tool plugin) that information is also worth noting.

答:
We are using FindBugs and Checkstyle as well as Clover for Code Coverage.

I think it's important to have some kind of static analysis, supporting your development. Unfortunately it's still not widely spread that these tools are important.

LastEditorDisplayName: Ned Batchelder


问:
C# switch statement limitations - why?
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

```<code>  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }
</code>```

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

答:
I suppose there is no fundamental reason why the compiler couldn't automatically translate your switch statement into:

```<code>if (t == typeof(int))
{
...
}
elseif (t == typeof(string))
{
...
}
...
</code>```

But there isn't much gained by that.

A case statement on integral types allows the compiler to make a number of optimizations:

There is no duplication (unless you duplicate case labels, which the compiler detects).  In your example t could match multiple types due to inheritance.  Should the first match be executed? All of them?

The compiler can choose to implement a switch statement over an integral type by a jump table to avoid all the comparisons.  If you are switching on an enumeration that has integer values 0 to 100 then it creates an array with 100 pointers in it, one for each switch statement. At runtime it simply looks up the address from the array based on the integer value being switched on.  This makes for much better runtime performance than performing 100 comparisons.

OwnerDisplayName: kronoz

Title: C# switch statement limitations - why?

Body:
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

LastEditorDisplayName: ecleel

Body:
I suppose there is no fundamental reason why the compiler couldn't automatically translate your switch statement into:

if (t == typeof(int))
{
...
}
elseif (t == typeof(string))
{
...
}
...

But there isn't much gained by that.

A case statement on integral types allows the compiler to make a number of optimizations:

There is no duplication (unless you duplicate case labels, which the compiler detects).  In your example t could match multiple types due to inheritance.  Should the first match be executed? All of them?

The compiler can choose to implement a switch statement over an integral type by a jump table to avoid all the comparisons.  If you are switching on an enumeration that has integer values 0 to 100 then it creates an array with 100 pointers in it, one for each switch statement. At runtime it simply looks up the address from the array based on the integer value being switched on.  This makes for much better runtime performance than performing 100 comparisons.

OwnerDisplayName: Rob Walker


问:
CSS Copy and paste problem
I've developed a system in my application where emails are picked up with a regex, and then reversed in the source (to thwart bots). I then add the span class 'obfuscate email'. I then use CSS to reverse the the text back to be displayed and Javascript make sure that mailto: links still work.

I was pretty happy with my solution until I realised that copying and pasting the email puts it in the clipboard backwards. I was wondering if there was any way I could remedy this? I've been testing in Firefox 3 for OS X.

The page in question is available here: http://www.leaklocations.com.au/contact-us/

To see the problem, simply copy and paste the email on that site.

答: You can use the same Javascript to reverse the text as well as the mailto links.  If the user doesn't have Javascript, then you can either settle for this problem or use an image.</p>

OwnerDisplayName: alex

Title: CSS Copy and paste problem

OwnerDisplayName: A. Rex