问:
Open Navigation Drawer from Button Click within Fragment (Kotlin)
I have created a custom button in a Fragment and I am trying to open the Navigation Drawer in the Activity when it is clicked.

The Navigation Drawer still opens ok when you swipe across, but the app just crashes when I click the button.

I guess this is because I am trying to access from the Fragment, but I am at a loss..

Fragment

```<code>override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val binding: SiteFragmentBinding = DataBindingUtil.inflate(
        inflater, R.layout.site_fragment, container, false
    )

    binding.apply {
        siteOverflowOptionsMenuButton.setOnClickListener{
            showPopUp(it)
        }

        siteDrawerMenuButton.setOnClickListener{
            drawer_layout.openDrawer(nav_view)  // this crashes (also crashes with Gravity.LEFT or similar)
        }

    }

    return binding.root
}
</code>```

activity.xml

```<code>?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/siteNavHostFragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/site_navigation" />

    </LinearLayout>

    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/nav_view"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_menu"

        />

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

site_fragment.xml

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

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/siteMainConstraintLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        android:background="@color/white"
        tools:context=".site.SiteActivity"

        >

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/siteLogoConstraintLayout"
            android:layout_width="wrap_content"
            android:layout_height="50dp"

            android:layout_marginTop="16dp"
            android:foregroundGravity="center_horizontal"

            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                android:id="@+id/siteLogoImage"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:src="@mipmap/ic_launcher_logo"

                app:layout_constraintEnd_toStartOf="@id/siteTopHeadingText"
                app:layout_constraintHorizontal_chainStyle="packed"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/siteTopHeadingText"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"

                android:gravity="center_vertical"
                android:paddingStart="12dp"
                android:paddingLeft="12dp"

                android:text="@string/site_top_heading"
                android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                android:textSize="18sp"
                android:textStyle="bold|italic"

                app:layout_constraintEnd_toEndOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>

        <ImageView
            android:id="@+id/siteOverflowOptionsMenuButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            app:srcCompat="@drawable/ic_menu_vertical_dots"
            android:tint="@color/locatorsPurpleCompany"
            app:layout_constraintBottom_toBottomOf="@+id/siteLogoConstraintLayout"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@+id/siteLogoConstraintLayout" />

        <ImageView
            android:id="@+id/siteDrawerMenuButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            app:srcCompat="@drawable/ic_menu_drawer"
            android:tint="@color/locatorsPurpleCompany"
            app:layout_constraintBottom_toBottomOf="@+id/siteLogoConstraintLayout"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/siteLogoConstraintLayout" />

        <androidx.cardview.widget.CardView
            android:id="@+id/siteFilterOptionsCardView"
            android:layout_width="match_parent"

            android:layout_height="60dp"

            android:layout_marginStart="8dp"

            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            app:cardBackgroundColor="@color/locatorsGrey"
            app:cardCornerRadius="18dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/siteLogoConstraintLayout">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/siteFilterOptionsConstraintLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:id="@+id/siteFilterIconImageView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    app:srcCompat="@drawable/ic_filter"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <TextView
                    android:id="@+id/siteCurrentFilterTextView"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="4dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"

                    android:layout_marginBottom="4dp"

                    android:background="@color/white"
                    android:drawableLeft="@drawable/ic_search"
                    android:drawablePadding="8dp"
                    android:ellipsize="end"
                    android:gravity="center_vertical"
                    android:lines="1"
                    android:paddingLeft="12dp"
                    android:paddingRight="12dp"
                    android:text="Search..."
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toStartOf="@+id/siteClearIconImageView"
                    app:layout_constraintStart_toEndOf="@+id/siteFilterIconImageView"
                    app:layout_constraintTop_toTopOf="parent" />

                <ImageView
                    android:id="@+id/siteClearIconImageView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    app:srcCompat="@drawable/ic_clear"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

            </androidx.constraintlayout.widget.ConstraintLayout>
        </androidx.cardview.widget.CardView>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/siteRecyclerView"
            android:layout_width="match_parent"

            android:layout_height="0dp"

            android:layout_marginBottom="4dp"
            app:layout_constraintBottom_toBottomOf="parent"

            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/siteFilterOptionsCardView"
            app:layout_constraintVertical_bias="0.0"
            tools:listitem="@layout/site_list_item" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/floatingActionButtonAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="32dp"
            android:layout_marginRight="32dp"
            android:layout_marginBottom="24dp"
            android:backgroundTint="@color/locatorsPurpleCompany"

            android:clickable="true"
            android:elevation="28dp"
            app:borderWidth="0dp"
            app:fabSize="normal"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/siteRecyclerView"

            app:srcCompat="@drawable/ic_add_white" />

    </androidx.constraintlayout.widget.ConstraintLayout>

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

<p><strong>drawer_menu.xml</strong></p>

```<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    >

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_first_fragment"
            android:icon="@drawable/ic_exit"
            android:title="First" />
        <item
            android:id="@+id/nav_second_fragment"
            android:icon="@drawable/ic_priority"
            android:title="Second" />
        <item
            android:id="@+id/nav_third_fragment"
            android:icon="@drawable/ic_filter"
            android:title="Third" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_contact"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_location"
                android:title="Send" />
        </menu>

    </item>

    <item android:title="Sub items">
        <menu>
            <group android:checkableBehavior="single">
                <item
                    android:icon="@drawable/ic_star_full"
                    android:title="Sub item 1" />
                <item
                    android:icon="@drawable/ic_location"
                    android:title="Sub item 2" />
            </group>
        </menu>
    </item>
</menu>
```

<p><strong>Crash Log</strong></p>

```2020-02-17 12:31:56.719 23527-23527/com.locators.acorn E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.locators.acorn, PID: 23527
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.drawerlayout.widget.DrawerLayout.openDrawer(int)' on a null object reference
    at com.locators.acorn.site.SiteFragment$onCreateView$$inlined$apply$lambda$2.onClick(SiteFragment.kt:46)
    at android.view.View.performClick(View.java:7125)
    at android.view.View.performClickInternal(View.java:7102)
    at android.view.View.access$3500(View.java:801)
    at android.view.View$PerformClick.run(View.java:27336)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
```

答:
In your implementation, you don't do that as drawer_layout is not accessible from fragment. Hence you got NullPointerException. Try to follow below steps:

Step - 1: Create a function in your Activity to open-close Navigation Drawer

```<code>fun openCloseNavigationDrawer(view: View) {
    if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
        drawer_layout.closeDrawer(GravityCompat.START)
    } else {
        drawer_layout.openDrawer(GravityCompat.START)
    }
}
</code>```

Step - 2: Invoke openCloseNavigationDrawer from your fragment

Option - 1: Remove OnClickListener from your fragment code and add onClick property through layout and pointed out the function openCloseNavigationDrawer on siteDrawerMenuButton.

```<code>    <ImageView
        android:id="@+id/siteDrawerMenuButton"
        android:onClick="openCloseNavigationDrawer"
        ... />
</code>```

Option - 2: You can access the function openCloseNavigationDrawer through code by casting your Activity like below:

```<code>    siteDrawerMenuButton.setOnClickListener{ v ->
        (activity as YOUR_ACTIVITY).openCloseNavigationDrawer(v)
    }
</code>```

Body:
I have created a custom button in a Fragment and I am trying to open the Navigation Drawer in the Activity when it is clicked.

The Navigation Drawer still opens ok when you swipe across, but the app just crashes when I click the button.

I guess this is because I am trying to access from the Fragment, but I am at a loss..

Fragment

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val binding: SiteFragmentBinding = DataBindingUtil.inflate(
        inflater, R.layout.site_fragment, container, false
    )

    binding.apply {
        siteOverflowOptionsMenuButton.setOnClickListener{
            showPopUp(it)
        }

        siteDrawerMenuButton.setOnClickListener{
            drawer_layout.openDrawer(nav_view)  // this crashes (also crashes with Gravity.LEFT or similar)
        }

    }

    return binding.root
}

activity.xml

?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/siteNavHostFragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/site_navigation" />

    </LinearLayout>

    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/nav_view"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_menu"

        />

</androidx.drawerlayout.widget.DrawerLayout>

site_fragment.xml

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

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/siteMainConstraintLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        android:background="@color/white"
        tools:context=".site.SiteActivity"

        >

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/siteLogoConstraintLayout"
            android:layout_width="wrap_content"
            android:layout_height="50dp"

            android:layout_marginTop="16dp"
            android:foregroundGravity="center_horizontal"

            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                android:id="@+id/siteLogoImage"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:src="@mipmap/ic_launcher_logo"

                app:layout_constraintEnd_toStartOf="@id/siteTopHeadingText"
                app:layout_constraintHorizontal_chainStyle="packed"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/siteTopHeadingText"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"

                android:gravity="center_vertical"
                android:paddingStart="12dp"
                android:paddingLeft="12dp"

                android:text="@string/site_top_heading"
                android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                android:textSize="18sp"
                android:textStyle="bold|italic"

                app:layout_constraintEnd_toEndOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>

        <ImageView
            android:id="@+id/siteOverflowOptionsMenuButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            app:srcCompat="@drawable/ic_menu_vertical_dots"
            android:tint="@color/locatorsPurpleCompany"
            app:layout_constraintBottom_toBottomOf="@+id/siteLogoConstraintLayout"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@+id/siteLogoConstraintLayout" />

        <ImageView
            android:id="@+id/siteDrawerMenuButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            app:srcCompat="@drawable/ic_menu_drawer"
            android:tint="@color/locatorsPurpleCompany"
            app:layout_constraintBottom_toBottomOf="@+id/siteLogoConstraintLayout"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/siteLogoConstraintLayout" />

        <androidx.cardview.widget.CardView
            android:id="@+id/siteFilterOptionsCardView"
            android:layout_width="match_parent"

            android:layout_height="60dp"

            android:layout_marginStart="8dp"

            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            app:cardBackgroundColor="@color/locatorsGrey"
            app:cardCornerRadius="18dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/siteLogoConstraintLayout">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/siteFilterOptionsConstraintLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:id="@+id/siteFilterIconImageView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    app:srcCompat="@drawable/ic_filter"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <TextView
                    android:id="@+id/siteCurrentFilterTextView"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="4dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"

                    android:layout_marginBottom="4dp"

                    android:background="@color/white"
                    android:drawableLeft="@drawable/ic_search"
                    android:drawablePadding="8dp"
                    android:ellipsize="end"
                    android:gravity="center_vertical"
                    android:lines="1"
                    android:paddingLeft="12dp"
                    android:paddingRight="12dp"
                    android:text="Search..."
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toStartOf="@+id/siteClearIconImageView"
                    app:layout_constraintStart_toEndOf="@+id/siteFilterIconImageView"
                    app:layout_constraintTop_toTopOf="parent" />

                <ImageView
                    android:id="@+id/siteClearIconImageView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    app:srcCompat="@drawable/ic_clear"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

            </androidx.constraintlayout.widget.ConstraintLayout>
        </androidx.cardview.widget.CardView>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/siteRecyclerView"
            android:layout_width="match_parent"

            android:layout_height="0dp"

            android:layout_marginBottom="4dp"
            app:layout_constraintBottom_toBottomOf="parent"

            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/siteFilterOptionsCardView"
            app:layout_constraintVertical_bias="0.0"
            tools:listitem="@layout/site_list_item" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/floatingActionButtonAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="32dp"
            android:layout_marginRight="32dp"
            android:layout_marginBottom="24dp"
            android:backgroundTint="@color/locatorsPurpleCompany"

            android:clickable="true"
            android:elevation="28dp"
            app:borderWidth="0dp"
            app:fabSize="normal"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/siteRecyclerView"

            app:srcCompat="@drawable/ic_add_white" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

drawer_menu.xml

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

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_first_fragment"
            android:icon="@drawable/ic_exit"
            android:title="First" />
        <item
            android:id="@+id/nav_second_fragment"
            android:icon="@drawable/ic_priority"
            android:title="Second" />
        <item
            android:id="@+id/nav_third_fragment"
            android:icon="@drawable/ic_filter"
            android:title="Third" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_contact"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_location"
                android:title="Send" />
        </menu>

    </item>

    <item android:title="Sub items">
        <menu>
            <group android:checkableBehavior="single">
                <item
                    android:icon="@drawable/ic_star_full"
                    android:title="Sub item 1" />
                <item
                    android:icon="@drawable/ic_location"
                    android:title="Sub item 2" />
            </group>
        </menu>
    </item>
</menu>

Crash Log

2020-02-17 12:31:56.719 23527-23527/com.locators.acorn E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.locators.acorn, PID: 23527
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.drawerlayout.widget.DrawerLayout.openDrawer(int)' on a null object reference
    at com.locators.acorn.site.SiteFragment$onCreateView$$inlined$apply$lambda$2.onClick(SiteFragment.kt:46)
    at android.view.View.performClick(View.java:7125)
    at android.view.View.performClickInternal(View.java:7102)
    at android.view.View.access$3500(View.java:801)
    at android.view.View$PerformClick.run(View.java:27336)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Body:
In your implementation, you don't do that as drawer_layout is not accessible from fragment. Hence you got NullPointerException. Try to follow below steps:

Step - 1: Create a function in your Activity to open-close Navigation Drawer

fun openCloseNavigationDrawer(view: View) {
    if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
        drawer_layout.closeDrawer(GravityCompat.START)
    } else {
        drawer_layout.openDrawer(GravityCompat.START)
    }
}

Step - 2: Invoke openCloseNavigationDrawer from your fragment

Option - 1: Remove OnClickListener from your fragment code and add onClick property through layout and pointed out the function openCloseNavigationDrawer on siteDrawerMenuButton.

    <ImageView
        android:id="@+id/siteDrawerMenuButton"
        android:onClick="openCloseNavigationDrawer"
        ... />

Option - 2: You can access the function openCloseNavigationDrawer through code by casting your Activity like below:

    siteDrawerMenuButton.setOnClickListener{ v ->
        (activity as YOUR_ACTIVITY).openCloseNavigationDrawer(v)
    }


来源: stackexchange

问:
Xamarin IOS get iBeacon Advertisement data
I'm trying to read the information written in the advertisement of an iBeacon and I'm always having null values with IOS.
I've already developed an Android app that works correctly, in the OnScanResult() I get the ScanRecord with all the info I need.

The same is not working on IOS, has anyone found a way to read this data?

Thanks a lot,
Gianluca

答:
Unfortunately iOS blocks accessing the raw Bluetooth packet data of any BLE advertisement that matches the iBeacon format.  The operating system actually truncates the data field for the packet when it matches iBeacon.

This appears to be an Intentional design by Apple , perhaps intended to prevent reading any unknown iBeacon Proximity UUID.  Apple's native APIs require you to know the Proximity UUiD up front.

This is a little silly, because as you have seen, Android has no such restriction.  But you can't argue with Apple!

More info in my blog post here: http://www.davidgyoungtech.com/2013/10/21/corebluetooth-doesnt-let-you-see-ibeacons

ContentLicense: CC BY-SA 4.0


问:
How to sort Firestore RecyclerView Items with a value that is not in the "Query-Collection"? (Social Leaderboard)
I have a RecyclerView adapter which should display all the users friends with their score, so basically a social leaderboard. With the adapter I get the uids from the friends and then make a query in the onBindViewHolder to get the avatar ids and usernames of each friend, and also his current score.

This works all fine but now I want to sort the RecyclerView after the score of the players. Since I have only the uid of each friend in the collection, not the score, I can't use this code:

```<code>Query query = userRef.orderBy("uid", Query.Direction.ASCENDING);
</code>```

Is there a way to sort the RecyclerView after the score of the players, without having the score in the "RecyclerView collection"? So without putting the score in the same collection where the uid is, which would lead to enormous reads and writes. I know that there is the Comparator operator but I don't know how to use this in this context.

Here is my adapter where I want the items to be sorted by the value pointsInt

```<code>public class LeaderboardAdapter extends FirestoreRecyclerAdapter<Users, LeaderboardAdapter.UserHolder> {
    private OnItemClickListener listener;

    private String avatar_id_player_2, mUid, mCurrentUser;
    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();

    public LeaderboardAdapter(@NonNull FirestoreRecyclerOptions<Users> options) {
        super(options);

    }

    @Override
    protected void onBindViewHolder(@NonNull UserHolder holder, int position, @NonNull Users model) {

        holder.textViewUsername.setText(model.getUsername());

        mCurrentUser = currentUser.getUid();

        mUid = model.getUid();

        db.collection("User").document(mUid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document != null) {

                        String username = document.getString("username");
                        avatar_id_player_2 = document.getString("avatar_id");

                        holder.textViewUsername.setText(username);
                        Picasso.get().load(avatar_id_player_2).placeholder(R.mipmap.ic_launcher).into(holder.circleImageView);

                        db.collection("User").document(mUid).collection("Points").document("Points")
                                .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                if (task.isSuccessful()) {
                                    DocumentSnapshot document = task.getResult();
                                    if (document != null) {

                                        Integer pointsInt = document.getLong("points").intValue();
                                        holder.textViewScore.setText("" + pointsInt);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    @NonNull
    @Override
    public UserHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_leaderboard, parent, false);
        return new UserHolder(view);
    }

    class UserHolder extends RecyclerView.ViewHolder {

       public TextView textViewUsername, textViewScore;
        CircleImageView circleImageView;

        public UserHolder(@NonNull View itemView) {
            super(itemView);

            textViewUsername = itemView.findViewById(R.id.leaderboard_username);
            circleImageView = itemView.findViewById(R.id.leaderboard_avatar);
            textViewScore = itemView.findViewById(R.id.leaderboard_score);

        }
    }

...
}
</code>```

Here is how I structured my database. Here I get the value of the friends (currently this user has one friend) and then make a query as explained earlier to get the score/point value of this player:

And this is the collection from where I get the value that I then wanted to sort in the RecyclerView:

Here you can see how my RecyclerView looks right now. Here the current player has 2 friends, but the highest score is not above the lowest since it is ordered by the lid value of the players:

答:
You need to convert your data into List of Object by creating a Model class after doing that you can sort List<Object> using

```<code>Collections.sort(userPointList, (item1, item2) -> {
    int firstUser = item1.getPoint() ? 0 : 1;
    int secondUser = item2.getPoint() ? 0 : 1;

    return first - second; // Ascending
}); // using JAVA 1_8
</code>```

Ask if you need more help :)

Hope this will help!

Body:
I have a RecyclerView adapter which should display all the users friends with their score, so basically a social leaderboard. With the adapter I get the uids from the friends and then make a query in the onBindViewHolder to get the avatar ids and usernames of each friend, and also his current score.

This works all fine but now I want to sort the RecyclerView after the score of the players. Since I have only the uid of each friend in the collection, not the score, I can't use this code:

Query query = userRef.orderBy("uid", Query.Direction.ASCENDING);

Is there a way to sort the RecyclerView after the score of the players, without having the score in the "RecyclerView collection"? So without putting the score in the same collection where the uid is, which would lead to enormous reads and writes. I know that there is the Comparator operator but I don't know how to use this in this context.

Here is my adapter where I want the items to be sorted by the value pointsInt

public class LeaderboardAdapter extends FirestoreRecyclerAdapter<Users, LeaderboardAdapter.UserHolder> {
    private OnItemClickListener listener;

    private String avatar_id_player_2, mUid, mCurrentUser;
    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();

    public LeaderboardAdapter(@NonNull FirestoreRecyclerOptions<Users> options) {
        super(options);

    }

    @Override
    protected void onBindViewHolder(@NonNull UserHolder holder, int position, @NonNull Users model) {

        holder.textViewUsername.setText(model.getUsername());

        mCurrentUser = currentUser.getUid();

        mUid = model.getUid();

        db.collection("User").document(mUid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document != null) {

                        String username = document.getString("username");
                        avatar_id_player_2 = document.getString("avatar_id");

                        holder.textViewUsername.setText(username);
                        Picasso.get().load(avatar_id_player_2).placeholder(R.mipmap.ic_launcher).into(holder.circleImageView);

                        db.collection("User").document(mUid).collection("Points").document("Points")
                                .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                if (task.isSuccessful()) {
                                    DocumentSnapshot document = task.getResult();
                                    if (document != null) {

                                        Integer pointsInt = document.getLong("points").intValue();
                                        holder.textViewScore.setText("" + pointsInt);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    @NonNull
    @Override
    public UserHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_leaderboard, parent, false);
        return new UserHolder(view);
    }

    class UserHolder extends RecyclerView.ViewHolder {

       public TextView textViewUsername, textViewScore;
        CircleImageView circleImageView;

        public UserHolder(@NonNull View itemView) {
            super(itemView);

            textViewUsername = itemView.findViewById(R.id.leaderboard_username);
            circleImageView = itemView.findViewById(R.id.leaderboard_avatar);
            textViewScore = itemView.findViewById(R.id.leaderboard_score);

        }
    }

...
}

Here is how I structured my database. Here I get the value of the friends (currently this user has one friend) and then make a query as explained earlier to get the score/point value of this player:

And this is the collection from where I get the value that I then wanted to sort in the RecyclerView:

Here you can see how my RecyclerView looks right now. Here the current player has 2 friends, but the highest score is not above the lowest since it is ordered by the lid value of the players:

Body:
You need to convert your data into List of Object by creating a Model class after doing that you can sort List<Object> using

Collections.sort(userPointList, (item1, item2) -> {
    int firstUser = item1.getPoint() ? 0 : 1;
    int secondUser = item2.getPoint() ? 0 : 1;

    return first - second; // Ascending
}); // using JAVA 1_8

Ask if you need more help :)

Hope this will help!


问:
web.py - WalkerError: ('unexpected node type', 339)
I am constructing a simple HTML template using web.py, but the system keeps throwing an error every time I try to run the basic app. I'm not sure how to diagnose. The full traceback is below. Anybody out there have ideas on ways to diagnose?

Somebody asked a similar question at this link, but it didn't get answered: Inheritance in web.py?

Source I'm mimicking for my files: http://learnpythonthehardway.org/book/ex50.html

HTML FILE:

```<code><html>
    <head>
        <title>Gothons Of Planet Percal #25</title>
    </head>
<body>

$if greeting:
    I just wanted to say <em style="color: green; font-size: 2em;">$greeting</em>.
$else:
    <em>Hello</em>, world!

</body>
</code>```

app.py:

```<code>import web

urls = (
  '/', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
    def GET(self):
        greeting = "Hello World"
        return render.index(greeting = greeting)

if __name__ == "__main__":
    app.run()
</code>```

TRACEBACK

```<code>Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/web/wsgiserver/__init__.py", line 1245, in     communicate
    req.respond()
  File "/Library/Python/2.7/site-packages/web/wsgiserver/__init__.py", line 775, in respond
self.server.gateway(self).respond()
  File "/Library/Python/2.7/site-packages/web/wsgiserver/__init__.py", line 2018, in respond
    response = self.req.server.wsgi_app(self.env, self.start_response)
  File "/Library/Python/2.7/site-packages/web/httpserver.py", line 268, in __call__
    return self.app(environ, xstart_response)
  File "/Library/Python/2.7/site-packages/web/httpserver.py", line 236, in __call__
    return self.app(environ, start_response)
  File "/Library/Python/2.7/site-packages/web/application.py", line 276, in wsgi
    result = self.handle_with_processors()
  File "/Library/Python/2.7/site-packages/web/application.py", line 246, in     handle_with_processors
    return process(self.processors)
  File "/Library/Python/2.7/site-packages/web/application.py", line 243, in process
    raise self.internalerror()
  File "/Library/Python/2.7/site-packages/web/application.py", line 467, in internalerror
    return debugerror.debugerror()
  File "/Library/Python/2.7/site-packages/web/debugerror.py", line 305, in debugerror
    return web._InternalError(djangoerror())
  File "/Library/Python/2.7/site-packages/web/debugerror.py", line 290, in djangoerror
    djangoerror_r = Template(djangoerror_t, filename=__file__, filter=websafe)
  File "/Library/Python/2.7/site-packages/web/template.py", line 844, in __init__
    code = self.compile_template(text, filename)
  File "/Library/Python/2.7/site-packages/web/template.py", line 922, in compile_template
    ast = compiler.parse(code)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/compiler/transformer.py", line 51, in parse
    return Transformer().parsesuite(buf)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/compiler/transformer.py", line 128, in parsesuite
    return self.transform(parser.suite(text))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/compiler/transformer.py", line 124, in transform
    return self.compile_node(tree)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/compiler/transformer.py", line 167, in compile_node
    raise WalkerError, ('unexpected node type', n)
WalkerError: ('unexpected node type', 339)
</code>```

答:
First of all you should add $def with(greeting) in your html page.

html file:

```<code>$def with(greeting)
<html>
    ...
</html>
    ...
</code>```

then change:

app.py:

```<code>...
return render.index(greeting)
...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am constructing a simple HTML template using web.py, but the system keeps throwing an error every time I try to run the basic app. I'm not sure how to diagnose. The full traceback is below. Anybody out there have ideas on ways to diagnose?

Somebody asked a similar question at this link, but it didn't get answered: Inheritance in web.py?

Source I'm mimicking for my files: http://learnpythonthehardway.org/book/ex50.html

HTML FILE:

        <title>Gothons Of Planet Percal #25</title>

$if greeting:
    I just wanted to say $greeting.
$else:
    Hello, world!

app.py:

import web

urls = (
  '/', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
    def GET(self):
        greeting = "Hello World"
        return render.index(greeting = greeting)

if __name__ == "__main__":
    app.run()

TRACEBACK

Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/web/wsgiserver/__init__.py", line 1245, in     communicate
    req.respond()
  File "/Library/Python/2.7/site-packages/web/wsgiserver/__init__.py", line 775, in respond
self.server.gateway(self).respond()
  File "/Library/Python/2.7/site-packages/web/wsgiserver/__init__.py", line 2018, in respond
    response = self.req.server.wsgi_app(self.env, self.start_response)
  File "/Library/Python/2.7/site-packages/web/httpserver.py", line 268, in __call__
    return self.app(environ, xstart_response)
  File "/Library/Python/2.7/site-packages/web/httpserver.py", line 236, in __call__
    return self.app(environ, start_response)
  File "/Library/Python/2.7/site-packages/web/application.py", line 276, in wsgi
    result = self.handle_with_processors()
  File "/Library/Python/2.7/site-packages/web/application.py", line 246, in     handle_with_processors
    return process(self.processors)
  File "/Library/Python/2.7/site-packages/web/application.py", line 243, in process
    raise self.internalerror()
  File "/Library/Python/2.7/site-packages/web/application.py", line 467, in internalerror
    return debugerror.debugerror()
  File "/Library/Python/2.7/site-packages/web/debugerror.py", line 305, in debugerror
    return web._InternalError(djangoerror())
  File "/Library/Python/2.7/site-packages/web/debugerror.py", line 290, in djangoerror
    djangoerror_r = Template(djangoerror_t, filename=__file__, filter=websafe)
  File "/Library/Python/2.7/site-packages/web/template.py", line 844, in __init__
    code = self.compile_template(text, filename)
  File "/Library/Python/2.7/site-packages/web/template.py", line 922, in compile_template
    ast = compiler.parse(code)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/compiler/transformer.py", line 51, in parse
    return Transformer().parsesuite(buf)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/compiler/transformer.py", line 128, in parsesuite
    return self.transform(parser.suite(text))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/compiler/transformer.py", line 124, in transform
    return self.compile_node(tree)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/compiler/transformer.py", line 167, in compile_node
    raise WalkerError, ('unexpected node type', n)
WalkerError: ('unexpected node type', 339)

Body:
First of all you should add $def with(greeting) in your html page.

html file:

$def with(greeting)
<html>
    ...
</html>
    ...

then change:

app.py:

...
return render.index(greeting)
...


问:
Hashmap. Find key(s) which have same values between two hashmaps
Lets consider we have two hashmaps as below:

```<code> HashMap<String, Integer> map1  = new HashMap<>();
 map1.put("vishal", 10);
 map1.put("sachin", 30);
 map1.put("vaibhav", 20);

 HashMap<String, Integer> map2  = new HashMap<>();
 map2.put("Raja", 10);
 map2.put("John", 30);
 map2.put("Krishna", 20);
</code>```

The "vaibhav" from map1 and "krishna" from map2 have the same values.

I need to find the keys from both the maps, which have the same values. In this case, "vaibhav" and "Krishna".

Thanks.

答:
You can improve the time complexity to O(n + m) where n is the size of first map and m is the size of the second map.

We can achieve this by making values as keys and keys as values.

Steps:

Iterate over each map.

Store all current map values in a new map and collect all keys who have that value in a list and put the current value with this list in the new map.

Now, iterate over any of the new map collections and get the common keys and it's respective values for printing.

Snippet:

```<code>private static void showCommonValueKeys(HashMap<String, Integer> map1,HashMap<String, Integer> map2){
    Map<Integer,List<String>> map1Collect = flipKeyValue(map1);
    Map<Integer,List<String>> map2Collect = flipKeyValue(map2);

    for(Map.Entry<Integer,List<String>> m : map1Collect.entrySet()){
        int key = m.getKey();
        if(map2Collect.containsKey(key)){
            System.out.println("For value " + key);
            System.out.println("First map keys: " + m.getValue().toString());
            System.out.println("Second map keys: " + map2Collect.get(key).toString());
            System.out.println();
        }
    }

}

private static  Map<Integer,List<String>> flipKeyValue(HashMap<String, Integer> map){
     Map<Integer,List<String>> mapCollect = new HashMap<>();

     for(Map.Entry<String,Integer> m : map.entrySet()){
        String  key = m.getKey();
        int val = m.getValue();
        mapCollect.putIfAbsent(val,new ArrayList<>());
        mapCollect.get(val).add(key);
     }

     return mapCollect;
}
</code>```

Demo: https://onlinegdb.com/SJdcpbOXU

Body:
Lets consider we have two hashmaps as below:

 HashMap<String, Integer> map1  = new HashMap<>();
 map1.put("vishal", 10);
 map1.put("sachin", 30);
 map1.put("vaibhav", 20);

 HashMap<String, Integer> map2  = new HashMap<>();
 map2.put("Raja", 10);
 map2.put("John", 30);
 map2.put("Krishna", 20);

The "vaibhav" from map1 and "krishna" from map2 have the same values.

I need to find the keys from both the maps, which have the same values. In this case, "vaibhav" and "Krishna".

Thanks.

Body:
You can improve the time complexity to O(n + m) where n is the size of first map and m is the size of the second map.

We can achieve this by making values as keys and keys as values.

Steps:

Iterate over each map.

Store all current map values in a new map and collect all keys who have that value in a list and put the current value with this list in the new map.

Now, iterate over any of the new map collections and get the common keys and it's respective values for printing.

Snippet:

private static void showCommonValueKeys(HashMap<String, Integer> map1,HashMap<String, Integer> map2){
    Map<Integer,List<String>> map1Collect = flipKeyValue(map1);
    Map<Integer,List<String>> map2Collect = flipKeyValue(map2);

    for(Map.Entry<Integer,List<String>> m : map1Collect.entrySet()){
        int key = m.getKey();
        if(map2Collect.containsKey(key)){
            System.out.println("For value " + key);
            System.out.println("First map keys: " + m.getValue().toString());
            System.out.println("Second map keys: " + map2Collect.get(key).toString());
            System.out.println();
        }
    }

}

private static  Map<Integer,List<String>> flipKeyValue(HashMap<String, Integer> map){
     Map<Integer,List<String>> mapCollect = new HashMap<>();

     for(Map.Entry<String,Integer> m : map.entrySet()){
        String  key = m.getKey();
        int val = m.getValue();
        mapCollect.putIfAbsent(val,new ArrayList<>());
        mapCollect.get(val).add(key);
     }

     return mapCollect;
}

Demo: https://onlinegdb.com/SJdcpbOXU


问:
How to create floating label on form <select> element?
I'm using the floating labels example from Bootstrap but can not get it to work for the "select" element. I'd like the label for the "select" element to function the same way as the "input".

https://www.bootply.com/zBo1RcUZ1o#

答:
you can use (1)Propeller Select lib or (2)Pure CSS.... Follow Example:

(1)

```<code><div class="form-group pmd-textfield pmd-textfield-floating-label">
    <label for="propeller-select">Select with Floating Label</label>
    <select id="propeller-select" class="form-control">
        <option></option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>
</div>
</code>```

Link

(2)

-HTML-

```<code>  <div class="floating-label">
      <select class="floating-select" onclick="this.setAttribute('value', this.value);" value="">
        <option value=""></option>
        <option value="1">Item1</option>
        <option value="2">Item2</option>
        <option value="3">Item3</option>
        <option value="4">Item4</option>
        <option value="5">Item5</option>
      </select>
      <label>Select</label>
</div>
</code>```

-CSS-

```<code>.floating-label {
  position:relative;
  margin-bottom:20px;
}

.floating-select {
  font-size:14px;
  padding:4px 4px;
  display:block;
  width:100%;
  height:30px;
  background-color: transparent;
  border:none;
  border-bottom:1px solid #757575;
}

.floating-select:focus {
     outline:none;
     border-bottom:2px solid #5264AE;
}

label {
  color:#999;
  font-size:14px;
  font-weight:normal;
  position:absolute;
  pointer-events:none;
  left:5px;
  top:5px;
  transition:0.2s ease all;
  -moz-transition:0.2s ease all;
  -webkit-transition:0.2s ease all;
}

.floating-select:focus ~ label , .floating-select:not([value=""]):valid ~ label {
  top:-18px;
  font-size:14px;
  color:#5264AE;
}

/* active state */
.floating-select:focus ~ .floating-select:focus ~  {
  width:50%;
}

*, *:before, *:after {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

/* active state */
 .floating-select:focus ~  {
  -webkit-animation:inputHighlighter 0.3s ease;
  -moz-animation:inputHighlighter 0.3s ease;
  animation:inputHighlighter 0.3s ease;
}
</code>```

DEMO

Body:
you can use (1)Propeller Select lib or (2)Pure CSS.... Follow Example:

(1)

<div class="form-group pmd-textfield pmd-textfield-floating-label">
    <label for="propeller-select">Select with Floating Label</label>
    <select id="propeller-select" class="form-control">
        <option></option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>
</div>

Link

(2)

-HTML-

  <div class="floating-label">
      <select class="floating-select" onclick="this.setAttribute('value', this.value);" value="">
        <option value=""></option>
        <option value="1">Item1</option>
        <option value="2">Item2</option>
        <option value="3">Item3</option>
        <option value="4">Item4</option>
        <option value="5">Item5</option>
      </select>
      <label>Select</label>
</div>

-CSS-

.floating-label {
  position:relative;
  margin-bottom:20px;
}

.floating-select {
  font-size:14px;
  padding:4px 4px;
  display:block;
  width:100%;
  height:30px;
  background-color: transparent;
  border:none;
  border-bottom:1px solid #757575;
}

.floating-select:focus {
     outline:none;
     border-bottom:2px solid #5264AE;
}

label {
  color:#999;
  font-size:14px;
  font-weight:normal;
  position:absolute;
  pointer-events:none;
  left:5px;
  top:5px;
  transition:0.2s ease all;
  -moz-transition:0.2s ease all;
  -webkit-transition:0.2s ease all;
}

.floating-select:focus ~ label , .floating-select:not([value=""]):valid ~ label {
  top:-18px;
  font-size:14px;
  color:#5264AE;
}

/* active state */
.floating-select:focus ~ .floating-select:focus ~  {
  width:50%;
}

*, *:before, *:after {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

/* active state */
 .floating-select:focus ~  {
  -webkit-animation:inputHighlighter 0.3s ease;
  -moz-animation:inputHighlighter 0.3s ease;
  animation:inputHighlighter 0.3s ease;
}

DEMO


问:
jQuery simple fade functions not running smooth in IE
I've got a correctly working website, which runs very smooth in FF and Chrome, but IE shows the fadeIn and fadeOut not fluently, but it flickers...
Is there a solution for this?
I have a bgstretcher on the background, maybe this is making it too heavy for IE?
Thanks in advance,
Wouter</p>

答:
Kind of a kludge, but it gets around the problem:</p>

```<code>if (jQuery.support.opacity) {
    x.fadeIn(100);
}
else {
    x.show();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Kind of a kludge, but it gets around the problem:

if (jQuery.support.opacity) {
    x.fadeIn(100);
}
else {
    x.show();
}


问:
Filter validation-type in Html.ValidationMessageFor
I got a model like this:

```<code>public class SignUpModel
{
    [Required, DisplayName(@"Particulars/Salutation")]
    public short Salutation { get; set; }

    public IEnumerable<SalutationOption> SalutationOptions { get; set; }

    [Required, DisplayName("Particulars/FirstName")]
    public string FirstName { get; set; }

    [Required, Display(Name = "Particulars/LastName")]
    public string LastName { get; set; }

    [Required, DataType(DataType.EmailAddress), Display(Name = "Particulars/Email")]
    public string Email { get; set; }

    [Required, DataType(DataType.EmailAddress), Compare("Email"), Display(Name = "Particulars/EmailConfirmation")]
    public string EmailConfirmation { get; set; }
}
</code>```

Now in my view, I want to post validation-errors (also client-side) using @Html.ValidationMessageFor.

```<code><div class="section-field">
    <div class="form-group">
        @Html.LabelFor(model => model.Email, new { @class = "control-label required" })
        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { autocomplete = "off" } })
        @Html.ValidationMessageFor(x=>x.Email);
    </div>
</div>
<div class="section-field">
    <div class="form-group">
        @Html.LabelFor(model => model.EmailConfirmation, new { @class = "control-label required" })
        @Html.EditorFor(model => model.EmailConfirmation, new { htmlAttributes = new { autocomplete = "off" } })
        @Html.ValidationMessageFor(x=>x.EmailConfirmation);
    </div>
</div>
</code>```

But in Html.ValidationMessageFor I only want to show things like "invalid email-adress" or "both emails must match".

I don't want to show the message saying, that the fields are required, since all are required - and they get bordered red.

Is it possible somehow? Tried with implementing a custom HtmlHelper, but that doesn't filter anything client-side.

答:
So I fixed it simply with css now.

I add a class required-validation to invalid Required-validations:

The field 'FirstName' is required

```

<p>and added into my <code>custom.css</code> </p>

<pre class="lang-css prettyprint-override"><code>p.validation-error.required-validation {
  display: none;
}
</code>```

Other ideas on how to handle this with ASP are welcome :)

Body:
I got a model like this:

public class SignUpModel
{
    [Required, DisplayName(@"Particulars/Salutation")]
    public short Salutation { get; set; }

    public IEnumerable<SalutationOption> SalutationOptions { get; set; }

    [Required, DisplayName("Particulars/FirstName")]
    public string FirstName { get; set; }

    [Required, Display(Name = "Particulars/LastName")]
    public string LastName { get; set; }

    [Required, DataType(DataType.EmailAddress), Display(Name = "Particulars/Email")]
    public string Email { get; set; }

    [Required, DataType(DataType.EmailAddress), Compare("Email"), Display(Name = "Particulars/EmailConfirmation")]
    public string EmailConfirmation { get; set; }
}

Now in my view, I want to post validation-errors (also client-side) using @Html.ValidationMessageFor.

        @Html.LabelFor(model => model.Email, new { @class = "control-label required" })
        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { autocomplete = "off" } })
        @Html.ValidationMessageFor(x=>x.Email);

        @Html.LabelFor(model => model.EmailConfirmation, new { @class = "control-label required" })
        @Html.EditorFor(model => model.EmailConfirmation, new { htmlAttributes = new { autocomplete = "off" } })
        @Html.ValidationMessageFor(x=>x.EmailConfirmation);

But in Html.ValidationMessageFor I only want to show things like "invalid email-adress" or "both emails must match".

I don't want to show the message saying, that the fields are required, since all are required - and they get bordered red.

Is it possible somehow? Tried with implementing a custom HtmlHelper, but that doesn't filter anything client-side.

Body:
So I fixed it simply with css now.

I add a class required-validation to invalid Required-validations:

<p class="validation-error required-validation">The field 'FirstName' is required</p>

and added into my custom.css

p.validation-error.required-validation {
  display: none;
}

Other ideas on how to handle this with ASP are welcome :)


问:
How to scrape multiple websites using Rcrawler in R?
I've noticed we don't have many questions here about Rcrawler, and I thought it's a great tool to scrape website. However, I have a problem telling it to scrape multiple websites as it can only do 3 currently. Please let me know if anyone has experience with this issue. Thanks.

I've tried putting all URLs in a list/vector, but it still doesn't do it. Here are my scraping codes to get the title, description, and keywords of the websites.

```<code>Rcrawler(Website = c("http://www.amazon.com", "www.yahoo.com", "www.wsj.com"),
 no_cores = 3, no_conn = 3, MaxDepth = 0,
ExtractXpathPat = c('/html/head/title', '//meta[@name="description"]/@content', '//meta[@name="keywords"]/@content'),
 PatternsName = c("Title", "Description", "Keywords"), saveOnDisk = FALSE)
</code>```

If I have more than 3 websites, it will give me this error:

```<code>Error in Rcrawler(Website = c("http://www.amazon.com", "www.yahoo.com",  :
  object 'getNewM' not found
</code>```

答:
I'm not sure how this would work in theory, but you can try creating many calls to R crawler.

For example in a while loop:

```<code>a <- list()

Rcrawler_function <- function(no_conn,no_cores,MaxDepth ,Obeyrobots,saveOnDisk,ExtractXpath)
{
  x <- 1
  while(x < 5)
  {
    tryCatch( expr = {

  Rcrawler(ads_txt_4_cat$gen_link[x],no_conn = no_conn,no_cores = no_cores,MaxDepth = MaxDepth,Obeyrobots = Obeyrobots,saveOnDisk = saveOnDisk,ExtractXpathPat = ExtractXpath)
   assign("DATA",DATA,envir = globalenv())
     a[[x]] <<- DATA
    x = x+1

    }
  , error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
  }
}

Rcrawler_function(4,4,0,T,F,"body")
</code>```

Body:
I've noticed we don't have many questions here about Rcrawler, and I thought it's a great tool to scrape website. However, I have a problem telling it to scrape multiple websites as it can only do 3 currently. Please let me know if anyone has experience with this issue. Thanks.

I've tried putting all URLs in a list/vector, but it still doesn't do it. Here are my scraping codes to get the title, description, and keywords of the websites.

Rcrawler(Website = c("http://www.amazon.com", "www.yahoo.com", "www.wsj.com"),
 no_cores = 3, no_conn = 3, MaxDepth = 0,
ExtractXpathPat = c('/html/head/title', '//meta[@name="description"]/@content', '//meta[@name="keywords"]/@content'),
 PatternsName = c("Title", "Description", "Keywords"), saveOnDisk = FALSE)

If I have more than 3 websites, it will give me this error:

Error in Rcrawler(Website = c("http://www.amazon.com", "www.yahoo.com",  :
  object 'getNewM' not found

Body:
I'm not sure how this would work in theory, but you can try creating many calls to R crawler.

For example in a while loop:

a <- list()

Rcrawler_function <- function(no_conn,no_cores,MaxDepth ,Obeyrobots,saveOnDisk,ExtractXpath)
{
  x <- 1
  while(x < 5)
  {
    tryCatch( expr = {

  Rcrawler(ads_txt_4_cat$gen_link[x],no_conn = no_conn,no_cores = no_cores,MaxDepth = MaxDepth,Obeyrobots = Obeyrobots,saveOnDisk = saveOnDisk,ExtractXpathPat = ExtractXpath)
   assign("DATA",DATA,envir = globalenv())
     a[[x]] <<- DATA
    x = x+1

    }
  , error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
  }
}

Rcrawler_function(4,4,0,T,F,"body")


问:
QML TabButton positioning in Column
I'm trying to position TabButtons in TabBar vertically. But the position of each TabButton is somewhere I didn't intend. It seems like they're anchored by root Item.

```<code>Item {
    id: element
    width:800; height:800
    Rectangle {
        id: container
        anchors.fill:parent
        color:"red"
        Rectangle {
            id: subContainer
            anchors.left:parent.left
            anchors.leftMargin: 100
            anchors.top:parent.top
            anchors.topMargin: 100
            width:200
            height:450
            TabBar {
                id: tabBar
                anchors.top:parent.top;
                anchors.bottom:parent.bottom
                anchors.left:parent.left;
                anchors.leftMargin:100
                width:120
                Column {
                    id: column
                    anchors.fill:subContainer //
                    TabButton {
                        id:tab1
                        anchors.top:tabBar.top; anchors.left:tabBar.left
                        width: tabBar.width; height:tabBar.height/3;
                    }
                    TabButton {
                        id:tab2
                        anchors.top:tab1.bottom; anchors.left:tabBar.left
                        width: tabBar.width; height:tabBar.height/3;
                    }
                    TabButton {
                        id:tab3
                        anchors.top:tab2.bottom; anchors.left:tabBar.left
                        width: tabBar.width; height:tabBar.height/3;
                    }
                } // End of Column
            } // End of TabBar
        }

        StackLayout { // this stack seems to be working as I've intended
            id: stack
            anchors.top:parent.top;
            anchors.bottom: parent.bottom;
            anchors.left : bar.right;
            anchors.right:parent.right
            Rectangle {
                id: homeTab
                color:"yellow"
                width: 300; height:300

            }
            Rectangle {
                id: discoverTab
                color:"skyblue"
                width: 300; height:300
            }
            Rectangle {
                id: activityTab
                color:"lightgray"
                width: 300; height:300
            }
        }
    }
}
</code>```

And in designer of QT creator, I can see like below screen capture. tab1 is positioned ignoring it's anchors properties. Could anybody let me know what I'm misunderstanding.

答:
Your anchors are not set properly, You also don't need that column:</p>

```<code>Item {
    id: element
    width:800; height:800
    Rectangle {
        id: container
        anchors.fill:parent
        color:"red"
        Rectangle {
            id: subContainer
            anchors.left:parent.left
            anchors.leftMargin: 100
            anchors.top:parent.top
            anchors.topMargin: 100
            width:200
            height:450
            TabBar {
                id: tabBar

                anchors.top:parent.top;
                anchors.bottom:parent.bottom
                anchors.left:parent.left;
                width:120

                TabButton {
                    id:tab1
                    anchors.top:parent.top; anchors.left:parent.left
                    width: tabBar.width; height:tabBar.height/3;
                }
                TabButton {
                    id:tab2
                    anchors.top:tab1.bottom; anchors.left:parent.left
                    width: tabBar.width; height:tabBar.height/3;
                }
                TabButton {
                    id:tab3
                    anchors.top:tab2.bottom; anchors.left:parent.left
                    width: tabBar.width; height:tabBar.height/3;
                }
            } // End of TabBar
        }

        StackLayout {
            id: stack
            anchors.top:parent.top;
            anchors.bottom: parent.bottom;
            anchors.left : subContainer.right;
            anchors.right:parent.right
            Rectangle {
                id: homeTab
                color:"yellow"
                width: 300; height:300

            }
            Rectangle {
                id: discoverTab
                color:"skyblue"
                width: 300; height:300
            }
            Rectangle {
                id: activityTab
                color:"lightgray"
                width: 300; height:300
            }
        }
    }
}
</code>```

Title: QML TabButton positioning in Column

Body:
I'm trying to position TabButtons in TabBar vertically. But the position of each TabButton is somewhere I didn't intend. It seems like they're anchored by root Item.

Item {
    id: element
    width:800; height:800
    Rectangle {
        id: container
        anchors.fill:parent
        color:"red"
        Rectangle {
            id: subContainer
            anchors.left:parent.left
            anchors.leftMargin: 100
            anchors.top:parent.top
            anchors.topMargin: 100
            width:200
            height:450
            TabBar {
                id: tabBar
                anchors.top:parent.top;
                anchors.bottom:parent.bottom
                anchors.left:parent.left;
                anchors.leftMargin:100
                width:120
                Column {
                    id: column
                    anchors.fill:subContainer //
                    TabButton {
                        id:tab1
                        anchors.top:tabBar.top; anchors.left:tabBar.left
                        width: tabBar.width; height:tabBar.height/3;
                    }
                    TabButton {
                        id:tab2
                        anchors.top:tab1.bottom; anchors.left:tabBar.left
                        width: tabBar.width; height:tabBar.height/3;
                    }
                    TabButton {
                        id:tab3
                        anchors.top:tab2.bottom; anchors.left:tabBar.left
                        width: tabBar.width; height:tabBar.height/3;
                    }
                } // End of Column
            } // End of TabBar
        }

        StackLayout { // this stack seems to be working as I've intended
            id: stack
            anchors.top:parent.top;
            anchors.bottom: parent.bottom;
            anchors.left : bar.right;
            anchors.right:parent.right
            Rectangle {
                id: homeTab
                color:"yellow"
                width: 300; height:300

            }
            Rectangle {
                id: discoverTab
                color:"skyblue"
                width: 300; height:300
            }
            Rectangle {
                id: activityTab
                color:"lightgray"
                width: 300; height:300
            }
        }
    }
}

And in designer of QT creator, I can see like below screen capture. tab1 is positioned ignoring it's anchors properties. Could anybody let me know what I'm misunderstanding.

Body:
Your anchors are not set properly, You also don't need that column:

Item {
    id: element
    width:800; height:800
    Rectangle {
        id: container
        anchors.fill:parent
        color:"red"
        Rectangle {
            id: subContainer
            anchors.left:parent.left
            anchors.leftMargin: 100
            anchors.top:parent.top
            anchors.topMargin: 100
            width:200
            height:450
            TabBar {
                id: tabBar

                anchors.top:parent.top;
                anchors.bottom:parent.bottom
                anchors.left:parent.left;
                width:120

                TabButton {
                    id:tab1
                    anchors.top:parent.top; anchors.left:parent.left
                    width: tabBar.width; height:tabBar.height/3;
                }
                TabButton {
                    id:tab2
                    anchors.top:tab1.bottom; anchors.left:parent.left
                    width: tabBar.width; height:tabBar.height/3;
                }
                TabButton {
                    id:tab3
                    anchors.top:tab2.bottom; anchors.left:parent.left
                    width: tabBar.width; height:tabBar.height/3;
                }
            } // End of TabBar
        }

        StackLayout {
            id: stack
            anchors.top:parent.top;
            anchors.bottom: parent.bottom;
            anchors.left : subContainer.right;
            anchors.right:parent.right
            Rectangle {
                id: homeTab
                color:"yellow"
                width: 300; height:300

            }
            Rectangle {
                id: discoverTab
                color:"skyblue"
                width: 300; height:300
            }
            Rectangle {
                id: activityTab
                color:"lightgray"
                width: 300; height:300
            }
        }
    }
}


问:
Detect swipe gesture direction
That is my code to try and simulate a swipe gesture so when I build to mobile I know it will work. Nothing is being logged and I am confused on why it seems to not work. I want it to print out in the console that I either swiped RTL (Right to Left) or LTR (Left to right). I do not see what I am doing wrong.

```<code>void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        startPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
    if (Input.GetMouseButtonUp(0))
    {
        endPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

    if (startPosition != endPosition && startPosition != Vector3.zero && endPosition != Vector3.zero)
    {
        float deltaX = endPosition.x - startPosition.x;
        float deltaY = endPosition.y - startPosition.y;
        if ((deltaX > 5.0f || deltaX < -5.0f) && (deltaY >= -1.0f || deltaY <= 1.0f))
        {
            if (startPosition.x < endPosition.x)
            {
                print("LTR");
            }
            else
            {
                print("RTL");
            }
        }
        startPosition = endPosition = Vector3.zero;
    }
}
</code>```

答: I searched for the same thing, and found it reasonable to create asset for easy swipe detection, and share it with community. So here it is on github. My solution supports different usecases, including: 8-directions swipe detection, 4-directions, 2-directions (left-right or up-down), swipes on hexagonal grid. All listed is included as a presets, but also you can configure it to detect any number of Vector3 directions. So ti`s really flexible. Also, you can try WebGL build or see video tutorial. If you try it, please, let me know (via youtube comment, or see Contacts section on github), was it suitable for your case, and was it comfortable enough. </p>

Title: Detect swipe gesture direction

Body:
That is my code to try and simulate a swipe gesture so when I build to mobile I know it will work. Nothing is being logged and I am confused on why it seems to not work. I want it to print out in the console that I either swiped RTL (Right to Left) or LTR (Left to right). I do not see what I am doing wrong.

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        startPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
    if (Input.GetMouseButtonUp(0))
    {
        endPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

    if (startPosition != endPosition && startPosition != Vector3.zero && endPosition != Vector3.zero)
    {
        float deltaX = endPosition.x - startPosition.x;
        float deltaY = endPosition.y - startPosition.y;
        if ((deltaX > 5.0f || deltaX < -5.0f) && (deltaY >= -1.0f || deltaY <= 1.0f))
        {
            if (startPosition.x < endPosition.x)
            {
                print("LTR");
            }
            else
            {
                print("RTL");
            }
        }
        startPosition = endPosition = Vector3.zero;
    }
}


问:
google world map chart
http://chart.googleapis.com/chart?cht=map:fixed=?,?,?,?&chs=550x350

how do you display the world map in the new version above like in the old one below?

the old version was that you just have to set chtm=world

http://chart.apis.google.com/chart?chf=bg,s,EAF7FE&chs=440x220&cht=t&chco=FFFFFF,FF0000,FFFF00,00FF00&chd=t:-1&chtm=world

thanks

Title: google world map chart


问:
How to make HTTP POST request with url encoded body in flutter?
I'm trying to make an post request in flutter with content type as url encoded. When I write body : json.encode(data), it encodes to plain text.

If I write body: data I get the error type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in type cast

This is the data object

```<code>var match = {
  "homeTeam": {"team": "Team A"},
  "awayTeam": {"team": "Team B"}
};
</code>```

And my request

```<code>var response = await post(Uri.parse(url),
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: match,
    encoding: Encoding.getByName("utf-8"));
</code>```

答:
I did it like this with dart's http package. It's not too fancy. My endpoint wasn't accepting the parameters with other methods, but it accepted them like this, with the brackets included in the parameter.</p>

```<code>import 'package:http/http.dart' as http;

String url = "<URL>";

Map<String, String> match = {
  "homeTeam[team]": "Team A",
  "awayTeam[team]": "Team B",
};

Map<String, String> headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

http.post(url, body: body, headers: headers).then((response){
    print(response.toString());
});
</code>```

Body:
I'm trying to make an post request in flutter with content type as url encoded. When I write body : json.encode(data), it encodes to plain text.

If I write body: data I get the error type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in type cast

This is the data object

var match = {
  "homeTeam": {"team": "Team A"},
  "awayTeam": {"team": "Team B"}
};

And my request

var response = await post(Uri.parse(url),
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: match,
    encoding: Encoding.getByName("utf-8"));

Body:
I did it like this with dart's http package. It's not too fancy. My endpoint wasn't accepting the parameters with other methods, but it accepted them like this, with the brackets included in the parameter.

import 'package:http/http.dart' as http;

String url = "<URL>";

Map<String, String> match = {
  "homeTeam[team]": "Team A",
  "awayTeam[team]": "Team B",
};

Map<String, String> headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

http.post(url, body: body, headers: headers).then((response){
    print(response.toString());
});


问:
The 'for' loop only prints the first element of my array
I have a problem that I want to go through an array with a for loop, but for some reason the loop doesn't go through it and just prints the first element of the array everywhere.

Here is my array with the days:

```<code>readonly days: WeekDayName[] = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
</code>```

And my functions is what it looks like now:

```<code>get dayName() {
  for (const { item, index } of this.days.map((item, index) => ({ item, index }))) {
    return (item);
  }
}
</code>```

How can I solve not just print the first item everywhere?

答:
Return statement gets you out of the loop. If you want to use an item that is iterated over in the for loop just store in a global variable.
and use break statement to fall out of the loop
Also important to notice that returns take you out of nested loops as well

Check this detailed answer on return vs break

Body:
I have a problem that I want to go through an array with a for loop, but for some reason the loop doesn't go through it and just prints the first element of the array everywhere.

Here is my array with the days:

readonly days: WeekDayName[] = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

And my functions is what it looks like now:

get dayName() {
  for (const { item, index } of this.days.map((item, index) => ({ item, index }))) {
    return (item);
  }
}

How can I solve not just print the first item everywhere?


问:
Room 2.1 SQLite FTS: inserting new single FTS object in database
I have been trying to use new Android's Room 2.1 feature of FTS table to enable search functionality.

Entity:

```<code> @Entity
    class ChatMessageEntity(
            @PrimaryKey
            var messageId: String,
            var messageUser: String,
            var messageText: String,
            )
</code>```

FTS entity:

```<code>@Fts4(contentEntity = ChatMessageEntity::class)
@Entity
class ChatMessageFts(
        var messageText: String //only want messageText searchable
)
</code>```

Database:

```<code>@Database(entities = [ChatMessageEntity::class, ChatMessageFts::class], version = 1)
abstract class ChatMessageDatabase : RoomDatabase() {

    abstract fun chatMessageDatabase(): ChatMessageDao

    companion object {
        fun create(context: Context) = Room.databaseBuilder(context, ChatMessageDatabase::class.java, DB_NAME).build()
    }
}
</code>```

DAO:

```<code>@Query("INSERT INTO ChatMessageFts(ChatMessageFts) VALUES('rebuild')") //works
    suspend fun ftsRebuild()

@Query("INSERT INTO ChatMessageFts(docid, messageText) VALUES(:id, :text)") //compiles but doesn't work
    suspend fun saveFtsMessage(id: Long, text: String)
</code>```

I wish to add each row in FTS when I also add the row in the original table (ChatMessageEntity - not shown). When rebuilding the FTS table from scratch, it works perfectly (ftsRebuild() above).

However, I wish to add each input individually. I have tried many things (for example saveFtsMessage() shown above) - adding without docId, trying with rowId, ... I even tried adding a new object ChatMessageEntity into ChatMessageFts as input but I didn't manage to compile it due to errors.

Any suggestion on how I can add individual input in FTS table is most welcome!

答:
```<code>@Fts4(contentEntity = ChatMessageEntity::class)
</code>```

The magic of the contentEntity property of the annotation is that Room sets up triggers to keep your FTS table in sync with the corresponding entity table:

```<code>"contentSyncTriggers": [
  "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_paragraphsFts_BEFORE_UPDATE BEFORE UPDATE ON `paragraphs` BEGIN DELETE FROM `paragraphsFts` WHERE `docid`=OLD.`rowid`; END",
  "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_paragraphsFts_BEFORE_DELETE BEFORE DELETE ON `paragraphs` BEGIN DELETE FROM `paragraphsFts` WHERE `docid`=OLD.`rowid`; END",
  "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_paragraphsFts_AFTER_UPDATE AFTER UPDATE ON `paragraphs` BEGIN INSERT INTO `paragraphsFts`(`docid`, `prose`) VALUES (NEW.`rowid`, NEW.`prose`); END",
  "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_paragraphsFts_AFTER_INSERT AFTER INSERT ON `paragraphs` BEGIN INSERT INTO `paragraphsFts`(`docid`, `prose`) VALUES (NEW.`rowid`, NEW.`prose`); END"
]
</code>```

(from this sample app from this book)

So long as you are inserting, updating, and deleting your entities, the FTS table will be maintained automatically. You just use the FTS table for querying purposes.

If you skip the contentEntity annotation — and assuming that works — then you might need to maintain your FTS table independently.

Body:
I have been trying to use new Android's Room 2.1 feature of FTS table to enable search functionality.

Entity:

 @Entity
    class ChatMessageEntity(
            @PrimaryKey
            var messageId: String,
            var messageUser: String,
            var messageText: String,
            )

FTS entity:

@Fts4(contentEntity = ChatMessageEntity::class)
@Entity
class ChatMessageFts(
        var messageText: String //only want messageText searchable
)

Database:

@Database(entities = [ChatMessageEntity::class, ChatMessageFts::class], version = 1)
abstract class ChatMessageDatabase : RoomDatabase() {

    abstract fun chatMessageDatabase(): ChatMessageDao

    companion object {
        fun create(context: Context) = Room.databaseBuilder(context, ChatMessageDatabase::class.java, DB_NAME).build()
    }
}

DAO:

@Query("INSERT INTO ChatMessageFts(ChatMessageFts) VALUES('rebuild')") //works
    suspend fun ftsRebuild()

@Query("INSERT INTO ChatMessageFts(docid, messageText) VALUES(:id, :text)") //compiles but doesn't work
    suspend fun saveFtsMessage(id: Long, text: String)

I wish to add each row in FTS when I also add the row in the original table (ChatMessageEntity - not shown). When rebuilding the FTS table from scratch, it works perfectly (ftsRebuild() above).

However, I wish to add each input individually. I have tried many things (for example saveFtsMessage() shown above) - adding without docId, trying with rowId, ... I even tried adding a new object ChatMessageEntity into ChatMessageFts as input but I didn't manage to compile it due to errors.

Any suggestion on how I can add individual input in FTS table is most welcome!

Body:
@Fts4(contentEntity = ChatMessageEntity::class)

The magic of the contentEntity property of the annotation is that Room sets up triggers to keep your FTS table in sync with the corresponding entity table:

"contentSyncTriggers": [
  "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_paragraphsFts_BEFORE_UPDATE BEFORE UPDATE ON `paragraphs` BEGIN DELETE FROM `paragraphsFts` WHERE `docid`=OLD.`rowid`; END",
  "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_paragraphsFts_BEFORE_DELETE BEFORE DELETE ON `paragraphs` BEGIN DELETE FROM `paragraphsFts` WHERE `docid`=OLD.`rowid`; END",
  "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_paragraphsFts_AFTER_UPDATE AFTER UPDATE ON `paragraphs` BEGIN INSERT INTO `paragraphsFts`(`docid`, `prose`) VALUES (NEW.`rowid`, NEW.`prose`); END",
  "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_paragraphsFts_AFTER_INSERT AFTER INSERT ON `paragraphs` BEGIN INSERT INTO `paragraphsFts`(`docid`, `prose`) VALUES (NEW.`rowid`, NEW.`prose`); END"
]

(from this sample app from this book)

So long as you are inserting, updating, and deleting your entities, the FTS table will be maintained automatically. You just use the FTS table for querying purposes.

If you skip the contentEntity annotation — and assuming that works — then you might need to maintain your FTS table independently.


问:
Regex doesn't match with parentheses
I am using Doctrine MongoDB and I have the following code in the query builder:

```<code>$regexSeller = new Regex('^'.$search['seller'], 'i');
$raw->addOr($builder->matchExpr()->field('seller')->equals($regexSeller));
</code>```

It works and find the good results with a search like this "Bob" but doesn't work when there are parentheses like "Bob (from Chicago)".

I guess the problem is in the first line but can't find a way to match with parentheses too.

答:
You have to escape the special characters of your query. E.g. replace ( with \( and ) with \).

In PHP you can use preg_quote(https://www.php.net/manual/en/function.preg-quote.php), like this:

```<code>$regexSeller = new Regex('^'.preg_quote($search['seller']), 'i');
</code>```

Let me know if it worked! ;)

Thanks!

Title: Regex doesn't match with parentheses

Body:
I am using Doctrine MongoDB and I have the following code in the query builder:

$regexSeller = new Regex('^'.$search['seller'], 'i');
$raw->addOr($builder->matchExpr()->field('seller')->equals($regexSeller));

It works and find the good results with a search like this "Bob" but doesn't work when there are parentheses like "Bob (from Chicago)".

I guess the problem is in the first line but can't find a way to match with parentheses too.

Body:
You have to escape the special characters of your query. E.g. replace ( with \( and ) with \).

In PHP you can use preg_quote(https://www.php.net/manual/en/function.preg-quote.php), like this:

$regexSeller = new Regex('^'.preg_quote($search['seller']), 'i');

Let me know if it worked! ;)

Thanks!


问:
changing inner array object value with outer array value with map
I'm new to full-stack development, specifically to java-script and functional programming.
Using high-order function (like map, filter and so) I need to change inner object array values into the outer array given value:

```<code>let arr = [
[ [
  {name: "Alice", age: 22},
  {name: "Charlie", age: 35}
 ], "Bob" ],
 [ [
  {name: "John" , age: 42}
  ], "Ben"]
]
</code>```

and I need output array of:

```<code>output = [
 [
  {name: "Bob", age: 22},
  {name: "Bob", age: 35}
 ],
 [
  {name: "Ben", age: 42}
 ]
]
</code>```

Thank you.

答:
You already knew to use map, so here it is:

```<code>arr.map(x => x[0].map(y => {return {...y, name: x[1]}}))
</code>```

For each item of the main list, we map it to a list of objects with the name replaced.

Body:
I'm new to full-stack development, specifically to java-script and functional programming.
Using high-order function (like map, filter and so) I need to change inner object array values into the outer array given value:

let arr = [
[ [
  {name: "Alice", age: 22},
  {name: "Charlie", age: 35}
 ], "Bob" ],
 [ [
  {name: "John" , age: 42}
  ], "Ben"]
]

and I need output array of:

output = [
 [
  {name: "Bob", age: 22},
  {name: "Bob", age: 35}
 ],
 [
  {name: "Ben", age: 42}
 ]
]

Thank you.

Body:
You already knew to use map, so here it is:

arr.map(x => x[0].map(y => {return {...y, name: x[1]}}))

For each item of the main list, we map it to a list of objects with the name replaced.


答: Getter functions can't return the iteration values. You just can get an element in result of getters.</p>

Title: The 'for' loop only prints the first element of my array


问:
Data Structure for large and detailed maps
Does anyone has recommendation of data structures for relative large maps with high resolution, something like 400mile x 400mile with 10-15ft resolution. Using 2D array, that would be roughly 2Mx2M cells.

The map only needs to store the elevation and terrain (earth, water, rock, etc.), and I don't think storing tiles is a good strategy.

Thank you!

答: If you want people to see the data as a map over the web, then creating small image tile overlays will be the fastest approach to sharing such a large dataset.  </p>


问:
Dictionary of dictionaries in python
Im trying to create a dictionary of dictionaries in python. I have a nested for loop which looks like this

```<code>frequencyLomb = {}
for J in range(1,81,4):
  n_items = take(dataDays.values(),J-1,J+3)
  for K in range(1,5):
    temp_time=n_items[K-1][0]
    temp_flux=n_items[K-1][1]
    mean_temp_flux=np.mean(temp_flux)

    temp_flux_final=temp_flux-mean_temp_flux
    # frequencyLomb[J][K] = freq_grid(temp_time)   want something like this
</code>```

n_items is a 4 element list with indexes 0 to 3 and in every one of these is a two element list with indexes 0 and 1. Now I want to create a dictionary of dictionaries which will save the value of frequencyLomb in way so that the Key name will be the variable J and the items will be added from the inner for loop so the final product will look like this:

```<code>frequencyLomb= {1: {1: 'somevalue1', 2: 'somevalue1', 3: 'somevalue1', 4: 'somevalue1', 5: 'somevalue1'},
      5: {1: 'somevalue1',....}}
</code>```

etc. up to Key number 80

P.S.: The function freq_grid just creates an array of floats and the function take takes the values from dictionary dataDays(dictionary of lists) with keys number J-1 up to values with key J+3

Thanks. Any help is appreciated

答:
Try something like this:</p>

```<code>if j not in frequencyLomb: #Then try frequencyLomb[J] = {} and then frequncyLomb[J][K] = Your Value

else: #Then directly add your value to the inner dictionary.
</code>```

Title: Dictionary of dictionaries in python

Body:
Im trying to create a dictionary of dictionaries in python. I have a nested for loop which looks like this

frequencyLomb = {}
for J in range(1,81,4):
  n_items = take(dataDays.values(),J-1,J+3)
  for K in range(1,5):
    temp_time=n_items[K-1][0]
    temp_flux=n_items[K-1][1]
    mean_temp_flux=np.mean(temp_flux)

    temp_flux_final=temp_flux-mean_temp_flux
    # frequencyLomb[J][K] = freq_grid(temp_time)   want something like this

n_items is a 4 element list with indexes 0 to 3 and in every one of these is a two element list with indexes 0 and 1. Now I want to create a dictionary of dictionaries which will save the value of frequencyLomb in way so that the Key name will be the variable J and the items will be added from the inner for loop so the final product will look like this:

frequencyLomb= {1: {1: 'somevalue1', 2: 'somevalue1', 3: 'somevalue1', 4: 'somevalue1', 5: 'somevalue1'},
      5: {1: 'somevalue1',....}}

etc. up to Key number 80

P.S.: The function freq_grid just creates an array of floats and the function take takes the values from dictionary dataDays(dictionary of lists) with keys number J-1 up to values with key J+3

Thanks. Any help is appreciated

Body:
Try something like this:

if j not in frequencyLomb: #Then try frequencyLomb[J] = {} and then frequncyLomb[J][K] = Your Value

else: #Then directly add your value to the inner dictionary.


问:
input for scikit-learn random forest
I am trying to predict the output of tennis matches - just a fun side project. Im using a random forest regressor to do this. now, one of the features is the ranking of the player before a specific match. for many matches I dont have a ranking (I only have the first 200 ranked). The question is - is it better to put a value that is not an integer, like for example the string "NoRank", or put an integer that is beyond the range of 1-200? Considering the learning algorithm, Im inclined to put the value 201, but I would like to hear your opinions on this..
Thanks!

答:
I will be careful with just adding 201 (or any other value) to the nonranked ones.
RF normalize the data (Do I need to normalize (or scale) data for randomForest (R package)?), which means it can group 200 with 201 in the split, or it might not. you are basically faking data that you do not have.

I will add another column: "haverank"
and use a 0/1 for it.
0 will be for people without rank
1 for people with rank.

call it "highrank" if the name sounds better.
you can also add another column named "veryhighrank"
and give the value 1 to all players between ranks 1-50. etc...

Title: input for scikit-learn random forest


问:
Keyboard not showing up in Webview
How to solve the Keyboard not showing up when the input field on the web is being clicked. I am currently using webview_flutter</p>

答:
Have you tried adding to your XML:</p>

```<code>android:focusable="true"
android:focusableInTouchMode="true"
</code>```

Title: Keyboard not showing up in Webview

Body:
Have you tried adding to your XML:

android:focusable="true"
android:focusableInTouchMode="true"


问:
Gatsby mongodb source plugin does not display anything in Graphiql
I'm starting with Gatsby.js, and I'm already facing problem connecting to mongodb source.

No error message at startup and I cannot see anything regarding Mongodb in Graphiql tool (I was expecting something like allMongodbCloudDocuments)

I'm working on fresh Gatsby project :

```<code>gatsby new my-site https://github.com/gatsbyjs/gatsby-starter-hello-world
</code>```

I've installed mongodb source plugin :

```<code>npm install --save gatsby-source-mongodb
</code>```

And modified config.js

```<code>module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-mongodb`,
      options: {
            connectionString: `mongodb://myuser:mypassword@mysubdomain-mongodb.services.clever-cloud.com:27017`,
            dbName: 'mydbname',
            collection: `cars`
      },
    },
  ],
}
</code>```

What am I missing?

答:
Answering my own question : I've tried connection without connection string, passing all parameters individually and it works. Don't understand why, as the connection string had the same parameters :</p>

```<code>module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-mongodb`,
      options: {
        server: { address: 'mysubdomain-mongodb.services.clever-cloud.com', port: '27017' },
        auth: { user: 'myuser', password: 'mypassword'},
        dbName: 'mydbname',
        collection: `cars`
      },
    },
  ],
}
</code>```

Body:
I'm starting with Gatsby.js, and I'm already facing problem connecting to mongodb source.

No error message at startup and I cannot see anything regarding Mongodb in Graphiql tool (I was expecting something like allMongodbCloudDocuments)

I'm working on fresh Gatsby project :

gatsby new my-site https://github.com/gatsbyjs/gatsby-starter-hello-world

I've installed mongodb source plugin :

npm install --save gatsby-source-mongodb

And modified config.js

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-mongodb`,
      options: {
            connectionString: `mongodb://myuser:mypassword@mysubdomain-mongodb.services.clever-cloud.com:27017`,
            dbName: 'mydbname',
            collection: `cars`
      },
    },
  ],
}

What am I missing?

Body:
Answering my own question : I've tried connection without connection string, passing all parameters individually and it works. Don't understand why, as the connection string had the same parameters :

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-mongodb`,
      options: {
        server: { address: 'mysubdomain-mongodb.services.clever-cloud.com', port: '27017' },
        auth: { user: 'myuser', password: 'mypassword'},
        dbName: 'mydbname',
        collection: `cars`
      },
    },
  ],
}