问:
App Stops Working when Trying ViewModel Android Kotlin
I am trying to use ViewModel for making API calls, But when I cick the button to send the phone number for OTP the app breaks and their is not information in the logcat too.

Code of LoginActivity.kt
`

```<code>class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding
    private lateinit var viewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        viewModel = LoginViewModelFactory(LoginService.create()).create(LoginViewModel::class.java)
        binding.loginViewModel = viewModel
        binding.lifecycleOwner = this

        binding.continueButton.setOnClickListener {
            viewModel.onLogin()
        }

        viewModel.login.observe(this){
            gotoOTP()
        }
    }
    fun gotoOTP(){
        var intent = Intent(this@LoginActivity, OTPLoginVerification::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
        this.startActivity(intent)
        this.finish()
    }
}
</code>```

`

code for LoginViewModel.kt
`

```<code>class LoginViewModel(var loginService: LoginService) : ViewModel(), Observable {

    val phoneNumber: MutableLiveData<String> = MutableLiveData()
    val login = MutableLiveData<Unit>()

    fun onLogin(){
            loginService.getOTP(LoginRequestModel(phone_no = phoneNumber.value.toString()))
                .enqueue(object: Callback<LoginResponseModel>{
                    override fun onResponse(call: Call<LoginResponseModel>, response: Response<LoginResponseModel>) {

                        if(response.isSuccessful) {
                            if (response.body()!!.result) login.postValue(Unit)
                            else print("Error")
                        }
                        else{
                            print("Error")
                        }
                    }

                    override fun onFailure(call: Call<LoginResponseModel>, t: Throwable) {
                        print("Error")
                    }

                })
        }

    override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

    }

    override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

    }
}
</code>```

`

code for LoginViewModelFactory.kt
`

```<code>class LoginViewModelFactory(private val loginService: LoginService): ViewModelProvider.Factory{

    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if(modelClass.isAssignableFrom(LoginViewModel::class.java)){
            return LoginViewModel(loginService) as T
        }
        else throw IllegalArgumentException("Error Unknown ViewModel Type")
    }
}
</code>```

And this is the service Interface

```<code>interface LoginService {

    @POST("getOTP")
    fun getOTP(@Body model: LoginRequestModel) : Call<LoginResponseModel>

    companion object{

        val BASE_URL = "*********"

        fun create(): LoginService{
            val client = OkHttpClient.Builder()
            client.connectTimeout(2, TimeUnit.MINUTES)
            client.readTimeout(2, TimeUnit.MINUTES)
            client.writeTimeout(2, TimeUnit.MINUTES)
            val gson = GsonBuilder()
                .serializeNulls()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .setLenient()
                .create()
            val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client.build())
                .build()
            return retrofit.create(LoginService::class.java)
        }
    }

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

<data>
    <variable
        name="LoginViewModel"
        type="com.example.sample.viewmodels.LoginViewModel" />
</data>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Auth.LoginActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.card.MaterialCardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="@id/g_h_1"
            app:cardBackgroundColor="@color/peach_dark"

            style="@style/CustomCardViewStyle">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:scaleType="fitXY"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintDimensionRatio="1.2:1"
                    android:src="@drawable/loginimage" />

            </androidx.constraintlayout.widget.ConstraintLayout>
        </com.google.android.material.card.MaterialCardView>

        <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:scaleType="fitCenter"
            android:src="@drawable/logo"
            app:layout_constraintDimensionRatio="3:1"
            app:layout_constraintTop_toTopOf="@id/g_h_2"
            app:layout_constraintStart_toStartOf="@id/g_v_2"
            app:layout_constraintEnd_toEndOf="@id/g_v_3"
            app:layout_constraintBottom_toBottomOf="@id/g_h_3" />

        <TextView
            android:id="@+id/company_highlight"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="@string/company_highlight"
            android:layout_marginTop="10dp"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toTopOf="@id/g_h_3"
            android:textAlignment="center"
            android:textSize="20dp"
            android:fontFamily="@font/metropolisbold"
            android:textColor="@color/t_dark" />

        <TextView
            android:id="@+id/login_textview"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="@string/login_text"
            android:layout_marginTop="20dp"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/company_highlight"
            android:textAlignment="center"
            android:textSize="17dp"
            android:fontFamily="@font/metropolissemibold" />

        <androidx.gridlayout.widget.GridLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/gridview_mobilenumber"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@+id/login_textview"
            android:layout_marginTop="25dp"
            app:columnCount="2">

            <com.google.android.material.card.MaterialCardView
                android:id="@+id/country_flag_cardview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_column="0"
                android:padding="10dp"
                app:layout_columnWeight="0.4"
                app:cardCornerRadius="10dp"
                app:layout_rowWeight="1"
                android:layout_marginLeft="3dp"
                app:strokeWidth="1dp"
                app:strokeColor="@color/t_light">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <ImageView
                        android:id="@+id/country_flag"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:padding="5dp"
                        android:src="@drawable/indianflag" />

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_toRightOf="@id/country_flag"
                        android:layout_centerVertical="true"
                        android:src="@drawable/dropdown" />
                </RelativeLayout>
            </com.google.android.material.card.MaterialCardView>

            <com.google.android.material.card.MaterialCardView
                android:id="@+id/mobile_number_cardview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_column="1"
                android:padding="10dp"
                android:layout_marginLeft="10dp"
                app:layout_columnWeight="20"
                app:layout_rowWeight="1"
                app:cardCornerRadius="10dp"
                app:strokeWidth="1dp"
                app:strokeColor="@color/t_light">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:id="@+id/country_code_textview"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:fontFamily="@font/metropolissemibold"
                        android:text="@string/country_code"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="5dp"
                        android:textColor="@color/t_dark"
                        android:textSize="22dp" />

                    <EditText
                        android:id="@+id/mobile_number_edittext"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="10dp"
                        android:layout_toRightOf="@+id/country_code_textview"
                        android:background="@null"
                        android:fontFamily="@font/metropolislight"
                        android:hint="@string/enter_mobile"
                        android:text="@{LoginViewModel.phoneNumber}"
                        android:inputType="phone"
                        android:maxLength="10"
                        android:textColor="@color/t_dark"
                        android:textColorHint="@color/t_light"
                        android:textSize="15dp" />

                </RelativeLayout>
            </com.google.android.material.card.MaterialCardView>
        </androidx.gridlayout.widget.GridLayout>

        <TextView
            android:id="@+id/new_user_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New User"
            android:textSize="15dp"
            android:fontFamily="@font/metropolisbold"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/gridview_mobilenumber"
            android:textColor="@color/peach_700"
            android:layout_marginTop="5dp" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/continue_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/new_user_textview"
            android:text="Continue"
            android:fontFamily="@font/metropolissemibold"
            android:textAllCaps="false"
            android:textSize="17dp"
            app:cornerRadius="10dp"
            android:layout_marginTop="20dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.45" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.47" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.54" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.10" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.30" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.70" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.90" />

    </android.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</code>```

To the best of my knowledge I tried to make changes but nothing worked.
Any help would be great, As I am unable to find the place where I am making mistake.
Thanks in Advance.

Body:
I am trying to use ViewModel for making API calls, But when I cick the button to send the phone number for OTP the app breaks and their is not information in the logcat too.

Code of LoginActivity.kt
`

class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding
    private lateinit var viewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        viewModel = LoginViewModelFactory(LoginService.create()).create(LoginViewModel::class.java)
        binding.loginViewModel = viewModel
        binding.lifecycleOwner = this

        binding.continueButton.setOnClickListener {
            viewModel.onLogin()
        }

        viewModel.login.observe(this){
            gotoOTP()
        }
    }
    fun gotoOTP(){
        var intent = Intent(this@LoginActivity, OTPLoginVerification::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
        this.startActivity(intent)
        this.finish()
    }
}

`

code for LoginViewModel.kt
`

class LoginViewModel(var loginService: LoginService) : ViewModel(), Observable {

    val phoneNumber: MutableLiveData<String> = MutableLiveData()
    val login = MutableLiveData<Unit>()

    fun onLogin(){
            loginService.getOTP(LoginRequestModel(phone_no = phoneNumber.value.toString()))
                .enqueue(object: Callback<LoginResponseModel>{
                    override fun onResponse(call: Call<LoginResponseModel>, response: Response<LoginResponseModel>) {

                        if(response.isSuccessful) {
                            if (response.body()!!.result) login.postValue(Unit)
                            else print("Error")
                        }
                        else{
                            print("Error")
                        }
                    }

                    override fun onFailure(call: Call<LoginResponseModel>, t: Throwable) {
                        print("Error")
                    }

                })
        }

    override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

    }

    override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

    }
}

`

code for LoginViewModelFactory.kt
`

class LoginViewModelFactory(private val loginService: LoginService): ViewModelProvider.Factory{

    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if(modelClass.isAssignableFrom(LoginViewModel::class.java)){
            return LoginViewModel(loginService) as T
        }
        else throw IllegalArgumentException("Error Unknown ViewModel Type")
    }
}

And this is the service Interface

interface LoginService {

    @POST("getOTP")
    fun getOTP(@Body model: LoginRequestModel) : Call<LoginResponseModel>

    companion object{

        val BASE_URL = "*********"

        fun create(): LoginService{
            val client = OkHttpClient.Builder()
            client.connectTimeout(2, TimeUnit.MINUTES)
            client.readTimeout(2, TimeUnit.MINUTES)
            client.writeTimeout(2, TimeUnit.MINUTES)
            val gson = GsonBuilder()
                .serializeNulls()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .setLenient()
                .create()
            val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client.build())
                .build()
            return retrofit.create(LoginService::class.java)
        }
    }

}

<?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>
    <variable
        name="LoginViewModel"
        type="com.example.sample.viewmodels.LoginViewModel" />
</data>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Auth.LoginActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.card.MaterialCardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="@id/g_h_1"
            app:cardBackgroundColor="@color/peach_dark"

            style="@style/CustomCardViewStyle">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:scaleType="fitXY"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintDimensionRatio="1.2:1"
                    android:src="@drawable/loginimage" />

            </androidx.constraintlayout.widget.ConstraintLayout>
        </com.google.android.material.card.MaterialCardView>

        <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:scaleType="fitCenter"
            android:src="@drawable/logo"
            app:layout_constraintDimensionRatio="3:1"
            app:layout_constraintTop_toTopOf="@id/g_h_2"
            app:layout_constraintStart_toStartOf="@id/g_v_2"
            app:layout_constraintEnd_toEndOf="@id/g_v_3"
            app:layout_constraintBottom_toBottomOf="@id/g_h_3" />

        <TextView
            android:id="@+id/company_highlight"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="@string/company_highlight"
            android:layout_marginTop="10dp"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toTopOf="@id/g_h_3"
            android:textAlignment="center"
            android:textSize="20dp"
            android:fontFamily="@font/metropolisbold"
            android:textColor="@color/t_dark" />

        <TextView
            android:id="@+id/login_textview"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="@string/login_text"
            android:layout_marginTop="20dp"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/company_highlight"
            android:textAlignment="center"
            android:textSize="17dp"
            android:fontFamily="@font/metropolissemibold" />

        <androidx.gridlayout.widget.GridLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/gridview_mobilenumber"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@+id/login_textview"
            android:layout_marginTop="25dp"
            app:columnCount="2">

            <com.google.android.material.card.MaterialCardView
                android:id="@+id/country_flag_cardview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_column="0"
                android:padding="10dp"
                app:layout_columnWeight="0.4"
                app:cardCornerRadius="10dp"
                app:layout_rowWeight="1"
                android:layout_marginLeft="3dp"
                app:strokeWidth="1dp"
                app:strokeColor="@color/t_light">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <ImageView
                        android:id="@+id/country_flag"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:padding="5dp"
                        android:src="@drawable/indianflag" />

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_toRightOf="@id/country_flag"
                        android:layout_centerVertical="true"
                        android:src="@drawable/dropdown" />
                </RelativeLayout>
            </com.google.android.material.card.MaterialCardView>

            <com.google.android.material.card.MaterialCardView
                android:id="@+id/mobile_number_cardview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_column="1"
                android:padding="10dp"
                android:layout_marginLeft="10dp"
                app:layout_columnWeight="20"
                app:layout_rowWeight="1"
                app:cardCornerRadius="10dp"
                app:strokeWidth="1dp"
                app:strokeColor="@color/t_light">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:id="@+id/country_code_textview"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:fontFamily="@font/metropolissemibold"
                        android:text="@string/country_code"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="5dp"
                        android:textColor="@color/t_dark"
                        android:textSize="22dp" />

                    <EditText
                        android:id="@+id/mobile_number_edittext"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="10dp"
                        android:layout_toRightOf="@+id/country_code_textview"
                        android:background="@null"
                        android:fontFamily="@font/metropolislight"
                        android:hint="@string/enter_mobile"
                        android:text="@{LoginViewModel.phoneNumber}"
                        android:inputType="phone"
                        android:maxLength="10"
                        android:textColor="@color/t_dark"
                        android:textColorHint="@color/t_light"
                        android:textSize="15dp" />

                </RelativeLayout>
            </com.google.android.material.card.MaterialCardView>
        </androidx.gridlayout.widget.GridLayout>

        <TextView
            android:id="@+id/new_user_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New User"
            android:textSize="15dp"
            android:fontFamily="@font/metropolisbold"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/gridview_mobilenumber"
            android:textColor="@color/peach_700"
            android:layout_marginTop="5dp" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/continue_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/new_user_textview"
            android:text="Continue"
            android:fontFamily="@font/metropolissemibold"
            android:textAllCaps="false"
            android:textSize="17dp"
            app:cornerRadius="10dp"
            android:layout_marginTop="20dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.45" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.47" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.54" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.10" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.30" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.70" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.90" />

    </android.constraintlayout.widget.ConstraintLayout>
</ScrollView>

To the best of my knowledge I tried to make changes but nothing worked.
Any help would be great, As I am unable to find the place where I am making mistake.
Thanks in Advance.


来源: stackexchange

问:
Should debugger be launched always in VScode when only running a file (not debugging) using code-runner?
In a VScode C/C++ programming setup on Windows 10 system, the "C/C++ Extension Pack", "Code Runner", "WSL" extensions are installed, which use Alpine Linux target on WSL on this PC. Alpine Linux WSL instance has the gcc dev environment, build-tools, gdb etc. installed, apart from the necessary VScode extensions needed inside WSL.

In this environment I am able to write C/C++ programs, build them, execute them, interact with them through the built-in terminal. I use the "Code Runner" "Run C/C++ file" shortcut button to build(if necessary) and run individual C/C++ program files (there is no Makefile and these are simple programs all thrown in a single folder, not in a project structure).

Recently however, I noticed that whenever I try to "Run C/C++ file", debugger is also launched and I get a screen like this (notice the 2 yellow/orange arrows indicating what I am trying to draw attention to):

I do not remember this being the case earlier, but I think this started after I tried to debug a program by setting a breakpoint, which I later cleared. I've also ensured that "Run > Remove All Breakpoints" is done, to make sure that there are absolutely no breakpoints. Therefore wondering if:

it is normal for debugger to get launched in this manner ?

if not, what exactly might have caused it ?

finally, what can I do to make sure that the debugger is not launched, when all I want to do is "Run" ?

In "Code Runner" settings file, I did not find anything that might control this behaviour, but then I am quite new to VScode so not sure if I am missing anything obvious.

ContentLicense: CC BY-SA 4.0


问:
Python Package Correct Import Structure For Source And Binaries?
I want to start by saying I know this has been answered many times before, but there was a lot of conflicting answers and half-solutions

Summary of layout

EDIT: GitHub Link Here

I am making a program valled ROSA in Python, and wish for it to be usable both by directly running a single script and by importing the code so that a user can write their own wrapper for it. Consequently, I have split the program into 2 files (well actually 3, but)

the file ROSA.py which contains a class called ROSA_ and uses class attributes from the foreign_potato_master.py file. Running this file directly does nothing

the file main.py which is imports ROSA.py and uses the ROSA_ class (it also uses variables from ROSA.py to decide whether the script is on a Raspberry Pi or a desktop, etc). This file is made to be run directly, and basically just calls the functions from ROSA_

the file foreign_potato_master.py which contains a few classes that contain dictionaries of strings that are used by ROSA.py to reply to the user. I moved these into a separate file to make it easier for others to edit the output of my program

Brief file contents:

ROSA.py:

import speech_recognition as sr
import foreign_potato_master

try:
    import RPi.GPIO as GPIO  # type: ignore
    is_on_RPi = True
except ImportError:
    # note: Probably a more elegant solution somewhere
    # note: but this is what works for me atm
    is_on_RPi = False

class ROSA_:
    def __init__(self, json_path = None):
        ...

        self.title = foreign_potato_master.Text_Decorations.title
        self.symbols = foreign_potato_master.Text_Decorations.symbols

        self.activations = foreign_potato_master.Responses.activations
        self.keys = foreign_potato_master.Responses.keys
        self.responses = foreign_potato_master.Responses.responses
        self.prev_responses = foreign_potato_master.Responses.prev_responses

        ...

    def background_listening(self):
        ...
```
<h5>foreign_potato_master.py:</h5>
<pre class="lang-py prettyprint-override"><code>class Responses:
    activations = [...]
    keys = {...}
    responses = {...}
    prev_responses = {...}

class Text_Decorations:
    title = '...'
    symbols = {...}

...
</code>```

main.py:

import ROSA

def main():
    ...

    obj = ROSA.ROSA_()
    speech = obj.background_listening()

    ...

if __name__ == '__main__': main()
```
<h5><strong>init</strong>.py:</h5>
<pre class="lang-py prettyprint-override"><code>from ROSA import ROSA
from ROSA import foreign_potato_master
</code>```

all of the files have some comments/docstrings/verison tags etc in the top, including the __init__.py

Directory Structure

```<code>ROSA
|- bin
    |- ...
|- docs
    |- ...
|- src
    |- ROSA
        |- __init__.py
        |- foreign_potato_master.py
        |- gpio.json
        |- main.py
        |- ROSA.py
</code>```

My question:

What is the best way to import these files into each other?

# main.py
from . import ROSA
import .ROSA
```
<p>Both of the above fail (<code>ImportError: attempted relative import with no known parent package</code> and <code>SyntaxError: invalid syntax</code> respectively)</p>
<pre class="lang-py prettyprint-override"><code># main.py
import ROSA
</code>```

The above works when running as Python files, but not as compiled binaries (via pyinstaller):

```<code>Traceback (most recent call last):
  File "\\192.168.0.8\source\projects\ROSA\src\ROSA\main.py", line 39, in <module>
  File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
  File "ROSA\__init__.py", line 35, in <module>
  File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
  File "ROSA\ROSA.py", line 80, in <module>
ModuleNotFoundError: No module named 'foreign_potato_master'
[2520] Failed to execute script 'main' due to unhandled exception!
</code>```

the above was run in Windows Sandbox

EDIT: probably should have clarified, the exe was built using the following batch script:

```<code>:: \ROSA

pyinstaller --noconfirm --log-level=WARN --clean ^
    --distpath ".\bin\bin" --workpath ".\bin\build" ^
    --name ROSA --onefile ^
    --paths ".\rosa-env\Lib\site-packages" ^
    --hidden-import pyi_splash ^
    --add-binary ".\src\ROSA\responses;.\responses" ^
    --splash ".\docs\ico\hotpot-ai.png" --icon ".\docs\ico\hotpot-ai.ico" ^
    .\src\ROSA\main.py
</code>```

Finally (TL;DR):

So how can I import these files and have it work when run directly, when imported and when compiled to binary?

Body:
I want to start by saying I know this has been answered many times before, but there was a lot of conflicting answers and half-solutions

Summary of layout

EDIT: GitHub Link Here

I am making a program valled ROSA in Python, and wish for it to be usable both by directly running a single script and by importing the code so that a user can write their own wrapper for it. Consequently, I have split the program into 2 files (well actually 3, but)

the file ROSA.py which contains a class called ROSA_ and uses class attributes from the foreign_potato_master.py file. Running this file directly does nothing

the file main.py which is imports ROSA.py and uses the ROSA_ class (it also uses variables from ROSA.py to decide whether the script is on a Raspberry Pi or a desktop, etc). This file is made to be run directly, and basically just calls the functions from ROSA_

the file foreign_potato_master.py which contains a few classes that contain dictionaries of strings that are used by ROSA.py to reply to the user. I moved these into a separate file to make it easier for others to edit the output of my program

Brief file contents:

ROSA.py:

import speech_recognition as sr
import foreign_potato_master

try:
    import RPi.GPIO as GPIO  # type: ignore
    is_on_RPi = True
except ImportError:
    # note: Probably a more elegant solution somewhere
    # note: but this is what works for me atm
    is_on_RPi = False

class ROSA_:
    def __init__(self, json_path = None):
        ...

        self.title = foreign_potato_master.Text_Decorations.title
        self.symbols = foreign_potato_master.Text_Decorations.symbols

        self.activations = foreign_potato_master.Responses.activations
        self.keys = foreign_potato_master.Responses.keys
        self.responses = foreign_potato_master.Responses.responses
        self.prev_responses = foreign_potato_master.Responses.prev_responses

        ...

    def background_listening(self):
        ...

foreign_potato_master.py:

class Responses:
    activations = [...]
    keys = {...}
    responses = {...}
    prev_responses = {...}

class Text_Decorations:
    title = '...'
    symbols = {...}

...

main.py:

import ROSA

def main():
    ...

    obj = ROSA.ROSA_()
    speech = obj.background_listening()

    ...

if __name__ == '__main__': main()

init.py:

from ROSA import ROSA
from ROSA import foreign_potato_master

all of the files have some comments/docstrings/verison tags etc in the top, including the __init__.py

Directory Structure

ROSA
|- bin
    |- ...
|- docs
    |- ...
|- src
    |- ROSA
        |- __init__.py
        |- foreign_potato_master.py
        |- gpio.json
        |- main.py
        |- ROSA.py

My question:

What is the best way to import these files into each other?

# main.py
from . import ROSA
import .ROSA

Both of the above fail (ImportError: attempted relative import with no known parent package and SyntaxError: invalid syntax respectively)

# main.py
import ROSA

The above works when running as Python files, but not as compiled binaries (via pyinstaller):

Traceback (most recent call last):
  File "\\192.168.0.8\source\projects\ROSA\src\ROSA\main.py", line 39, in <module>
  File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
  File "ROSA\__init__.py", line 35, in <module>
  File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
  File "ROSA\ROSA.py", line 80, in <module>
ModuleNotFoundError: No module named 'foreign_potato_master'
[2520] Failed to execute script 'main' due to unhandled exception!

the above was run in Windows Sandbox

EDIT: probably should have clarified, the exe was built using the following batch script:

:: \ROSA

pyinstaller --noconfirm --log-level=WARN --clean ^
    --distpath ".\bin\bin" --workpath ".\bin\build" ^
    --name ROSA --onefile ^
    --paths ".\rosa-env\Lib\site-packages" ^
    --hidden-import pyi_splash ^
    --add-binary ".\src\ROSA\responses;.\responses" ^
    --splash ".\docs\ico\hotpot-ai.png" --icon ".\docs\ico\hotpot-ai.ico" ^
    .\src\ROSA\main.py

Finally (TL;DR):

So how can I import these files and have it work when run directly, when imported and when compiled to binary?


问:
Connection Airflow for Microsoft SQL Server didn't show at Airflow WebServer
I want to ask, how do you add new Connection choice in Airflow Webserver ? I can't see connection for Microsoft SQL Server

enter image description here

Thank you.

I've already follow step by step from this article.

https://girishdeshpande.medium.com/apache-airflow-on-docker-ms-sql-server-etl-dag-a8317da5cbcc

But I still cannot choose MSSQL (Microsoft SQL Server) connection on Airflow WebServer


问:
Drag and drop between overlapping views
I am trying to move items between two recyclerviews, one of them into a bottom sheet.

I get this working without problems if the bottom sheet is in the same LinearLayout that the target recylcerview, as you can see in this gif:

This is the working layout:

```<code><LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
app:layout_constraintBaseline_toTopOf="parent"
android:gravity="center_horizontal">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="25sp"
    android:paddingTop="20dp"
    android:paddingBottom="10dp"
    android:text="Target RecyclerView" />

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rvTop"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"/>

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

My problem is when I try it with the bottom sheet overlapping the main content, I mean using a FrameLayout or Relativelayout as parent. In this case onDrag() is not fired outside the bottom sheet. Not working:

Not working layout, using a RelativeLayout:

```<code>    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:orientation="vertical"
        app:layout_constraintBaseline_toTopOf="parent"
        android:gravity="center_horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:paddingTop="20dp"
            android:paddingBottom="10dp"
            android:text="Target RecyclerView" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvTop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="16dp"
            android:paddingBottom="16dp"/>

    </LinearLayout>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>
</code>```

I need the bottom sheet over the main content. Any idea?
Thanks!

Edit: Further investigations point that the problem is the CoordinatorLayout (which is a Bottom Sheet requirement). CoordinatorLayout is a "super-powered FrameLayout" and it acts at "top-level application decor", and I do not know why it does not allow onDrag events get views outside of CoordinatorLayout.

Workaround: For the moment my workaround is setting CorrdinatorLayout visibility to GONE when one of its views is dragged. This allow me to drop the view outside of CoordinatorLayout successfully, but I think should be some other way, some CoordinatorLayout parameter to allow dragging outside it.

Title: Drag and drop between overlapping views

Body:
I am trying to move items between two recyclerviews, one of them into a bottom sheet.

I get this working without problems if the bottom sheet is in the same LinearLayout that the target recylcerview, as you can see in this gif:

This is the working layout:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
app:layout_constraintBaseline_toTopOf="parent"
android:gravity="center_horizontal">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="25sp"
    android:paddingTop="20dp"
    android:paddingBottom="10dp"
    android:text="Target RecyclerView" />

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rvTop"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"/>

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</androidx.coordinatorlayout.widget.CoordinatorLayout>

My problem is when I try it with the bottom sheet overlapping the main content, I mean using a FrameLayout or Relativelayout as parent. In this case onDrag() is not fired outside the bottom sheet. Not working:

Not working layout, using a RelativeLayout:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:orientation="vertical"
        app:layout_constraintBaseline_toTopOf="parent"
        android:gravity="center_horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:paddingTop="20dp"
            android:paddingBottom="10dp"
            android:text="Target RecyclerView" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvTop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="16dp"
            android:paddingBottom="16dp"/>

    </LinearLayout>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>

I need the bottom sheet over the main content. Any idea?
Thanks!

Edit: Further investigations point that the problem is the CoordinatorLayout (which is a Bottom Sheet requirement). CoordinatorLayout is a "super-powered FrameLayout" and it acts at "top-level application decor", and I do not know why it does not allow onDrag events get views outside of CoordinatorLayout.

Workaround: For the moment my workaround is setting CorrdinatorLayout visibility to GONE when one of its views is dragged. This allow me to drop the view outside of CoordinatorLayout successfully, but I think should be some other way, some CoordinatorLayout parameter to allow dragging outside it.


问:
Plot non-continuous time series with Matplotlib as datetime not string
I'm trying to plot date vs num with these datasets

```<code>                    date    num
0   22/12/2022 09:09    7.92
1   22/12/2022 09:09    7.95
2   22/12/2022 09:09    7.98
3   22/12/2022 09:09    7.95
4   22/12/2022 09:09    7.93

... ... ...

4514    23/12/2022 14:48    5.68
4515    23/12/2022 14:48    5.68
4516    23/12/2022 14:48    5.69
4517    23/12/2022 14:48    5.70
4518    23/12/2022 14:48    5.66
</code>```

When the date column type is a string it gets the correct plot

```<code>data_1.plot(x='date',y='num')
plt.xticks(rotation = 45)
</code>```

However, when I converted the date to datetime, it plotted datetime which doesn't exist in data

```<code>data_1['date'] = pd.to_datetime(data_1['date'], format='%d/%m/%Y %H:%M')
data_1.plot(x='date',y='num')
plt.xticks(rotation = 45)
</code>```

Do you know what is the problem? I'm having a hard time searching for the solution, thank you

Updated
thanks for editing my question and giving me the solution, but still the solution is suggesting to convert to string not solve the problem using datetime

Body:
I'm trying to plot date vs num with these datasets

                    date    num
0   22/12/2022 09:09    7.92
1   22/12/2022 09:09    7.95
2   22/12/2022 09:09    7.98
3   22/12/2022 09:09    7.95
4   22/12/2022 09:09    7.93

... ... ...

4514    23/12/2022 14:48    5.68
4515    23/12/2022 14:48    5.68
4516    23/12/2022 14:48    5.69
4517    23/12/2022 14:48    5.70
4518    23/12/2022 14:48    5.66

When the date column type is a string it gets the correct plot

data_1.plot(x='date',y='num')
plt.xticks(rotation = 45)

However, when I converted the date to datetime, it plotted datetime which doesn't exist in data

data_1['date'] = pd.to_datetime(data_1['date'], format='%d/%m/%Y %H:%M')
data_1.plot(x='date',y='num')
plt.xticks(rotation = 45)

Do you know what is the problem? I'm having a hard time searching for the solution, thank you

Updated
thanks for editing my question and giving me the solution, but still the solution is suggesting to convert to string not solve the problem using datetime


问:
How to close fragment in fragment, when back button pressed?
The structure is like this.
viewPager2 -> MainFragment -> Fragment1 & Fragment2 & Fragment3

I made 3 pages ViewPager2. In ViewPager2(fragment), I made new Fragment.
I used FrameLayout at the 'MainFragment'.

```<code>tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override public void onTabSelected(TabLayout.Tab tab) {
    viewPager2.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
</code>```
```<code>FragmentTransaction ft = getChildFragmentManager().beginTransaction();
fragment = new MainFragment();
ft.add(R.id.layout_frame,fragment)
        .addToBackStack(null)
        .commit();
</code>```

The Fragment has button. The button enable to replace other Fragment like this.

```<code>button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
    fragment = new Fragment1();
    ft = getParentFragmentManager().beginTransaction();
    ft.replace(R.id.layout_frame,fragment)
            .addToBackStack(null)
            .commit();
    }
});
</code>```

Here, I want to replace the Fragment1 to MainFragment or close Fragment1, when back pressed.

How can I apply this in code?

I just don't know well. I'm junior developer. I need help. Thank you.

Body:
The structure is like this.
viewPager2 -> MainFragment -> Fragment1 & Fragment2 & Fragment3

I made 3 pages ViewPager2. In ViewPager2(fragment), I made new Fragment.
I used FrameLayout at the 'MainFragment'.

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override public void onTabSelected(TabLayout.Tab tab) {
    viewPager2.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

FragmentTransaction ft = getChildFragmentManager().beginTransaction();
fragment = new MainFragment();
ft.add(R.id.layout_frame,fragment)
        .addToBackStack(null)
        .commit();

The Fragment has button. The button enable to replace other Fragment like this.

button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
    fragment = new Fragment1();
    ft = getParentFragmentManager().beginTransaction();
    ft.replace(R.id.layout_frame,fragment)
            .addToBackStack(null)
            .commit();
    }
});

Here, I want to replace the Fragment1 to MainFragment or close Fragment1, when back pressed.

How can I apply this in code?

I just don't know well. I'm junior developer. I need help. Thank you.


问:
Yowsup registration failed " authkey, missing parm
Getting below error while register yowsup with cmd

```<code>yowsup-cli registration --requestcode sms --phone ********* --cc 49 --mcc 24 --mnc 07
</code>```

error:

```<code>status: fail
param: authkey
reason: missing_param
login: 91**********
</code>```

could not able to register on yowsup

Body:
Getting below error while register yowsup with cmd

yowsup-cli registration --requestcode sms --phone ********* --cc 49 --mcc 24 --mnc 07

error:

status: fail
param: authkey
reason: missing_param
login: 91**********

could not able to register on yowsup


问:
WebClient: exceeded limit on max bytes to buffer
I using spring-boot-starter-parent:2.7.7

I have the below config of webclient to call soap web services

```<code>@Bean
fun webClientXml(): WebClient {
    val httpClient = HttpClient.create()
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100000).doOnConnected {
            it.addHandlerLast(ReadTimeoutHandler(100))
            it.addHandlerLast(WriteTimeoutHandler(100))
        }.resolver(DefaultAddressResolverGroup.INSTANCE)

    val exchangeStrategies = ExchangeStrategies.builder().codecs {
        it.defaultCodecs().maxInMemorySize(16 * 1024 * 1024)
        it.customCodecs().register(Jaxb2SoapEncoder())
        it.customCodecs().register(Jaxb2SoapDecoder())
    }.build()

    return WebClient.builder()
        .codecs { it.defaultCodecs().maxInMemorySize(16 * 1024 * 1024) }
        .clientConnector(ReactorClientHttpConnector(httpClient))
        .exchangeStrategies(exchangeStrategies).build()
}
</code>```

application.yml

```<code>spring:
  elasticsearch:
    webclient:
      max-in-memory-size: 512MB
  codec:
    max-in-memory-size: 512MB
</code>```

config of Jaxb2SoapDecoder

```<code>class Jaxb2SoapDecoder : Jaxb2XmlDecoder() {

    override fun setMaxInMemorySize(byteCount: Int) {
        super.setMaxInMemorySize(16 * 1024 * 1024)
    }

    @Throws(DecodingException::class)
    override fun decode(dataBuffer: DataBuffer, targetType: ResolvableType, @Nullable mimeType: MimeType?, @Nullable hints: MutableMap<String, Any>?): Any {
        .....
    }

}
</code>```

config of Jaxb2SoapEncoder

```<code>class Jaxb2SoapEncoder : Encoder<Any> {

    private fun encode(value: Any, bufferFactory: DataBufferFactory): Flux<DataBuffer> {
        return Mono.fromCallable {
            var release = true
            val buffer = bufferFactory.allocateBuffer(1000000000)
            .....
        }.flux()

</code>```

}
}

when i invoke an api, i have the below error

org.springframework.web.reactive.function.client.WebClientResponseException:
200 OK from POST
xxxxxxxxx;
nested exception is
org.springframework.core.io.buffer.DataBufferLimitException: Exceeded
limit on max bytes to buffer : 262144

Body:
I using spring-boot-starter-parent:2.7.7

I have the below config of webclient to call soap web services

@Bean
fun webClientXml(): WebClient {
    val httpClient = HttpClient.create()
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100000).doOnConnected {
            it.addHandlerLast(ReadTimeoutHandler(100))
            it.addHandlerLast(WriteTimeoutHandler(100))
        }.resolver(DefaultAddressResolverGroup.INSTANCE)

    val exchangeStrategies = ExchangeStrategies.builder().codecs {
        it.defaultCodecs().maxInMemorySize(16 * 1024 * 1024)
        it.customCodecs().register(Jaxb2SoapEncoder())
        it.customCodecs().register(Jaxb2SoapDecoder())
    }.build()

    return WebClient.builder()
        .codecs { it.defaultCodecs().maxInMemorySize(16 * 1024 * 1024) }
        .clientConnector(ReactorClientHttpConnector(httpClient))
        .exchangeStrategies(exchangeStrategies).build()
}

application.yml

spring:
  elasticsearch:
    webclient:
      max-in-memory-size: 512MB
  codec:
    max-in-memory-size: 512MB

config of Jaxb2SoapDecoder

class Jaxb2SoapDecoder : Jaxb2XmlDecoder() {

    override fun setMaxInMemorySize(byteCount: Int) {
        super.setMaxInMemorySize(16 * 1024 * 1024)
    }

    @Throws(DecodingException::class)
    override fun decode(dataBuffer: DataBuffer, targetType: ResolvableType, @Nullable mimeType: MimeType?, @Nullable hints: MutableMap<String, Any>?): Any {
        .....
    }

}

config of Jaxb2SoapEncoder

class Jaxb2SoapEncoder : Encoder<Any> {

    private fun encode(value: Any, bufferFactory: DataBufferFactory): Flux<DataBuffer> {
        return Mono.fromCallable {
            var release = true
            val buffer = bufferFactory.allocateBuffer(1000000000)
            .....
        }.flux()

}
}

when i invoke an api, i have the below error

org.springframework.web.reactive.function.client.WebClientResponseException:
200 OK from POST
xxxxxxxxx;
nested exception is
org.springframework.core.io.buffer.DataBufferLimitException: Exceeded
limit on max bytes to buffer : 262144


问:
How to speed up USB msc host in stm32 or Enable DMA to speed up IO operations on usb?
Is there any way to speed up stm32 USB host applications.
For example I am running at 207 MHz in stm32f730v8
my USB clock is 48 MHz and I want to open a director.

It takes about 30 milliseconds on average. For a very complicated and hierarchal folders .

Does Enabling this line has any effect on the USB read or write speed.

```<code>hhcd_USB_OTG_FS.Init.dma_enable = ENABLE;
</code>```

Body:
Is there any way to speed up stm32 USB host applications.
For example I am running at 207 MHz in stm32f730v8
my USB clock is 48 MHz and I want to open a director.

It takes about 30 milliseconds on average. For a very complicated and hierarchal folders .

Does Enabling this line has any effect on the USB read or write speed.

hhcd_USB_OTG_FS.Init.dma_enable = ENABLE;


问:
Buffered-Input Stream
The below line is from the java documentation.

"Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full."

Can some-one explain what does the line mean especially the last part of it ..

Title: Buffered-Input Stream


问:
OSError : Cannot Find sndfile library
I am trying to deploy a Web Application in Streamit Cloud and am facing the Error.

```<code>ERROR: pip's dependency resolver does not currently
take into account all the packages that are installed.
This behaviour is the source of the following dependency conflicts.

tensorflow 2.11.0 requires protobuf<3.20,>=3.9.2, but you have
protobuf 3.20.1 which is incompatible.googleapis-common-protos
1.57.0 requires protobuf!=3.20.0,!=3.20.1,!=4.21.1,!=4.21.2,!=4.21.3,
!=4.21.4,!=4.21.5,<5.0.0dev,>=3.19.5, but you have protobuf 3.20.1
which is incompatible.Successfully installed protobuf-3.20.1

WARNING: You are using pip version 22.0.3; however, version 22.3.1 is available.
You should consider upgrading via the '/home/appuser/venv/bin/python -m pip install --upgrade pip' command.
────────────────────────────────────────────────────────────────────────────────────────[10:51:17]

Python dependencies were installed from /app/tvs_credit_app/requirements.txt using pip.[10:51:17]  Processed dependencies!  Stopping...Collecting usage statistics. To deactivate, set browser.gatherUsageStats to False.[10:51:21]  Updated app!2022-12-31 10:51:29.902 Uncaught app exceptionTraceback (most recent call last):  File "/home/appuser/venv/lib/python3.9/site-packages/soundfile.py", line 151, in <module>    raise OSError('sndfile library not found')OSError: sndfile library not foundDuring handling of the above exception, another exception occurred:Traceback (most recent call last):  File "/home/appuser/venv/lib/python3.9/site-packages/soundfile.py", line 178, in <module>    _snd = _ffi.dlopen(_os.path.join(_path, '_soundfile_data', _packaged_libname))OSError: cannot load library '/home/appuser/venv/lib/python3.9/site-packages/_soundfile_data/libsndfile.so': /home/appuser/venv/lib/python3.9/site-packages/_soundfile_data/libsndfile.so: cannot open shared object file: No such file or directoryDuring handling of the above exception, another exception occurred:
</code>```

There are two Errors : One is about protoBuff Version and the other is  that the system is not able to identify the sndfile (might be used in librosa)

The requirements.txt file is :

```<code>librosa
matplotlib
numpy
pandas
Pillow
scipy
seaborn
streamlit
tensorflow
</code>```

The app.py file looks like :

```<code>#Importing All Required Dependencies
import streamlit as st
from explore_page import show_explore_page
from predict_page import show_predict_page

page = st.sidebar.selectbox("Pages", ("Vehicle Price Estimator", "Explore More"))
if page=="Vehicle Price Estimator":
         show_predict_page()

else:
         show_explore_page()
</code>```

The predict page is :

```<code>#Importing All Required Dependencies

import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
from scipy import io, misc
import librosa
import tensorflow as tf
# import keras
from scipy.io.wavfile import read
from PIL import Image
import cv2
import pickle
@st.cache
def load_models():
    model = tf.keras.models.load_model('audio_analysis_model.hdf5')
    model_image = tf.keras.models.load_model('image_analysis_model.hdf5')
    with open('saved', 'rb') as file:
      data=pickle.load(file)
    return (model,model_image,data)

models=load_models()

def show_predict_page():
    st.title("Vehicle Price Estimator")

    # MODEL 1 - Takes an Audio Input and Classify whether the defect present is Inner defect, Outer defect or Roller defect

    uploaded_file = st.file_uploader("1. Upload an audio File of the Engine:")

    if uploaded_file is not None:
        # To read file as bytes:
        bytes_data = uploaded_file.getvalue()
        st.audio(bytes_data, format='audio/ogg')
        # For reference, example.wav file is  provided here
        frequency = 10000
        def feature_extract(l):
            y = np.array(l)
            sr = frequency
            mfcc = librosa.feature.mfcc(y=y, sr=sr)
            mfcc_scaled = np.mean(mfcc.T, axis=0)

            return mfcc_scaled
        a = read(uploaded_file)

        audio= np.array(a[1],dtype=float)

        test_dummy = feature_extract(audio)

        test_dummy = test_dummy.reshape(1, -1)
        model=models[0]
        ans = model.predict(test_dummy)
        # predicted class is stored in predicted_class
        predicted_class = np.argmax(ans, axis=-1)
        # Stores the parameter implying the defect detected through audio
        audio_defect=0.0
        if predicted_class==0:
          st.subheader('No Defect Detected!')
        elif predicted_class==1:
          st.subheader('Inner Defect Detected!')
          audio_defect=0.2
        elif predicted_class==2:
          st.subheader('Roller Defect Detected!')
          audio_defect=0.2
        else:
          st.subheader('Outer Defect Detected!')
          audio_defect=0.2

    # MODEL 2 - Takes an Image Input and Classify whether the defect present is Minor, Moderate or Severe

    uploaded_file2 = st.file_uploader("2. Upload an Image File of the Vehicle:")
    if uploaded_file2 is not None:
        # Reading the Image
        image = Image.open(uploaded_file2)
        st.image(image, caption='Car Image')

        pic = Image.open(uploaded_file2)
        # pix here denotes the resized image array
        pix = np.asarray(pic)
        pix = cv2.resize(pix, (80, 80))

        im_data=np.array(pix).reshape(80,80,3)
        im_data=im_data/255.0
         # model_image is the image analysis model
        model_image=models[1]
        ans_im=model_image.predict(im_data.reshape(1,80,80,3))
        pred_class_img = np.argmax(ans_im, axis=-1)
        # parameter indicating the defect int the image
        image_defect = 0.0
        if pred_class_img == 0:
          st.subheader('Minor Damage Detected!')
          image_defect=0.2
        elif pred_class_img == 1:
          st.subheader('Moderate Damage Detected!')
          image_defect= 0.3
        elif pred_class_img == 2:
          st.subheader('Severe Damage Detected!')
          image_defect= 0.4

    # The Same Logic can be easilt implemented for a Video Data as a Video is just several Frames of Images together
    uploaded_file3 = st.file_uploader("OR, Upload an Video File of the Vehicle:")
    if uploaded_file3 is not None:

     video_bytes = uploaded_file3.read()
     st.video(video_bytes)

    # MODEL 3 = Decision Tree Regression Model to do Data Analysis as it gave the best result among all

    # Designing all User Input Fields

    # data stores 4 items:
    # 1. A Data Analysis Model (MODEL 3)
    # 2. A Standard Scaler as the input values can be of very different Ranges
    # 3. A HashMap/Dictionary containing Model Name of Vehicle as keys and New Price of Vehicle as values
    # 4. A List of Names of Vehicles
    data=models[2]
    model = data["model"]
    scaling = data["scaling"]
    priceMp = data["priceMap"]
    model_names = data["names"]

    # Taking User Inputs

    col1, col2 = st.columns(2)

    with col1:
        name = st.selectbox( '3. Select Model of the Vehicle:', model_names)

        fuel = st.selectbox(
            '5. Select Fuel Type:',
            ('Petrol', 'Diesel', 'CNG'))

        mileage = st.number_input('7. Enter Mileage in kmpl:')

    with col2:
        location = st.selectbox(
            '4. Select nearest Location:',
            ('Chennai', 'Mumbai', 'Kochi', 'Delhi', 'Coimbatore','Kolkata', 'Jaipur', 'Ahmedabad', 'Hyderabad', 'Pune','Bangalore'))

        owners = st.selectbox(
            '6. Select Number of Owners:',
            ('1','2','3'))
        cc = st.number_input('8. Enter CC of the Engine:')

    years = st.slider('9. Numbers of years used: ', 0, 50, 1)
    kms = st.number_input('10. Kilometers Driven:')

    trans = st.selectbox(
            '11. Select Transmission Type:',
            ('Manual', 'Automatic'))

    # Converting Transmission Type, Location, Fuel into Integer Values
    trans_val=0
    if trans=='Manual' :
        trans_val=0
    else:
        trans_val=1
    new_price=priceMp[name]
    dict_cities = { 'Kochi':0,'Mumbai':1,'Coimbatore':2, 'Hyderabad':3, 'Pune':4, 'Kolkata':5, 'Delhi':6, 'Chennai': 7, 'Jaipur':8, 'Ahmedabad':9, 'Bangalore':10 }
    dict_fuel= {'Petrol':0,'Diesel':1,'CNG':2}
    loc_val = dict_cities[location]
    fuel_val = dict_fuel[fuel]

    # Scaling the Values and Testing the trained Model with it

    inp = np.array([[ loc_val, kms,   fuel_val, trans_val,   mileage,   cc,    new_price, years, owners ]])
    df2 = pd.DataFrame(inp, columns = ['Location','Kilometers_Driven', 'Fuel_Type','Transmission','Mileage', 'Engine', 'New_Price', 'Years', 'Owners'])
    transformed_data= scaling.transform(df2)
    inp=np.array(transformed_data)
    df2 = pd.DataFrame(inp, columns = ['Location','Kilometers_Driven', 'Fuel_Type','Transmission','Mileage', 'Engine', 'New_Price', 'Years', 'Owners'])
    outp = model.predict(df2)

    # Predicting the Final Price using all the outputs of the models

    if st.button('GET ESTIMATED PRICE'):
       ans=float(outp)
       ans = ans - (ans*audio_defect)-(ans*image_defect)
       if ans<=0.0:
          ans=2.2
       st.subheader(f"The Predicted Price is: Rs. {'%.2f'%ans} Lakhs.")
    else:
        st.write('')
</code>```

I tried adding versions in requirements.txt file but the errors remained. Then I got the reqirements.txt file using pipreqs but still it gives error. I think the requirements.txt file needs some modifications as the app is working well locally.
THe entire code link :
https://github.com/bikramghosh-ux/TVS_CREDIT_APP

Title: OSError : Cannot Find sndfile library

Body:
I am trying to deploy a Web Application in Streamit Cloud and am facing the Error.

ERROR: pip's dependency resolver does not currently
take into account all the packages that are installed.
This behaviour is the source of the following dependency conflicts.

tensorflow 2.11.0 requires protobuf<3.20,>=3.9.2, but you have
protobuf 3.20.1 which is incompatible.googleapis-common-protos
1.57.0 requires protobuf!=3.20.0,!=3.20.1,!=4.21.1,!=4.21.2,!=4.21.3,
!=4.21.4,!=4.21.5,<5.0.0dev,>=3.19.5, but you have protobuf 3.20.1
which is incompatible.Successfully installed protobuf-3.20.1

WARNING: You are using pip version 22.0.3; however, version 22.3.1 is available.
You should consider upgrading via the '/home/appuser/venv/bin/python -m pip install --upgrade pip' command.
────────────────────────────────────────────────────────────────────────────────────────[10:51:17]

Python dependencies were installed from /app/tvs_credit_app/requirements.txt using pip.[10:51:17]  Processed dependencies!  Stopping...Collecting usage statistics. To deactivate, set browser.gatherUsageStats to False.[10:51:21]  Updated app!2022-12-31 10:51:29.902 Uncaught app exceptionTraceback (most recent call last):  File "/home/appuser/venv/lib/python3.9/site-packages/soundfile.py", line 151, in <module>    raise OSError('sndfile library not found')OSError: sndfile library not foundDuring handling of the above exception, another exception occurred:Traceback (most recent call last):  File "/home/appuser/venv/lib/python3.9/site-packages/soundfile.py", line 178, in <module>    _snd = _ffi.dlopen(_os.path.join(_path, '_soundfile_data', _packaged_libname))OSError: cannot load library '/home/appuser/venv/lib/python3.9/site-packages/_soundfile_data/libsndfile.so': /home/appuser/venv/lib/python3.9/site-packages/_soundfile_data/libsndfile.so: cannot open shared object file: No such file or directoryDuring handling of the above exception, another exception occurred:

There are two Errors : One is about protoBuff Version and the other is  that the system is not able to identify the sndfile (might be used in librosa)

The requirements.txt file is :

librosa
matplotlib
numpy
pandas
Pillow
scipy
seaborn
streamlit
tensorflow

The app.py file looks like :

#Importing All Required Dependencies
import streamlit as st
from explore_page import show_explore_page
from predict_page import show_predict_page

page = st.sidebar.selectbox("Pages", ("Vehicle Price Estimator", "Explore More"))
if page=="Vehicle Price Estimator":
         show_predict_page()

else:
         show_explore_page()

The predict page is :

#Importing All Required Dependencies

import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
from scipy import io, misc
import librosa
import tensorflow as tf
# import keras
from scipy.io.wavfile import read
from PIL import Image
import cv2
import pickle
@st.cache
def load_models():
    model = tf.keras.models.load_model('audio_analysis_model.hdf5')
    model_image = tf.keras.models.load_model('image_analysis_model.hdf5')
    with open('saved', 'rb') as file:
      data=pickle.load(file)
    return (model,model_image,data)

models=load_models()

def show_predict_page():
    st.title("Vehicle Price Estimator")

    # MODEL 1 - Takes an Audio Input and Classify whether the defect present is Inner defect, Outer defect or Roller defect

    uploaded_file = st.file_uploader("1. Upload an audio File of the Engine:")

    if uploaded_file is not None:
        # To read file as bytes:
        bytes_data = uploaded_file.getvalue()
        st.audio(bytes_data, format='audio/ogg')
        # For reference, example.wav file is  provided here
        frequency = 10000
        def feature_extract(l):
            y = np.array(l)
            sr = frequency
            mfcc = librosa.feature.mfcc(y=y, sr=sr)
            mfcc_scaled = np.mean(mfcc.T, axis=0)

            return mfcc_scaled
        a = read(uploaded_file)

        audio= np.array(a[1],dtype=float)

        test_dummy = feature_extract(audio)

        test_dummy = test_dummy.reshape(1, -1)
        model=models[0]
        ans = model.predict(test_dummy)
        # predicted class is stored in predicted_class
        predicted_class = np.argmax(ans, axis=-1)
        # Stores the parameter implying the defect detected through audio
        audio_defect=0.0
        if predicted_class==0:
          st.subheader('No Defect Detected!')
        elif predicted_class==1:
          st.subheader('Inner Defect Detected!')
          audio_defect=0.2
        elif predicted_class==2:
          st.subheader('Roller Defect Detected!')
          audio_defect=0.2
        else:
          st.subheader('Outer Defect Detected!')
          audio_defect=0.2

    # MODEL 2 - Takes an Image Input and Classify whether the defect present is Minor, Moderate or Severe

    uploaded_file2 = st.file_uploader("2. Upload an Image File of the Vehicle:")
    if uploaded_file2 is not None:
        # Reading the Image
        image = Image.open(uploaded_file2)
        st.image(image, caption='Car Image')

        pic = Image.open(uploaded_file2)
        # pix here denotes the resized image array
        pix = np.asarray(pic)
        pix = cv2.resize(pix, (80, 80))

        im_data=np.array(pix).reshape(80,80,3)
        im_data=im_data/255.0
         # model_image is the image analysis model
        model_image=models[1]
        ans_im=model_image.predict(im_data.reshape(1,80,80,3))
        pred_class_img = np.argmax(ans_im, axis=-1)
        # parameter indicating the defect int the image
        image_defect = 0.0
        if pred_class_img == 0:
          st.subheader('Minor Damage Detected!')
          image_defect=0.2
        elif pred_class_img == 1:
          st.subheader('Moderate Damage Detected!')
          image_defect= 0.3
        elif pred_class_img == 2:
          st.subheader('Severe Damage Detected!')
          image_defect= 0.4

    # The Same Logic can be easilt implemented for a Video Data as a Video is just several Frames of Images together
    uploaded_file3 = st.file_uploader("OR, Upload an Video File of the Vehicle:")
    if uploaded_file3 is not None:

     video_bytes = uploaded_file3.read()
     st.video(video_bytes)

    # MODEL 3 = Decision Tree Regression Model to do Data Analysis as it gave the best result among all

    # Designing all User Input Fields

    # data stores 4 items:
    # 1. A Data Analysis Model (MODEL 3)
    # 2. A Standard Scaler as the input values can be of very different Ranges
    # 3. A HashMap/Dictionary containing Model Name of Vehicle as keys and New Price of Vehicle as values
    # 4. A List of Names of Vehicles
    data=models[2]
    model = data["model"]
    scaling = data["scaling"]
    priceMp = data["priceMap"]
    model_names = data["names"]

    # Taking User Inputs

    col1, col2 = st.columns(2)

    with col1:
        name = st.selectbox( '3. Select Model of the Vehicle:', model_names)

        fuel = st.selectbox(
            '5. Select Fuel Type:',
            ('Petrol', 'Diesel', 'CNG'))

        mileage = st.number_input('7. Enter Mileage in kmpl:')

    with col2:
        location = st.selectbox(
            '4. Select nearest Location:',
            ('Chennai', 'Mumbai', 'Kochi', 'Delhi', 'Coimbatore','Kolkata', 'Jaipur', 'Ahmedabad', 'Hyderabad', 'Pune','Bangalore'))

        owners = st.selectbox(
            '6. Select Number of Owners:',
            ('1','2','3'))
        cc = st.number_input('8. Enter CC of the Engine:')

    years = st.slider('9. Numbers of years used: ', 0, 50, 1)
    kms = st.number_input('10. Kilometers Driven:')

    trans = st.selectbox(
            '11. Select Transmission Type:',
            ('Manual', 'Automatic'))

    # Converting Transmission Type, Location, Fuel into Integer Values
    trans_val=0
    if trans=='Manual' :
        trans_val=0
    else:
        trans_val=1
    new_price=priceMp[name]
    dict_cities = { 'Kochi':0,'Mumbai':1,'Coimbatore':2, 'Hyderabad':3, 'Pune':4, 'Kolkata':5, 'Delhi':6, 'Chennai': 7, 'Jaipur':8, 'Ahmedabad':9, 'Bangalore':10 }
    dict_fuel= {'Petrol':0,'Diesel':1,'CNG':2}
    loc_val = dict_cities[location]
    fuel_val = dict_fuel[fuel]

    # Scaling the Values and Testing the trained Model with it

    inp = np.array([[ loc_val, kms,   fuel_val, trans_val,   mileage,   cc,    new_price, years, owners ]])
    df2 = pd.DataFrame(inp, columns = ['Location','Kilometers_Driven', 'Fuel_Type','Transmission','Mileage', 'Engine', 'New_Price', 'Years', 'Owners'])
    transformed_data= scaling.transform(df2)
    inp=np.array(transformed_data)
    df2 = pd.DataFrame(inp, columns = ['Location','Kilometers_Driven', 'Fuel_Type','Transmission','Mileage', 'Engine', 'New_Price', 'Years', 'Owners'])
    outp = model.predict(df2)

    # Predicting the Final Price using all the outputs of the models

    if st.button('GET ESTIMATED PRICE'):
       ans=float(outp)
       ans = ans - (ans*audio_defect)-(ans*image_defect)
       if ans<=0.0:
          ans=2.2
       st.subheader(f"The Predicted Price is: Rs. {'%.2f'%ans} Lakhs.")
    else:
        st.write('')

I tried adding versions in requirements.txt file but the errors remained. Then I got the reqirements.txt file using pipreqs but still it gives error. I think the requirements.txt file needs some modifications as the app is working well locally.
THe entire code link :
https://github.com/bikramghosh-ux/TVS_CREDIT_APP


问:
Time limit exceeded error Geeks for geeks
```<code>for i in arr:
            c=arr.count(i)
            if c==1:
                return i
</code>```

it was to count the number that comes only 1 time , but it showed error that time limit exceeded .
How can i optimize this code.

I tried using count method of string

Body:
for i in arr:
            c=arr.count(i)
            if c==1:
                return i

it was to count the number that comes only 1 time , but it showed error that time limit exceeded .
How can i optimize this code.

I tried using count method of string


问:
"...not a valid selector." Chrome Extension that will find a DIV and change it's text
I am creating a Chrome extension that will find specific text on this website and add to the end of the text a "|" character.

Currently, I have for testing purposes:

const test = document.querySelectorAll('div.w-full.text-left.text-[13px].font-semibold.text-white');

if (test){
  console.log(test)
  console.log(test.textContent);
}
```
<p>The DIV I am trying to find is specifically:</p>
<pre class="lang-html prettyprint-override"><code><div class="w-full text-left text-[13px] font-semibold  text-white">2,016,990</div>
</code>```

Multiple of these exact divs are inside the HTML file but with different numbers. I am trying to find all of them to add to the text.

Error

Now I am running into the error:

```<code>Uncaught DOMException: Failed to execute 'querySelector' on 'Document': 'div.w-full text-left text-[13px] font-semibold  text-white' is not a valid selector.
</code>```

I believe the issue is caused by the use of square brackets ([]) in the text-[13px] class.

TESTS

So far I have tried adding back slashes \ infront of both the brackets, however this throws the same exact error as before.

const elements = document.querySelectorAll('div.w-full.text-left.text-\[13px\].font-semibold.text-white');
```
<p>This was to hopefully treat the text-[13px] class as a regular class, rather than an attribute selector.</p>
<p>And removing the brackets entirely, <code>text-13px</code> instead of <code>text-[13px]</code>.</p>
<pre class="lang-js prettyprint-override"><code>const elements = document.querySelectorAll('div.w-full.text-left.text-13px.font-semibold.text-white');
</code>```

Now while this throws no errors, it doesn't return anything found.

```<code>NodeList []
length: 0
...
</code>```

And using variables to be added into the query selector. I found this from Brackets in Attribute not A valid Selector

var name = "13px";
const test = document.querySelectorAll(`div.w-full.text-left.text-["${name}"].font-semibold.text-white`);

```
<p>Throws the error "is not a vaild selector"</p>
```Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'div.w-full.text-left.text-["13px"].font-semibold.text-white' is not a valid selector.
```

Thanks :)

Body:
I am creating a Chrome extension that will find specific text on this website and add to the end of the text a "|" character.

Currently, I have for testing purposes:

const test = document.querySelectorAll('div.w-full.text-left.text-[13px].font-semibold.text-white');

if (test){
  console.log(test)
  console.log(test.textContent);
}

The DIV I am trying to find is specifically:

2,016,990

Multiple of these exact divs are inside the HTML file but with different numbers. I am trying to find all of them to add to the text.

Error

Now I am running into the error:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': 'div.w-full text-left text-[13px] font-semibold  text-white' is not a valid selector.

I believe the issue is caused by the use of square brackets ([]) in the text-[13px] class.

TESTS

So far I have tried adding back slashes \ infront of both the brackets, however this throws the same exact error as before.

const elements = document.querySelectorAll('div.w-full.text-left.text-\[13px\].font-semibold.text-white');

This was to hopefully treat the text-[13px] class as a regular class, rather than an attribute selector.

And removing the brackets entirely, text-13px instead of text-[13px].

const elements = document.querySelectorAll('div.w-full.text-left.text-13px.font-semibold.text-white');

Now while this throws no errors, it doesn't return anything found.

NodeList []
length: 0
...

And using variables to be added into the query selector. I found this from Brackets in Attribute not A valid Selector

var name = "13px";
const test = document.querySelectorAll(`div.w-full.text-left.text-["${name}"].font-semibold.text-white`);

Throws the error "is not a vaild selector"

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'div.w-full.text-left.text-["13px"].font-semibold.text-white' is not a valid selector.

Thanks :)


问:
having problem with installing PHP Debug extension in Virtual Studio Code on macOS
I'm trying to install the PHP Debug extension in Virtual Studio Code on macOS Ventura 13.1.
While following the instructions from https://xdebug.org/wizard, I am getting an error "Check for supported PHP versions...configure: error: not supported. Need a PHP version >= 7.2.0 and < 8.2.0 (found 8.2.0)" at step 6: Run ./configure

I have no problems installing PHP and Xdebug when I tried installing via homebrew outside of the VS Code app(followed instructions from https://xdebug.org/docs/install). When I typed php -v in terminal, it shows Xdebug version(3.2) and Zend OPcache v8.2.0.

I have tried copying xdebug.so module file from homebrew php app folder to AMPPS php app folder, configuring php.ini as the step 8 & 9 and reloading the AMPPS Apache web server. It still does not work, and I guess I need to run ./configure -> make to get proper xdebug.so file for AMPPS configuration settings.

UPDATE
I found the solution to use ./configure --with-php-config="path-to-AMPPS-php" but still having the problem of loading the Xdebug extension after reloading the web server.

Is there a way to use Xdebug with AMPPS and Virtual Studio Code together?


问:
I have a value (stree_adrress) in field (varchar) in mysql, i want to perform select query on that field with some value(incomplete) of that field
I want to implement functionality filter properties with its matching incomplete address..

I have a table name property , which has column 'stree_adrress'.

exe : 'street_address' : 'E-503, shree near SG high way' .

I want to find this when I just type 'SG high way' or 'shree near' or 'E-503' ,,, etc so that user does not have to add full adrress.

I am working with backend node JS, MySQL

Is it even possible ? I have no idea. or is it done by front end ?


问:
How to print Paskal's Triangle in Java
Can I print this with triangle shape in Java?

I tried to print this with only border "1"s:

```<code>int[][] matrix = new int[5][5];

for (int i = 0; i < 5; i++) {

    matrix[i][i] = 1;
    matrix[i][0] = 1;

}
</code>```

Title: How to print Paskal's Triangle in Java

Body:
Can I print this with triangle shape in Java?

I tried to print this with only border "1"s:

int[][] matrix = new int[5][5];

for (int i = 0; i < 5; i++) {

    matrix[i][i] = 1;
    matrix[i][0] = 1;

}


问:
How to use python's scapy or mitmproxy library to intercept html and modify content？
I am the owner of a small Internet cafe. Because of national laws and regulations, I must completely prohibit customers from accessing unhealthy content. However, some customers always try, and I know some pythons.

Can you use python's mitmproxy library or the scapy library to achieve the following functions?

When the computer receives any html, check whether it contains keywords. If yes, block and modify the content to "Please do not browse the prohibited content in this Internet cafe".

I just want to make the script into an exe and run it in the background. Don't let customers turn it off.

I have tried to use the mitmproxy library, but it must be started with the command line. Because English is not my native language and the documents are difficult to read, let alone the scan library. I am not a professional programmer at first, and I hope someone can help me


问:
Include related custom table in Dynamics 365 Plugin Registration Tool step
I have created a ServiceEndpoint with create, update and delete steps for the accounts table. The accounts table has a many-to-many relationship with a custom table. How do I create a step that will include the relationship records when changes are made to the accounts table?

I tried finding the relationship table in Dataverse, but it's not part of the list of tables.


问:
Cannot invoke "io.appium.java_client.ios.IOSDriver.findElementByAccessibilityId(String)" because "this.driver" is null

header 1
header 2

cell 1
cell 2

cell 3
cell 4

```<code>@RunWith(Cucumber.class)
public class SearchTest {
public IOSDriver
<MobileElement> driver;

@Before
public void setup() throws Exception {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");
caps.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone 11");
caps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");
caps.setCapability(MobileCapabilityType.UDID, "F17A9EE4-42A9-4A4D-9203-CA8F5C918215");
caps.setCapability("bundleId", "com.example.apple-samplecode.UICatalog");
URL url = new URL("http://0.0.0.0:4723/wd/hub");
driver= new IOSDriver\<\>(url, caps);`your text`
}

@Given("Search butonu tıklanır")
public void search_butonu_tıklanır() {
MobileElement el1 = (MobileElement) driver.findElementByAccessibilityId("SearchViewControllers");
el1.click();
}
</code>```

```<code> Cannot invoke "io.appium.java_client.ios.IOSDriver.findElementByAccessibilityId(String)" because "this.driver" is null
</code>```

Cannot invoke "io.appium.java_client.ios.IOSDriver.findElementByAccessibilityId(String)" because "this.driver" is null

Body:
header 1
header 2

cell 1
cell 2

cell 3
cell 4

@RunWith(Cucumber.class)
public class SearchTest {
public IOSDriver
<MobileElement> driver;

@Before
public void setup() throws Exception {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");
caps.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone 11");
caps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");
caps.setCapability(MobileCapabilityType.UDID, "F17A9EE4-42A9-4A4D-9203-CA8F5C918215");
caps.setCapability("bundleId", "com.example.apple-samplecode.UICatalog");
URL url = new URL("http://0.0.0.0:4723/wd/hub");
driver= new IOSDriver\<\>(url, caps);`your text`
}

@Given("Search butonu tıklanır")
public void search_butonu_tıklanır() {
MobileElement el1 = (MobileElement) driver.findElementByAccessibilityId("SearchViewControllers");
el1.click();
}

 Cannot invoke "io.appium.java_client.ios.IOSDriver.findElementByAccessibilityId(String)" because "this.driver" is null

Cannot invoke "io.appium.java_client.ios.IOSDriver.findElementByAccessibilityId(String)" because "this.driver" is null


问:
I am getting an errror while clicking the button of producing sound
Whenever I want to play the sound of the
word it doesn't play that sound and gives me an error of "The element has no supported sources".

Have a look into this please and let me know where I'm doing something wrong.

Html

```<code><audio id="micCheck"></audio>
<div id="container">
  <div id="box-1">
    <input
      type="text"
      placeholder="Type your word here.."
      id="searchWord"
    />
    <button id="btn">Search</button>
  </div>
  <div class="output" id="output"></div>
</div>
<script src="script.js"></script>
</code>```

Javascript

```<code>const searchButton = document.getElementById("btn");
const searchField = document.getElementById("searchWord");
const volume = document.getElementById("micCheck");
const url = "https://api.dictionaryapi.dev/api/v2/entries/en/";

searchButton.addEventListener("click", () => {
  let saveWord = searchField.value;
  fetch(`${url}${saveWord}`)
    .then((response) => response.json())
    .then((values) => {
      console.log(values);
      output.innerHTML = `
      <div id="box-2">
      <h3>${values[0].word}</h3>
      <button onclick="playSound()">
        <i class="fas fa-volume-up">
        </i>
      </button>
    </div>
    <div id="box-3">
      <p>${values[0].meanings[0].partOfSpeech}</p>
      <p> ${values[0].phonetic} </p>
    </div>

    <div id="box-4">
      <p>
      ${values[0].meanings[0].definitions[0].definition}</br>
      </p>
      <p id="paragraph-2">
    ${values[0].meanings[0].definitions[0].example || ""}
      </p>`;
      volume.setAttribute("src", `https:${values[0].phonetics[0].audio}`);
    });
});

function playSound() {
  volume.play();
}

</code>```

Body:
Whenever I want to play the sound of the
word it doesn't play that sound and gives me an error of "The element has no supported sources".

Have a look into this please and let me know where I'm doing something wrong.

Html

<audio id="micCheck"></audio>

    <input
      type="text"
      placeholder="Type your word here.."
      id="searchWord"
    />
    <button id="btn">Search</button>

Javascript

const searchButton = document.getElementById("btn");
const searchField = document.getElementById("searchWord");
const volume = document.getElementById("micCheck");
const url = "https://api.dictionaryapi.dev/api/v2/entries/en/";

searchButton.addEventListener("click", () => {
  let saveWord = searchField.value;
  fetch(`${url}${saveWord}`)
    .then((response) => response.json())
    .then((values) => {
      console.log(values);
      output.innerHTML = `

${values[0].word}

      <button onclick="playSound()">

      </button>

${values[0].meanings[0].partOfSpeech}

 ${values[0].phonetic}

      ${values[0].meanings[0].definitions[0].definition}

    ${values[0].meanings[0].definitions[0].example || ""}

`;
      volume.setAttribute("src", `https:${values[0].phonetics[0].audio}`);
    });
});

function playSound() {
  volume.play();
}


问:
Middleware Log Grpc Request
I have asp.net grpc service with middleware to block bad user Ip.
I would like to log bad user grpc request, at the moment i can access only with headers, body look like not work.</p>
```<code>public BlackIpService(RequestDelegate next, ILogger<BlackIpService> logger)
{
        _next = next;
        _logger = logger;
}

public async Task Invoke(HttpContext context)
{
  var currentIp = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
  if (BlackListIp.TryGetValue(currentIp, out var requestFailed))
  {
     var requestContent = new StringBuilder();

     requestContent.AppendLine($"method = {context.Request.Method.ToUpper()} " + $"path = {context.Request.Path}");
      foreach (var (headerKey, headerValue) in context.Request.Headers)
      {
          requestContent.AppendLine($"header = {headerKey}    value = {headerValue}");
      }
                    /*
                    context.Request.EnableBuffering();
                    var requestReader = new StreamReader(context.Request.Body);
                    var content = await requestReader.ReadToEndAsync(); //not work with GRPC
                    requestContent.AppendLine($"body = {content}");
                    */
      _logger.Log("BlackList", "Ip " + currentIp + " " + requestContent.ToString());
       context.Request.Body.Position = 0;
       return;
  }
 await _next.Invoke(context);
}
</code>```

Title: Middleware Log Grpc Request

Body:
I have asp.net grpc service with middleware to block bad user Ip.
I would like to log bad user grpc request, at the moment i can access only with headers, body look like not work.

public BlackIpService(RequestDelegate next, ILogger<BlackIpService> logger)
{
        _next = next;
        _logger = logger;
}

public async Task Invoke(HttpContext context)
{
  var currentIp = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
  if (BlackListIp.TryGetValue(currentIp, out var requestFailed))
  {
     var requestContent = new StringBuilder();

     requestContent.AppendLine($"method = {context.Request.Method.ToUpper()} " + $"path = {context.Request.Path}");
      foreach (var (headerKey, headerValue) in context.Request.Headers)
      {
          requestContent.AppendLine($"header = {headerKey}    value = {headerValue}");
      }
                    /*
                    context.Request.EnableBuffering();
                    var requestReader = new StreamReader(context.Request.Body);
                    var content = await requestReader.ReadToEndAsync(); //not work with GRPC
                    requestContent.AppendLine($"body = {content}");
                    */
      _logger.Log("BlackList", "Ip " + currentIp + " " + requestContent.ToString());
       context.Request.Body.Position = 0;
       return;
  }
 await _next.Invoke(context);
}