问:
Keep the image after collapse the layout in coordinator layout and set min height
I am working in collapseToolbarLayout, in the design in the appBar it should be an image in the bottom anchor of the appBar (most of the designs put a floatingActionButton .. here I am using an image) I need partially collapse as I scroll up, but not completely. so I get some solution to set a min height from this custom height for appBar

I tried one solution and its work, but, when I scroll up totally the image has been cut and the toolbar disappear , how to make the image stay as it is and not cut, in case of floatingActionButton the button disappear if you understand what I mean in my case which is an image I don't want it to disappear nor been cut

see this image to understand what is happen

what I want is to keep the image like this here and also with the toolbar

here is the layout

```<?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/pink"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".MainActivity"
        android:paddingBottom="?attr/actionBarSize"
        tools:showIn="@layout/activity_main"
        >

        <RelativeLayout
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_marginTop="80dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent">

            <TextView
                android:id="@+id/offerNameTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_marginBottom="20dp"
                android:letterSpacing="0.01"
                android:text="Get a Pizza Free"
                android:textColor="@color/colorPrimary"
                android:textSize="34sp"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/descTitTxt"
                style="@style/AppTheme"
                android:textColor="@color/colorPrimary"
                android:layout_below="@+id/offerNameTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Description"
                />

            <TextView android:id="@+id/offerDescTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="16sp"
                android:layout_below="@+id/descTitTxt"
                android:fontFamily="sans-serif"
                android:textStyle="normal"
                android:layout_marginTop="8dp"
                android:textColor="@color/colorPrimary"
                android:letterSpacing="0.03"
                android:lineSpacingExtra="12sp"
                android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Rutrum
      placerat habitant in eget. Enim elementum in sed lorem nisi purus pharetra. Suscipit
      pellentesque nibh interdum ultrices enim, amet libero gravida scelerisque Rutrum
      placerat."
                />

            <View
                android:id="@+id/line"
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:layout_marginTop="100dp"
                android:layout_below="@+id/offerDescTxt"
                android:background="@color/colorPrimary"
                android:alpha="0.4"/>

            <LinearLayout
                android:id="@+id/socialMediaLayout"
                android:layout_marginTop="40dp"
                android:layout_below="@+id/line"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="center"
                android:padding="10dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:layout_marginEnd="40dp"
                    android:src="@drawable/ic_launcher_background"/>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:layout_marginEnd="40dp"
                    android:src="@drawable/abc_vector_test"/>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:layout_marginEnd="40dp"
                    android:src="@drawable/ic_launcher_background"/>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:layout_marginEnd="40dp"
                    android:src="@drawable/ic_launcher_foreground"/>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:src="@drawable/ic_launcher_foreground"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginTop="20dp"
                android:layout_below="@+id/socialMediaLayout"
                >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />
            </LinearLayout>

        </RelativeLayout>

    </androidx.core.widget.NestedScrollView>
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:fitsSystemWindows="true">

        <om.metamorph.mycollapsingdemo.CustomCollapseLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:minHeight="100dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/expandedImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:background="@drawable/immmg"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7" />

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:background="@color/colorPrimary"
                android:alpha="0.8"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center">

                    <TextView
                        android:id="@+id/TitleTxt"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:fontFamily="sans-serif-medium"
                        android:gravity="bottom|center"
                        android:text="Pizza Hut"
                        android:textColor="@color/colorAccent"
                        android:textSize="18sp"
                        android:textStyle="bold" />
                </RelativeLayout>

            </androidx.appcompat.widget.Toolbar>

        </om.metamorph.mycollapsingdemo.CustomCollapseLayout>
    </com.google.android.material.appbar.AppBarLayout>

    <ImageView
        android:id="@+id/fab"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="16dp"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|start"
        android:src="@drawable/img22" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

```

<p>and here the MainActivity</p>

```public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageView fab = (ImageView) findViewById(R.id.fab);

    fab.bringToFront();
    AppBarLayout mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
    mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
        boolean isShow = false;
        int scrollRange = -1;

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

            /**
             * Collapsed
             */
            if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
                fab.animate().scaleX((float)0.4).setDuration(3000);
                fab.animate().scaleY((float)0.4).setDuration(3000);
                fab.animate().alpha(1).setDuration(0);

                /**
                 * Expanded
                 */
            } else if (verticalOffset == 0) {
                fab.animate().scaleX((float)1).setDuration(100);
                fab.animate().scaleY((float)1).setDuration(100);
                fab.animate().alpha(1).setDuration(0);
                /**
                 * Somewhere in between
                 */
            } else {
                final int scrollRange = appBarLayout.getTotalScrollRange();
                float offsetFactor = (float) (-verticalOffset) / (float) scrollRange;
                float scaleFactor = 1F - offsetFactor * .5F;
                fab.animate().scaleX(scaleFactor);
                fab.animate().scaleY(scaleFactor);
            }
        }
    });

}
}
```

<p>and this the custom collapse layout class that I used to fix the height to what I want,</p>

```public class CustomCollapseLayout extends FrameLayout {
    private static final String TAG = "CollapsingImageLayout";

    private WindowInsetsCompat mLastInsets;

    private int mImageTopExpanded;

    private int mImageTopCollapsed;

    private OnOffsetChangedListener mOnOffsetChangedListener;

    public CustomCollapseLayout(Context context) {
        this(context, null);
    }

    public CustomCollapseLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomCollapseLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mImageTopCollapsed = getResources().getDimensionPixelOffset(R.dimen.image_top_margin_collapsed);

        ViewCompat.setOnApplyWindowInsetsListener(this,
                new androidx.core.view.OnApplyWindowInsetsListener() {
                    @Override
                    public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                        return setWindowInsets(insets);
                    }
                });
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        // Add an OnOffsetChangedListener if possible
        final ViewParent parent = getParent();
        if (parent instanceof AppBarLayout) {
            if (mOnOffsetChangedListener == null) {
                mOnOffsetChangedListener = new OnOffsetChangedListener();
            }
            ((AppBarLayout) parent).addOnOffsetChangedListener(mOnOffsetChangedListener);
        }

        // We're attached, so lets request an inset dispatch
        ViewCompat.requestApplyInsets(this);
    }

    private WindowInsetsCompat setWindowInsets(WindowInsetsCompat insets) {
        if (mLastInsets != insets) {
            mLastInsets = insets;
            requestLayout();
        }
        return insets.consumeSystemWindowInsets();
    }

    class OnOffsetChangedListener implements AppBarLayout.OnOffsetChangedListener {

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

        }
    }
}
```

please help I am new to cllapsetoolbarlayout, if something not clear tell me please, thanks in advance

答:
the hack here is to make ImageView on top of other layouts be giving it higher z-index

```<code>final ImageView fab = (ImageView) findViewById(R.id.fab);
ViewCompat.setTranslationZ(fab, 100);
</code>```

Body:
I am working in collapseToolbarLayout, in the design in the appBar it should be an image in the bottom anchor of the appBar (most of the designs put a floatingActionButton .. here I am using an image) I need partially collapse as I scroll up, but not completely. so I get some solution to set a min height from this custom height for appBar

I tried one solution and its work, but, when I scroll up totally the image has been cut and the toolbar disappear , how to make the image stay as it is and not cut, in case of floatingActionButton the button disappear if you understand what I mean in my case which is an image I don't want it to disappear nor been cut

see this image to understand what is happen

what I want is to keep the image like this here and also with the toolbar

here is the layout

<?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/pink"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".MainActivity"
        android:paddingBottom="?attr/actionBarSize"
        tools:showIn="@layout/activity_main"
        >

        <RelativeLayout
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_marginTop="80dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent">

            <TextView
                android:id="@+id/offerNameTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_marginBottom="20dp"
                android:letterSpacing="0.01"
                android:text="Get a Pizza Free"
                android:textColor="@color/colorPrimary"
                android:textSize="34sp"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/descTitTxt"
                style="@style/AppTheme"
                android:textColor="@color/colorPrimary"
                android:layout_below="@+id/offerNameTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Description"
                />

            <TextView android:id="@+id/offerDescTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="16sp"
                android:layout_below="@+id/descTitTxt"
                android:fontFamily="sans-serif"
                android:textStyle="normal"
                android:layout_marginTop="8dp"
                android:textColor="@color/colorPrimary"
                android:letterSpacing="0.03"
                android:lineSpacingExtra="12sp"
                android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Rutrum
      placerat habitant in eget. Enim elementum in sed lorem nisi purus pharetra. Suscipit
      pellentesque nibh interdum ultrices enim, amet libero gravida scelerisque Rutrum
      placerat."
                />

            <View
                android:id="@+id/line"
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:layout_marginTop="100dp"
                android:layout_below="@+id/offerDescTxt"
                android:background="@color/colorPrimary"
                android:alpha="0.4"/>

            <LinearLayout
                android:id="@+id/socialMediaLayout"
                android:layout_marginTop="40dp"
                android:layout_below="@+id/line"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="center"
                android:padding="10dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:layout_marginEnd="40dp"
                    android:src="@drawable/ic_launcher_background"/>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:layout_marginEnd="40dp"
                    android:src="@drawable/abc_vector_test"/>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:layout_marginEnd="40dp"
                    android:src="@drawable/ic_launcher_background"/>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:layout_marginEnd="40dp"
                    android:src="@drawable/ic_launcher_foreground"/>

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:tint="@color/colorPrimary"
                    android:src="@drawable/ic_launcher_foreground"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginTop="20dp"
                android:layout_below="@+id/socialMediaLayout"
                >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:fontFamily="sans-serif-medium"
                    android:textStyle="normal"
                    android:textColor="@color/colorPrimary"
                    android:letterSpacing="0.01"
                    android:lineSpacingExtra="6sp"
                    android:text=" Contact"
                    />
            </LinearLayout>

        </RelativeLayout>

    </androidx.core.widget.NestedScrollView>
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:fitsSystemWindows="true">

        <om.metamorph.mycollapsingdemo.CustomCollapseLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:minHeight="100dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/expandedImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:background="@drawable/immmg"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7" />

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:background="@color/colorPrimary"
                android:alpha="0.8"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center">

                    <TextView
                        android:id="@+id/TitleTxt"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:fontFamily="sans-serif-medium"
                        android:gravity="bottom|center"
                        android:text="Pizza Hut"
                        android:textColor="@color/colorAccent"
                        android:textSize="18sp"
                        android:textStyle="bold" />
                </RelativeLayout>

            </androidx.appcompat.widget.Toolbar>

        </om.metamorph.mycollapsingdemo.CustomCollapseLayout>
    </com.google.android.material.appbar.AppBarLayout>

    <ImageView
        android:id="@+id/fab"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="16dp"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|start"
        android:src="@drawable/img22" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

and here the MainActivity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageView fab = (ImageView) findViewById(R.id.fab);

    fab.bringToFront();
    AppBarLayout mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
    mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
        boolean isShow = false;
        int scrollRange = -1;

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

            /**
             * Collapsed
             */
            if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
                fab.animate().scaleX((float)0.4).setDuration(3000);
                fab.animate().scaleY((float)0.4).setDuration(3000);
                fab.animate().alpha(1).setDuration(0);

                /**
                 * Expanded
                 */
            } else if (verticalOffset == 0) {
                fab.animate().scaleX((float)1).setDuration(100);
                fab.animate().scaleY((float)1).setDuration(100);
                fab.animate().alpha(1).setDuration(0);
                /**
                 * Somewhere in between
                 */
            } else {
                final int scrollRange = appBarLayout.getTotalScrollRange();
                float offsetFactor = (float) (-verticalOffset) / (float) scrollRange;
                float scaleFactor = 1F - offsetFactor * .5F;
                fab.animate().scaleX(scaleFactor);
                fab.animate().scaleY(scaleFactor);
            }
        }
    });

}
}

and this the custom collapse layout class that I used to fix the height to what I want,

public class CustomCollapseLayout extends FrameLayout {
    private static final String TAG = "CollapsingImageLayout";

    private WindowInsetsCompat mLastInsets;

    private int mImageTopExpanded;

    private int mImageTopCollapsed;

    private OnOffsetChangedListener mOnOffsetChangedListener;

    public CustomCollapseLayout(Context context) {
        this(context, null);
    }

    public CustomCollapseLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomCollapseLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mImageTopCollapsed = getResources().getDimensionPixelOffset(R.dimen.image_top_margin_collapsed);

        ViewCompat.setOnApplyWindowInsetsListener(this,
                new androidx.core.view.OnApplyWindowInsetsListener() {
                    @Override
                    public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                        return setWindowInsets(insets);
                    }
                });
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        // Add an OnOffsetChangedListener if possible
        final ViewParent parent = getParent();
        if (parent instanceof AppBarLayout) {
            if (mOnOffsetChangedListener == null) {
                mOnOffsetChangedListener = new OnOffsetChangedListener();
            }
            ((AppBarLayout) parent).addOnOffsetChangedListener(mOnOffsetChangedListener);
        }

        // We're attached, so lets request an inset dispatch
        ViewCompat.requestApplyInsets(this);
    }

    private WindowInsetsCompat setWindowInsets(WindowInsetsCompat insets) {
        if (mLastInsets != insets) {
            mLastInsets = insets;
            requestLayout();
        }
        return insets.consumeSystemWindowInsets();
    }

    class OnOffsetChangedListener implements AppBarLayout.OnOffsetChangedListener {

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

        }
    }
}

please help I am new to cllapsetoolbarlayout, if something not clear tell me please, thanks in advance

Body:
the hack here is to make ImageView on top of other layouts be giving it higher z-index

final ImageView fab = (ImageView) findViewById(R.id.fab);
ViewCompat.setTranslationZ(fab, 100);


来源: stackexchange

问:
Removing background color from image opencv python
I have many images of specimen which have uncontrollable background color.  Some of them have black background.  Some of them have white background. Some of them have green background, etc.

I would like to remove these background color of a given image where the object in the image is just only one specimen.  I try this code but it does not work as i expect.

```<code>def get_holes(image, thresh):
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        im_bw = cv2.threshold(gray, thresh, 255, cv2.THRESH_BINARY)[1]
        im_bw_inv = cv2.bitwise_not(im_bw)

        _, contour, _ = cv2.findContours(im_bw_inv, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
        for cnt in contour:
            cv2.drawContours(im_bw_inv, [cnt], 0, 255, -1)

        nt = cv2.bitwise_not(im_bw)
        im_bw_inv = cv2.bitwise_or(im_bw_inv, nt)
        return im_bw_inv

    def remove_background(image, thresh, scale_factor=.25, kernel_range=range(1, 15), border=None):
        border = border or kernel_range[-1]

        holes = get_holes(image, thresh)
        small = cv2.resize(holes, None, fx=scale_factor, fy=scale_factor)
        bordered = cv2.copyMakeBorder(small, border, border, border, border, cv2.BORDER_CONSTANT)

        for i in kernel_range:
            kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*i+1, 2*i+1))
            bordered = cv2.morphologyEx(bordered, cv2.MORPH_CLOSE, kernel)

        unbordered = bordered[border: -border, border: -border]
        mask = cv2.resize(unbordered, (image.shape[1], image.shape[0]))
        fg = cv2.bitwise_and(image, image, mask=mask)
        return fg

file = your_file_location
img = cv2.imread(file)
nb_img = dm.remove_background(img, 255)
</code>```

These are some example images

May i have your suggestions?

答:
Here's a simple approach with the assumption that there is only one specimen per image.

Kmeans color quantization. We load the image then perform Kmeans color quantization to segment the image into a specified cluster of colors. For instance with clusters=4, the image will be labeled into four colors.

Obtain binary image. Convert to grayscale, Gaussian blur, adaptive threshold.

Draw largest enclosing circle onto mask. Find contours, sort for largest contour using contour area filtering then draw the largest enclosing circle onto a mask using cv2.minEnclosingCircle.

Bitwise-and. Since we have isolated the desired sections to extract, we simply bitwise-and the mask and input image

Input image -> Kmeans -> Binary image

Detected largest enclosing circle -> Mask -> Result

Here's the output for the second image

Input image -> Kmeans -> Binary image

Detected largest enclosing circle -> Mask -> Result

Code

```<code>import cv2
import numpy as np

# Kmeans color segmentation
def kmeans_color_quantization(image, clusters=8, rounds=1):
    h, w = image.shape[:2]
    samples = np.zeros([h*w,3], dtype=np.float32)
    count = 0

    for x in range(h):
        for y in range(w):
            samples[count] = image[x][y]
            count += 1

    compactness, labels, centers = cv2.kmeans(samples,
            clusters,
            None,
            (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001),
            rounds,
            cv2.KMEANS_RANDOM_CENTERS)

    centers = np.uint8(centers)
    res = centers[labels.flatten()]
    return res.reshape((image.shape))

# Load image and perform kmeans
image = cv2.imread('2.jpg')
original = image.copy()
kmeans = kmeans_color_quantization(image, clusters=4)

# Convert to grayscale, Gaussian blur, adaptive threshold
gray = cv2.cvtColor(kmeans, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,21,2)

# Draw largest enclosing circle onto a mask
mask = np.zeros(original.shape[:2], dtype=np.uint8)
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in cnts:
    ((x, y), r) = cv2.minEnclosingCircle(c)
    cv2.circle(image, (int(x), int(y)), int(r), (36, 255, 12), 2)
    cv2.circle(mask, (int(x), int(y)), int(r), 255, -1)
    break

# Bitwise-and for result
result = cv2.bitwise_and(original, original, mask=mask)
result[mask==0] = (255,255,255)

cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.imshow('mask', mask)
cv2.imshow('kmeans', kmeans)
cv2.imshow('image', image)
cv2.waitKey()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have many images of specimen which have uncontrollable background color.  Some of them have black background.  Some of them have white background. Some of them have green background, etc.

I would like to remove these background color of a given image where the object in the image is just only one specimen.  I try this code but it does not work as i expect.

def get_holes(image, thresh):
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        im_bw = cv2.threshold(gray, thresh, 255, cv2.THRESH_BINARY)[1]
        im_bw_inv = cv2.bitwise_not(im_bw)

        _, contour, _ = cv2.findContours(im_bw_inv, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
        for cnt in contour:
            cv2.drawContours(im_bw_inv, [cnt], 0, 255, -1)

        nt = cv2.bitwise_not(im_bw)
        im_bw_inv = cv2.bitwise_or(im_bw_inv, nt)
        return im_bw_inv

    def remove_background(image, thresh, scale_factor=.25, kernel_range=range(1, 15), border=None):
        border = border or kernel_range[-1]

        holes = get_holes(image, thresh)
        small = cv2.resize(holes, None, fx=scale_factor, fy=scale_factor)
        bordered = cv2.copyMakeBorder(small, border, border, border, border, cv2.BORDER_CONSTANT)

        for i in kernel_range:
            kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*i+1, 2*i+1))
            bordered = cv2.morphologyEx(bordered, cv2.MORPH_CLOSE, kernel)

        unbordered = bordered[border: -border, border: -border]
        mask = cv2.resize(unbordered, (image.shape[1], image.shape[0]))
        fg = cv2.bitwise_and(image, image, mask=mask)
        return fg

file = your_file_location
img = cv2.imread(file)
nb_img = dm.remove_background(img, 255)

These are some example images

May i have your suggestions?

Body:
Here's a simple approach with the assumption that there is only one specimen per image.

Kmeans color quantization. We load the image then perform Kmeans color quantization to segment the image into a specified cluster of colors. For instance with clusters=4, the image will be labeled into four colors.

Obtain binary image. Convert to grayscale, Gaussian blur, adaptive threshold.

Draw largest enclosing circle onto mask. Find contours, sort for largest contour using contour area filtering then draw the largest enclosing circle onto a mask using cv2.minEnclosingCircle.

Bitwise-and. Since we have isolated the desired sections to extract, we simply bitwise-and the mask and input image

Input image -> Kmeans -> Binary image

Detected largest enclosing circle -> Mask -> Result

Here's the output for the second image

Input image -> Kmeans -> Binary image

Detected largest enclosing circle -> Mask -> Result

Code

import cv2
import numpy as np

# Kmeans color segmentation
def kmeans_color_quantization(image, clusters=8, rounds=1):
    h, w = image.shape[:2]
    samples = np.zeros([h*w,3], dtype=np.float32)
    count = 0

    for x in range(h):
        for y in range(w):
            samples[count] = image[x][y]
            count += 1

    compactness, labels, centers = cv2.kmeans(samples,
            clusters,
            None,
            (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001),
            rounds,
            cv2.KMEANS_RANDOM_CENTERS)

    centers = np.uint8(centers)
    res = centers[labels.flatten()]
    return res.reshape((image.shape))

# Load image and perform kmeans
image = cv2.imread('2.jpg')
original = image.copy()
kmeans = kmeans_color_quantization(image, clusters=4)

# Convert to grayscale, Gaussian blur, adaptive threshold
gray = cv2.cvtColor(kmeans, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,21,2)

# Draw largest enclosing circle onto a mask
mask = np.zeros(original.shape[:2], dtype=np.uint8)
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in cnts:
    ((x, y), r) = cv2.minEnclosingCircle(c)
    cv2.circle(image, (int(x), int(y)), int(r), (36, 255, 12), 2)
    cv2.circle(mask, (int(x), int(y)), int(r), 255, -1)
    break

# Bitwise-and for result
result = cv2.bitwise_and(original, original, mask=mask)
result[mask==0] = (255,255,255)

cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.imshow('mask', mask)
cv2.imshow('kmeans', kmeans)
cv2.imshow('image', image)
cv2.waitKey()


问:
How to set the gravity on a GTK3+ window in python
I run python 2.7.13 on windows 7.
I am creating a window with Gtk (from pygobject 3.18.2).

I am running windows 7 with a custom shell and I am trying to make a toolbar at the bottom of the screen.

I use a grid to divide the window in  a top and a bottom part.

The bottom part is always visible.
The top part must show above the bottom part on mouse enter and hide on mouse leave without moving the bottom part.

The default positioning of a window uses the top-left corner of the window, but this will cause the bottom part to shift up to the position of the top part when the top part is hidden.

I think I understand that I have to use

set_gravity(Gdk.Gravity.SOUTH_WEST)

to change this behaviour

I do not get errors, but it seems this setting is ignored. The placement of the window is not affected at all.

What am I missing?

Anything wrong in the way I call set_gravity()?

Is set_gravity the right way to achieve this?

I read Set window gravity in PyGObject?, but this question is still not answered

Here is the code I try to get working

```<code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Test")
        self.set_decorated(0)
        self.screen = Gdk.Screen.get_default()
        self.connect("destroy", self.destroy)
        self.connect("enter-notify-event", self.mouseenter)
        self.connect("leave-notify-event", self.mouseleave)

        self.label1 = Gtk.Label("Label1\n    line1\n    line2")
        self.label2 = Gtk.Label("Label2")

        self.label1.set_hexpand(True)
        self.label2.set_hexpand(True)

        self.maingrid = Gtk.Grid()
        self.add(self.maingrid)

        self.maingrid.attach(self.label1, 0, 0, 1, 1)
        self.maingrid.attach(self.label2, 0, 1, 1, 1)

        self.set_gravity(Gdk.Gravity.SOUTH_WEST)  # looks like this is ignored
        print self.get_gravity()

    def mouseleave(self, widget, data=None):
        print "mouse leave"

        self.label1.hide()
        label2_height = self.label2.get_allocation().height
        self.resize(self.screen.width(), label2_height)

    def mouseenter(self, widget, data=None):
        print "mouse enter"

        label1_height = self.label1.get_allocation().height
        label2_height = self.label2.get_allocation().height
        self.resize(self.screen.width(), label1_height + label2_height)

        self.label1.show()

        # Here I expect label2 to stay where it is at the bottom of the screen and label1 to be drawn above label2.
        # But label2 is pushed down to make space for label1
        # (normal behaviour if Gdk.Gravity.SOUTH_WEST is not set)

    def destroy(self, widget, data=None):
        print "destroy signal occurred"
        Gtk.main_quit()

win = MyWindow()
win.show_all()
win.label1.hide()

height = win.label2.get_allocation().height
win.resize(win.screen.width(), height)

#win.move(0, win.screen.height())           # I expect this to place the window at the bottom of the screen
                                            # if Gdk.Gravity.SOUTH_WEST is set, but it is placed offscreen
                                            # (normal behaviour if Gdk.Gravity.SOUTH_WEST is not set)

win.move(0, win.screen.height() - 200)      # shift it up 200 pixels to see what is happening

Gtk.main()
</code>```

Here is a working version where I move the window to it's proper position after resizing. Moving the window makes the window flicker and it also generates the leave-notify-event and the enter-notify-event.

```<code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Test")
        self.set_decorated(0)
        self.screen = Gdk.Screen.get_default()
#        self.set_gravity(Gdk.Gravity.SOUTH_WEST)
        self.connect("destroy", self.destroy)
        self.connect("enter-notify-event", self.mouseenter)
        self.connect("leave-notify-event", self.mouseleave)

        self.label1 = Gtk.Label("Label1\n    line1\n    line2")
        self.label2 = Gtk.Label("Label2")

        self.label1.set_hexpand(True)
        self.label2.set_hexpand(True)

        self.maingrid = Gtk.Grid()
        self.add(self.maingrid)

        self.maingrid.attach(self.label1, 0, 0, 1, 1)
        self.maingrid.attach(self.label2, 0, 1, 1, 1)
        self.ismoving = 0

    def mouseleave(self, widget, data=None):
        print "mouse leave"

        if self.ismoving:
            print "window is moving"
        else:
            self.label1.hide()
            label2_height = self.label2.get_allocation().height
            self.resize(self.screen.width(), label2_height)
            self.move(0, self.screen.height() - label2_height)

    def mouseenter(self, widget, data=None):
        print "mouse enter"

        if self.ismoving:           # moving the window generates a leave-notify-event and a enter-notify-event
            self.ismoving = 0       # ignore these events when moving the window
        else:
            self.ismoving = 1

            label1_height = self.label1.get_allocation().height
            label2_height = self.label2.get_allocation().height
            self.resize(self.screen.width(), label1_height + label2_height)

            self.move(0, self.screen.height()-label1_height - label2_height)

            self.label1.show()

    def destroy(self, widget, data=None):
        print "destroy signal occurred"
        Gtk.main_quit()

win = MyWindow()
win.show_all()
win.label1.hide()

height = win.label2.get_allocation().height
win.resize(win.screen.width(), height)
win.move(0, win.screen.height() - height)

Gtk.main()
</code>```

Based on AlexB's comment i assume my code is correct, but it is not working for me. I don't see any reason why it will not run under python 2. Maybe there is an issue with the window manager. I'll investigate

Did anyone succesfully use set_gravity() on windows?

答: Documentation indicates it may or may not work, depending on Window Manager. It doesn't for me on Xubuntu 18.04</p>

ContentLicense: CC BY-SA 3.0

Body:
I run python 2.7.13 on windows 7.
I am creating a window with Gtk (from pygobject 3.18.2).

I am running windows 7 with a custom shell and I am trying to make a toolbar at the bottom of the screen.

I use a grid to divide the window in  a top and a bottom part.

The bottom part is always visible.
The top part must show above the bottom part on mouse enter and hide on mouse leave without moving the bottom part.

The default positioning of a window uses the top-left corner of the window, but this will cause the bottom part to shift up to the position of the top part when the top part is hidden.

I think I understand that I have to use

set_gravity(Gdk.Gravity.SOUTH_WEST)

to change this behaviour

I do not get errors, but it seems this setting is ignored. The placement of the window is not affected at all.

What am I missing?

Anything wrong in the way I call set_gravity()?

Is set_gravity the right way to achieve this?

I read Set window gravity in PyGObject?, but this question is still not answered

Here is the code I try to get working

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Test")
        self.set_decorated(0)
        self.screen = Gdk.Screen.get_default()
        self.connect("destroy", self.destroy)
        self.connect("enter-notify-event", self.mouseenter)
        self.connect("leave-notify-event", self.mouseleave)

        self.label1 = Gtk.Label("Label1\n    line1\n    line2")
        self.label2 = Gtk.Label("Label2")

        self.label1.set_hexpand(True)
        self.label2.set_hexpand(True)

        self.maingrid = Gtk.Grid()
        self.add(self.maingrid)

        self.maingrid.attach(self.label1, 0, 0, 1, 1)
        self.maingrid.attach(self.label2, 0, 1, 1, 1)

        self.set_gravity(Gdk.Gravity.SOUTH_WEST)  # looks like this is ignored
        print self.get_gravity()

    def mouseleave(self, widget, data=None):
        print "mouse leave"

        self.label1.hide()
        label2_height = self.label2.get_allocation().height
        self.resize(self.screen.width(), label2_height)

    def mouseenter(self, widget, data=None):
        print "mouse enter"

        label1_height = self.label1.get_allocation().height
        label2_height = self.label2.get_allocation().height
        self.resize(self.screen.width(), label1_height + label2_height)

        self.label1.show()

        # Here I expect label2 to stay where it is at the bottom of the screen and label1 to be drawn above label2.
        # But label2 is pushed down to make space for label1
        # (normal behaviour if Gdk.Gravity.SOUTH_WEST is not set)

    def destroy(self, widget, data=None):
        print "destroy signal occurred"
        Gtk.main_quit()

win = MyWindow()
win.show_all()
win.label1.hide()

height = win.label2.get_allocation().height
win.resize(win.screen.width(), height)

#win.move(0, win.screen.height())           # I expect this to place the window at the bottom of the screen
                                            # if Gdk.Gravity.SOUTH_WEST is set, but it is placed offscreen
                                            # (normal behaviour if Gdk.Gravity.SOUTH_WEST is not set)

win.move(0, win.screen.height() - 200)      # shift it up 200 pixels to see what is happening

Gtk.main()

Here is a working version where I move the window to it's proper position after resizing. Moving the window makes the window flicker and it also generates the leave-notify-event and the enter-notify-event.

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Test")
        self.set_decorated(0)
        self.screen = Gdk.Screen.get_default()
#        self.set_gravity(Gdk.Gravity.SOUTH_WEST)
        self.connect("destroy", self.destroy)
        self.connect("enter-notify-event", self.mouseenter)
        self.connect("leave-notify-event", self.mouseleave)

        self.label1 = Gtk.Label("Label1\n    line1\n    line2")
        self.label2 = Gtk.Label("Label2")

        self.label1.set_hexpand(True)
        self.label2.set_hexpand(True)

        self.maingrid = Gtk.Grid()
        self.add(self.maingrid)

        self.maingrid.attach(self.label1, 0, 0, 1, 1)
        self.maingrid.attach(self.label2, 0, 1, 1, 1)
        self.ismoving = 0

    def mouseleave(self, widget, data=None):
        print "mouse leave"

        if self.ismoving:
            print "window is moving"
        else:
            self.label1.hide()
            label2_height = self.label2.get_allocation().height
            self.resize(self.screen.width(), label2_height)
            self.move(0, self.screen.height() - label2_height)

    def mouseenter(self, widget, data=None):
        print "mouse enter"

        if self.ismoving:           # moving the window generates a leave-notify-event and a enter-notify-event
            self.ismoving = 0       # ignore these events when moving the window
        else:
            self.ismoving = 1

            label1_height = self.label1.get_allocation().height
            label2_height = self.label2.get_allocation().height
            self.resize(self.screen.width(), label1_height + label2_height)

            self.move(0, self.screen.height()-label1_height - label2_height)

            self.label1.show()

    def destroy(self, widget, data=None):
        print "destroy signal occurred"
        Gtk.main_quit()

win = MyWindow()
win.show_all()
win.label1.hide()

height = win.label2.get_allocation().height
win.resize(win.screen.width(), height)
win.move(0, win.screen.height() - height)

Gtk.main()

Based on AlexB's comment i assume my code is correct, but it is not working for me. I don't see any reason why it will not run under python 2. Maybe there is an issue with the window manager. I'll investigate

Did anyone succesfully use set_gravity() on windows?


问:
NoReverseMatch at /user/password_reset/ Reverse for 'password_reset_done' not found
I'm trying to use the Django authentication system, but I'm getting the error:
enter image description here

'user' is an app name.

Project's urls.py:

```<code>from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
     url(r'^admin/', admin.site.urls),
     ...
     url(r'^user/', include('user.urls', namespace='user')),
     ...
]
</code>```

user/urls.py:

```<code>from django.conf.urls import url, include

from . import views

urlpatterns = [
    url(r'^register/$', views.register, name='register'),
    url(r'^settings/$', views.settings, name='settings'),
    url(r'^settings/password/$', views.password, name='password'),
    url(r'^settings/accounts/$', views.configure_accounts,
        name='configure_accounts'),
    url(r'^settings/accounts/error/$', views.configure_accounts_error,
        name='configure_accounts_error'),
    url('^', include('django.contrib.auth.urls')),
]
</code>```

I can access /user/login/, /user/logout/. When I go to /user/password_reset/, I can enter email, and, after pressing 'Submit' button, an error occurs (shown at picture):

```<code>NoReverseMatch at /user/password_reset/
Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name.
</code>```

Any ideas how to fix this?
Thanks a lot.

答:
I ran into this issue too. These posts are outdated, so I want to give a revised answer. Essentially the PasswordResetConfirmView has the property of success_url which can be set at urls.py.

So for example...

```<code>path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(
    template_name='password-reset-confirm.html', success_url=reverse_lazy(
        'user:password_reset_complete')),
     name="password_reset_confirm"),
</code>```

The problem is the default behavior of the Password Reset Confirm. Specifically it sets the success_url = reverse_lazy('password_reset_complete'). Since your password_reset_complete view is in your "user" app, it can't find it. The default property is telling it to look at the root urls.py when you need it to be looking at user/urls.py. Overriding the success_url will solve this problem.

Body:
I'm trying to use the Django authentication system, but I'm getting the error:
enter image description here

'user' is an app name.

Project's urls.py:

from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
     url(r'^admin/', admin.site.urls),
     ...
     url(r'^user/', include('user.urls', namespace='user')),
     ...
]

user/urls.py:

from django.conf.urls import url, include

from . import views

urlpatterns = [
    url(r'^register/$', views.register, name='register'),
    url(r'^settings/$', views.settings, name='settings'),
    url(r'^settings/password/$', views.password, name='password'),
    url(r'^settings/accounts/$', views.configure_accounts,
        name='configure_accounts'),
    url(r'^settings/accounts/error/$', views.configure_accounts_error,
        name='configure_accounts_error'),
    url('^', include('django.contrib.auth.urls')),
]

I can access /user/login/, /user/logout/. When I go to /user/password_reset/, I can enter email, and, after pressing 'Submit' button, an error occurs (shown at picture):

NoReverseMatch at /user/password_reset/
Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name.

Any ideas how to fix this?
Thanks a lot.

Body:
I ran into this issue too. These posts are outdated, so I want to give a revised answer. Essentially the PasswordResetConfirmView has the property of success_url which can be set at urls.py.

So for example...

path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(
    template_name='password-reset-confirm.html', success_url=reverse_lazy(
        'user:password_reset_complete')),
     name="password_reset_confirm"),

The problem is the default behavior of the Password Reset Confirm. Specifically it sets the success_url = reverse_lazy('password_reset_complete'). Since your password_reset_complete view is in your "user" app, it can't find it. The default property is telling it to look at the root urls.py when you need it to be looking at user/urls.py. Overriding the success_url will solve this problem.


问:
Load view component(table) after finish a service call who push an array with info for the table
I'm building a dynamic table to use in my application. I'm using @Input parameters to send info like header and elements for the table.

This is the input for the table component generic.

```<code>@Input()
public listaElementosTabla: any = [];

@Input()
public titulosCabecera = [];

@Input()
public cantidadMaximaRegistros: number;
</code>```

And I call the table component in the next way:

```<code><tabla-component [listaElementosTabla]="arrayElements"
[titulosCabecera]=headElementsArray cantidadMaximaRegistros=5></tabla-component>
</code>```

I have a service to query the information from BD to a specific data and I'm saving that information in the array "arrayElements". I call the service in the onInit page.

```<code>ngOnInit() {
     this.myService.queryInfoInBd().subscribe(
        (data: ObjectDTO[]) => {
            data.forEach((objectDTO: ObjectDTO) => {
                this.arrayElements.push(objectDTO);
            });
        },
        error => {
            console.log(error);
        }
    );
}
</code>```

The problem here is that the table component is loading first that the call of the service, so, when the component is trying to obtain info about arrayElements always is empty.

I know javascript is async, but I don't know how to do to wait until the service finish and the array loads the information and after of that load the table component.

答:
Change your HTML to: </p>

```<code><tabla-component *ngIf="arrayElements" [listaElementosTabla]="arrayElements"
[titulosCabecera]=headElementsArray cantidadMaximaRegistros=5></tabla-component>
</code>```

<p>Like that the table component will be called only if the list is not empty. </p>

Body:
I'm building a dynamic table to use in my application. I'm using @Input parameters to send info like header and elements for the table.

This is the input for the table component generic.

@Input()
public listaElementosTabla: any = [];

@Input()
public titulosCabecera = [];

@Input()
public cantidadMaximaRegistros: number;

And I call the table component in the next way:

<tabla-component [listaElementosTabla]="arrayElements"
[titulosCabecera]=headElementsArray cantidadMaximaRegistros=5></tabla-component>

I have a service to query the information from BD to a specific data and I'm saving that information in the array "arrayElements". I call the service in the onInit page.

ngOnInit() {
     this.myService.queryInfoInBd().subscribe(
        (data: ObjectDTO[]) => {
            data.forEach((objectDTO: ObjectDTO) => {
                this.arrayElements.push(objectDTO);
            });
        },
        error => {
            console.log(error);
        }
    );
}

The problem here is that the table component is loading first that the call of the service, so, when the component is trying to obtain info about arrayElements always is empty.

I know javascript is async, but I don't know how to do to wait until the service finish and the array loads the information and after of that load the table component.

Body:
Change your HTML to:

<tabla-component *ngIf="arrayElements" [listaElementosTabla]="arrayElements"
[titulosCabecera]=headElementsArray cantidadMaximaRegistros=5></tabla-component>

Like that the table component will be called only if the list is not empty.


问:
AKS - incorrect Pod Status
I have an AKS Cluster with two nodepools. Node pool 1 has 3 nodes, and nodepool 2 has 1 node - all Linux VMs. I noticed that after stopping the VMs and then doing kubectl get pods, the Pods status shows "running" though the VMs are not actually running. How is this possible?

This is the command I tried: kubectl get pods -n development -o=wide

The screenshot is given below. Though VMs are not running, the Pod status shows "running". However, trying to access the app using the Public IP of the service resulted in

ERR_CONNECTION_TIMED_OUT

答:
What is actually going is related to the kubelet processes running on the nodes cannot provide their status to the Kubernetes API server. Kubernetes will always assume that your PODs are running when the nodes associated with the POD are offline. The fact that all nodes are offline, will in fact cause your POD to not be running hence not being accessible, causing the ERR_CONNECTION_TIMED_OUT

You can run kubectl get nodes to get the status of the nodes, they should show NotReady. Please check and let me know.
Also, can you please provide the output for kubectl get pods -A

Title: AKS - incorrect Pod Status


问:
Why is this Array is not saving the pushed elements each time the event is triggered?
I am facing a problem: I want the array to save the x value each time the button is clicked.

So, the first time the button is clicked, the console is going to print: [48], the next time [48,48] and the third time [48,48,48]

```<code><button id="me">Click me to print form E to Z</button>

<script type="text/javascript">

      const insertOptions = x=>{
    console.log(x);
  }

  const circleInsertOptions = () => {
    let myArray = [];
    let x = 48;
    myArray.push(48);
    console.log(myArray);
    return myArray;
  };

  document.getElementById('me').addEventListener('click', circleInsertOptions);

</script>
</code>```

答:
The myArray variable is local to the function. Each time the function is called, it is initialized with a new array.

If you want to define the array once then you need to define it once and not every time the function is called (i.e. outside the function).

Body:
I am facing a problem: I want the array to save the x value each time the button is clicked.

So, the first time the button is clicked, the console is going to print: [48], the next time [48,48] and the third time [48,48,48]

<button id="me">Click me to print form E to Z</button>


问:
Using dynamic to find a property
I have a set of messages which I cannot alter their structure, but all of them follow the same property structure after you drill into the first two. For example,

```<code>public class Animal {
    public Dog Doggy { get; set; }
}

public class MixedAnimal {
    public CatDog CatDoggy { get; set; }
}

public class Dog {
    public Name name { get; set; }
    public Age age { get; set; }
}

public class CatDog {
    public Name name { get; set; }
    public Age age { get; set; }
}
</code>```

If I have a structure like this: SomeObj.Item where SomeObj is some object and Item is of type object which can hold either an Animal or MixedAnimal. How would I get to the value of either Dog or CatDog using the keyword dynamic?

I can get the top level object using SomeObj.Item as dynamic, and then do:

(SomeObj.Item as dynamic).Doggy.Name

but what I want is to just get the name without knowing the type of Item.

(SomeObj.Item as dynamic).(Something as dynamic).Name

Is this possible?

答:
Using reflection is quite easy to resolve this problem. Something like this (general idea):

object animal = new Animal { Doggy = new Dog { age = 10, name = "Good boy" }};
var members = animal.GetType().GetMembers();

foreach (PropertyInfo member in members.Where(x => x is PropertyInfo))
{
    if (member.PropertyType.Name == "Dog" || member.PropertyType.Name == "CatDog")
    {
        var propertyValue = member.GetValue(animal);
        var propertyType = propertyValue.GetType();
        var nameMember = propertyType.GetProperty("name");
        var ageMember = propertyType.GetProperty("age");

        var nameValue = nameMember.GetValue(propertyValue);
        var ageValue = ageMember.GetValue(propertyValue);

        Console.WriteLine($"Name: {nameValue}, Age: {ageValue}");
    }
}
```

Everything you need to do additionally is providing list of type names which you want to process (like "Dog" or "CatDog" here).

Title: Using dynamic to find a property

Body:
I have a set of messages which I cannot alter their structure, but all of them follow the same property structure after you drill into the first two. For example,

public class Animal {
    public Dog Doggy { get; set; }
}

public class MixedAnimal {
    public CatDog CatDoggy { get; set; }
}

public class Dog {
    public Name name { get; set; }
    public Age age { get; set; }
}

public class CatDog {
    public Name name { get; set; }
    public Age age { get; set; }
}

If I have a structure like this: SomeObj.Item where SomeObj is some object and Item is of type object which can hold either an Animal or MixedAnimal. How would I get to the value of either Dog or CatDog using the keyword dynamic?

I can get the top level object using SomeObj.Item as dynamic, and then do:

(SomeObj.Item as dynamic).Doggy.Name

but what I want is to just get the name without knowing the type of Item.

(SomeObj.Item as dynamic).(Something as dynamic).Name

Is this possible?

Body:
Using reflection is quite easy to resolve this problem. Something like this (general idea):

object animal = new Animal { Doggy = new Dog { age = 10, name = "Good boy" }};
var members = animal.GetType().GetMembers();

foreach (PropertyInfo member in members.Where(x => x is PropertyInfo))
{
    if (member.PropertyType.Name == "Dog" || member.PropertyType.Name == "CatDog")
    {
        var propertyValue = member.GetValue(animal);
        var propertyType = propertyValue.GetType();
        var nameMember = propertyType.GetProperty("name");
        var ageMember = propertyType.GetProperty("age");

        var nameValue = nameMember.GetValue(propertyValue);
        var ageValue = ageMember.GetValue(propertyValue);

        Console.WriteLine($"Name: {nameValue}, Age: {ageValue}");
    }
}

Everything you need to do additionally is providing list of type names which you want to process (like "Dog" or "CatDog" here).


问:
Using LIKE in SQL with multiple search terms
I'm doing a basic SQL course and learning the basics currently and having issue with filtering:

Task: list all the rows from TableName where the columnName field content does not contain any of the following words: 'stack' or 'overflow' or 'exampleword'.

```<code>SELECT columnName
FROM TableName
WHERE columnName NOT LIKE '%stack%'
</code>```

-> I get it to work properly with just a single value, but when I try adding more words as values it no longer works ->

```<code>SELECT columnName
FROM TableName
WHERE columnName NOT LIKE '%stack%' OR columnName NOT LIKE '%overflow%'
</code>```

What's the correct syntax for having multiple search terms?

Apparently I'm also not supposed to be using CONTAINS here or it would've been too easy.

答:
You want AND, not OR:

```<code>SELECT columnName
FROM TableName
WHERE columnName NOT LIKE '%stack%' AND columnName NOT LIKE '%overflow%'
</code>```

You can expand the WHERE clause with more conditions as needed.

Side note: if you know in advance in which sequence the words appear in the string, you can also do:

```<code>SELECT columnName
FROM TableName
WHERE columnName NOT LIKE '%stack%overflow%'
</code>```

Body:
I'm doing a basic SQL course and learning the basics currently and having issue with filtering:

Task: list all the rows from TableName where the columnName field content does not contain any of the following words: 'stack' or 'overflow' or 'exampleword'.

SELECT columnName
FROM TableName
WHERE columnName NOT LIKE '%stack%'

-> I get it to work properly with just a single value, but when I try adding more words as values it no longer works ->

SELECT columnName
FROM TableName
WHERE columnName NOT LIKE '%stack%' OR columnName NOT LIKE '%overflow%'

What's the correct syntax for having multiple search terms?

Apparently I'm also not supposed to be using CONTAINS here or it would've been too easy.

Body:
You want AND, not OR:

SELECT columnName
FROM TableName
WHERE columnName NOT LIKE '%stack%' AND columnName NOT LIKE '%overflow%'

You can expand the WHERE clause with more conditions as needed.

Side note: if you know in advance in which sequence the words appear in the string, you can also do:

SELECT columnName
FROM TableName
WHERE columnName NOT LIKE '%stack%overflow%'


问:
Control access to files based on DB values with PHP/Apache

What i want

I'm making a system where, when a user uploads an image it goes to the folder images, where there is two copies of the image, a thumb and a bigger one.

Now, when a user uploads an image it's done alongside insertion of a row in a MySQL database, where the image gets an id, and the row holds a value that determines if the images is available to the public or not (1 for only thumb available, 2 for both) along with the owner(admin) of the image.

What i wan't to do is, if a user tries to reach the image by going to the image's URL, and the value in the database says that it should not be publicly available, and the session of that user is not the owner of the image, (admin not logged in) it should either say image not found or access denied.

What i imagine

If it could be done with php i imagine something like this:

```<code>//User tries to go to URL "images/IMAGE-ID_thumb.jpg"
if($img['access'] >= 1 || $_SESSION['admin_ID'] == $img['owner_ID']) {
  //Show image thumb
}
else {
  //Access denied
}
</code>```

I could maybe hide the images in a .htaccess protected folder, make a imgae_get.php that accepts URL variables, sees if the image is available, and loads the image if so. I just want to avoid having to de/re-compile the image and other server power consuming processes.

My question is, can i control the image like this? Is there a way to make a php script appear as an image it loads internally?
Or is there maybe some other/better way than through PHP? (Apache maybe?) Any suggestions is much appreciated.

答:
```<code>//get_image.php

//Do session/mysql checks as outlined in your code above.

header("Content-Disposition: filename=$imagename.$filetype");
header("Content-type: $mimetype");
readfile(PROTECTED_IMAGE_FOLDER . "$imagename.$filetype");
</code>```

Body:
What i want

I'm making a system where, when a user uploads an image it goes to the folder images, where there is two copies of the image, a thumb and a bigger one.

Now, when a user uploads an image it's done alongside insertion of a row in a MySQL database, where the image gets an id, and the row holds a value that determines if the images is available to the public or not (1 for only thumb available, 2 for both) along with the owner(admin) of the image.

What i wan't to do is, if a user tries to reach the image by going to the image's URL, and the value in the database says that it should not be publicly available, and the session of that user is not the owner of the image, (admin not logged in) it should either say image not found or access denied.

What i imagine

If it could be done with php i imagine something like this:

//User tries to go to URL "images/IMAGE-ID_thumb.jpg"
if($img['access'] >= 1 || $_SESSION['admin_ID'] == $img['owner_ID']) {
  //Show image thumb
}
else {
  //Access denied
}

I could maybe hide the images in a .htaccess protected folder, make a imgae_get.php that accepts URL variables, sees if the image is available, and loads the image if so. I just want to avoid having to de/re-compile the image and other server power consuming processes.

My question is, can i control the image like this? Is there a way to make a php script appear as an image it loads internally?
Or is there maybe some other/better way than through PHP? (Apache maybe?) Any suggestions is much appreciated.


答:
after couple times of try, i am able to create a dataframe that contains the flattened information of the matrix. and create a tempview, so that access from python as a dataframe

in scala

```<code>// covarianceMatrix (in scala)

val c = covarianceMatrix.toArray.toSeq
val covarianceMatrix_df = c.toDF("number")
covarianceMatrix_df.createOrReplaceTempView("covarianceMatrix_df")
</code>```

in python

```<code>covarianceMatrix_df=spark.sql('''SELECT * FROM covarianceMatrix_df  ''')
covarianceMatrix_pd = covarianceMatrix_df.toPandas()
nrows = np.sqrt(len(covarianceMatrix_pd))
covarianceMatrix_pd = covarianceMatrix_pd.to_numpy().reshape((int(nrows),int(nrows)))
covarianceMatrix_pd
</code>```

Title: convert breeze.linalg.DenseMatrix[Double] to a dataframe in Scala

Body:
i have a breeze.linalg.DenseMatrix[Double] as follow, i want to convert it to a dataframe

breeze.linalg.DenseMatrix[Double] =
0.009748169568491553   3.04248345416453E-4    -0.0018493112842201912  8.200326863261204E-4
3.0424834541645305E-4  0.00873118653317929    6.352723194418622E-4    1.84118791655692E-5
-0.001849311284220191  6.35272319441862E-4    0.008553284420541575    -6.407982513791382E-4
8.200326863261203E-4   1.8411879165568983E-5  -6.407982513791378E-4   0.008413484758510377

is there any way i can do that?

Body:
after couple times of try, i am able to create a dataframe that contains the flattened information of the matrix. and create a tempview, so that access from python as a dataframe

in scala

// covarianceMatrix (in scala)

val c = covarianceMatrix.toArray.toSeq
val covarianceMatrix_df = c.toDF("number")
covarianceMatrix_df.createOrReplaceTempView("covarianceMatrix_df")

in python

covarianceMatrix_df=spark.sql('''SELECT * FROM covarianceMatrix_df  ''')
covarianceMatrix_pd = covarianceMatrix_df.toPandas()
nrows = np.sqrt(len(covarianceMatrix_pd))
covarianceMatrix_pd = covarianceMatrix_pd.to_numpy().reshape((int(nrows),int(nrows)))
covarianceMatrix_pd


问:
Change, reset and increment time in python
I need to increment time in python and if the value of the range in loop increments, I need to set time to the original value.

example

```<code>start_time = '0230'
start_time = datetime.strptime(start_time, '%H%M')

difference_time = '0030'
difference_time = datetime.strptime(differece_time, '%H%M')

differnce_delta = timedelta(
    hours=difference.hour, minutes=difference.minute)

listvar = [5, 3, 4]

for i in range(3):
    x = listvar[i]
    for loop in range(x)
        print(f'{start_time.hour}:{start_time.minute}')
        start_time += difference_delta
</code>```

Now if the the value of i becomes 2, I want start_time to get back to original value i.e 0230.

答:
You can use another variable as a place holder for the original value.

```<code>    start_time = '0230'
    start_time_holder = '0230'
    start_time = datetime.strptime(start_time, '%H%M')

    difference_time = '0030'
    difference_time = datetime.strptime(differece_time, '%H%M')

    differnce_delta = timedelta(
        hours=difference.hour, minutes=difference.minute)

    listvar = [5, 3, 4]

    for i in range(5):
        start_time = start_time_holder
        x = listvar[i]
        for loop in range(x):
            print(f'{start_time.hour}:{start_time.minute}')
            start_time += difference_delta
</code>```

FYI: you would get a index out of range error at x = listvar[i] because the range is 5 but the list length is only 3

Body:
I need to increment time in python and if the value of the range in loop increments, I need to set time to the original value.

example

start_time = '0230'
start_time = datetime.strptime(start_time, '%H%M')

difference_time = '0030'
difference_time = datetime.strptime(differece_time, '%H%M')

differnce_delta = timedelta(
    hours=difference.hour, minutes=difference.minute)

listvar = [5, 3, 4]

for i in range(3):
    x = listvar[i]
    for loop in range(x)
        print(f'{start_time.hour}:{start_time.minute}')
        start_time += difference_delta

Now if the the value of i becomes 2, I want start_time to get back to original value i.e 0230.

Body:
You can use another variable as a place holder for the original value.

    start_time = '0230'
    start_time_holder = '0230'
    start_time = datetime.strptime(start_time, '%H%M')

    difference_time = '0030'
    difference_time = datetime.strptime(differece_time, '%H%M')

    differnce_delta = timedelta(
        hours=difference.hour, minutes=difference.minute)

    listvar = [5, 3, 4]

    for i in range(5):
        start_time = start_time_holder
        x = listvar[i]
        for loop in range(x):
            print(f'{start_time.hour}:{start_time.minute}')
            start_time += difference_delta

FYI: you would get a index out of range error at x = listvar[i] because the range is 5 but the list length is only 3


问:
RStudio "Run Document" not producing an html file
I've been writing a flexdashboard script in RMarkdown, but the "run document" button does not produce an actual html file, just a preview. The gear box to the right of the "run document" button does not give me the option to produce an html file. It simply says preview in window, preview in viewer pane, or no preview.

The script looks as follows

```<code>---
title: "dashboard title"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: scroll
    theme: cerulean
runtime: shiny
---
</code>```

Any help on what is going on would be greatly appreciated!

答:
You can try rmarkdown::render_site() as in this example or:

knitr::kable()

Also you could try htmltools package

Body:
I've been writing a flexdashboard script in RMarkdown, but the "run document" button does not produce an actual html file, just a preview. The gear box to the right of the "run document" button does not give me the option to produce an html file. It simply says preview in window, preview in viewer pane, or no preview.

The script looks as follows

---
title: "dashboard title"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: scroll
    theme: cerulean
runtime: shiny
---

Any help on what is going on would be greatly appreciated!