问:
How to debug numba error involving synchronization
NB - see 2nd comment below; actually underlying problem is a basic error with sync, duplicating CUDA kernels and memory access (one kernel doesn't execute entirely and the next doesn't get launched), as @RobertCrovella points out.

However, may be useful for googlers, because the error message I first got suggests something different.

I'm launching a cooperative group grid using numba CUDA, and am getting

numba.cuda.cudadrv.driver.CudaAPIError: [720] Call to cuLaunchCooperativeKernel results in CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE
```
<p>I'm wondering how to debug this. The code is just a unit test, with a grid of one (1x1) 32x32 block (which I get a warning for being too small). I have gotten this error in the past by stepping outside of array bounds, but I have eliminated that possibility in this case. It is during an array access that I get the error - if I comment out the access, I don't get it.</p>
<p>The code runs well in CUDASIM & everything is in-bounds.</p>
<p>It is unfortunately too complex (and proprietary) for me to paste as a whole. I am looking for a good debugging strategy first of all - and/or other things to check. (I will try to concoct a simpler example as well.)</p>
<p>[What I think <em>may</em> be happening is that the cooperative group code, which is relatively new in numba, is catching an error it shouldn't be catching....]</p>
<p><strong>UPDATE</strong></p>
<p>In fact, since I only have one block in this trivial example, I don't need to have a cooperative group at all. I've commented out the cooperative group code, and have the following case, which hangs:</p>
<pre class="lang-py prettyprint-override"><code>@cuda.jit(device=True)
def infer(
    minibatch: MiniBatchState,
    config: "TrainingConfig",
    model: "ModelData",
    train: "TrainingState",
) -> None:
    i_off_sample: int
    i_off_edge: int
    i_off_sample, i_off_edge = cuda.grid(2)  # type: ignore
    i_sample = minibatch.i_start_sample + i_off_sample
    n_samples = train.data.features.shape[0]
    # g: cuda.cg.GridGroup = cuda.cg.this_grid()  # type: ignore
    if (
        i_sample >= n_samples
        or i_off_sample > config.minibatch_size
        or i_off_edge >= config.model_width
    ):
        for i_level in range(model.n_levels):
            # g.sync()
            # g.sync()
            cuda.syncthreads()
            cuda.syncthreads()
        return
    else:
        for i_level in range(model.n_levels):
            # g.sync()
            # g.sync()
            cuda.syncthreads()
            cuda.syncthreads()
        return
</code>```

The arguments are all named tuples or arrays. This hangs. However, If I make the if contain a "True", then it doesn't hang! Am I misunderstanding synchronization? I thought each thread must synchronize the same # of times, not that each thread must synchronize using exactly the same line of code!?

Body:
NB - see 2nd comment below; actually underlying problem is a basic error with sync, duplicating CUDA kernels and memory access (one kernel doesn't execute entirely and the next doesn't get launched), as @RobertCrovella points out.

However, may be useful for googlers, because the error message I first got suggests something different.

I'm launching a cooperative group grid using numba CUDA, and am getting

numba.cuda.cudadrv.driver.CudaAPIError: [720] Call to cuLaunchCooperativeKernel results in CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE

I'm wondering how to debug this. The code is just a unit test, with a grid of one (1x1) 32x32 block (which I get a warning for being too small). I have gotten this error in the past by stepping outside of array bounds, but I have eliminated that possibility in this case. It is during an array access that I get the error - if I comment out the access, I don't get it.

The code runs well in CUDASIM & everything is in-bounds.

It is unfortunately too complex (and proprietary) for me to paste as a whole. I am looking for a good debugging strategy first of all - and/or other things to check. (I will try to concoct a simpler example as well.)

[What I think may be happening is that the cooperative group code, which is relatively new in numba, is catching an error it shouldn't be catching....]

UPDATE

In fact, since I only have one block in this trivial example, I don't need to have a cooperative group at all. I've commented out the cooperative group code, and have the following case, which hangs:

@cuda.jit(device=True)
def infer(
    minibatch: MiniBatchState,
    config: "TrainingConfig",
    model: "ModelData",
    train: "TrainingState",
) -> None:
    i_off_sample: int
    i_off_edge: int
    i_off_sample, i_off_edge = cuda.grid(2)  # type: ignore
    i_sample = minibatch.i_start_sample + i_off_sample
    n_samples = train.data.features.shape[0]
    # g: cuda.cg.GridGroup = cuda.cg.this_grid()  # type: ignore
    if (
        i_sample >= n_samples
        or i_off_sample > config.minibatch_size
        or i_off_edge >= config.model_width
    ):
        for i_level in range(model.n_levels):
            # g.sync()
            # g.sync()
            cuda.syncthreads()
            cuda.syncthreads()
        return
    else:
        for i_level in range(model.n_levels):
            # g.sync()
            # g.sync()
            cuda.syncthreads()
            cuda.syncthreads()
        return

The arguments are all named tuples or arrays. This hangs. However, If I make the if contain a "True", then it doesn't hang! Am I misunderstanding synchronization? I thought each thread must synchronize the same # of times, not that each thread must synchronize using exactly the same line of code!?


来源: stackexchange

问:
Docker container stops after a few seconds and shows 'in use (dangling)'
I am using Docker Desktop in Windows 10. I dockerized a Machine Learning project using Django as a web framework. Whenever I am going to run the image, it just runs for a few seconds and stops.  In Docker Desktop, it shows 'in use (dangling).'

I restarted the container and did other stuff but it did not work.

This is my Dockerfile:

```<code>FROM python

RUN mkdir /disease-prediction

WORKDIR /disease-prediction

ADD  . /disease-prediction

RUN pip install -r requirements.txt

EXPOSE 8000

CMD python manage.py runserver 0:8000
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Docker Desktop in Windows 10. I dockerized a Machine Learning project using Django as a web framework. Whenever I am going to run the image, it just runs for a few seconds and stops.  In Docker Desktop, it shows 'in use (dangling).'

I restarted the container and did other stuff but it did not work.

This is my Dockerfile:

FROM python

RUN mkdir /disease-prediction

WORKDIR /disease-prediction

ADD  . /disease-prediction

RUN pip install -r requirements.txt

EXPOSE 8000

CMD python manage.py runserver 0:8000


问:
Data not rebuild (restart) with rxdart
I do floating alert which is controlled with stream. The logic of that alert is, when tap the OK button on it to turn true to stream and then close.

I will show my codes, and please fix me what my logic wrong.

```<code> Widget dataState(
      AsyncSnapshot pinValidateSnapshot, ChangePinBloc changePinBloc) {
    if (pinValidateSnapshot.data == true) {
      WidgetsBinding.instance.addPostFrameCallback(
          (_) => Navigator.pushNamed(context, newConfirmPinRoute));
    }
    else if(pinValidateSnapshot.data == false){
      return StreamBuilder(
        stream: changePinBloc.alertStream,
        builder: (context, AsyncSnapshot<bool> alertSnapshot) {
          // if (alertSnapshot.hasError) {
          //   changePinBloc.onCloseAlert(false);
          // }
          return Positioned.fill(
            child: Visibility(
              visible: alertSnapshot.data != true,
              child: AlertContainerView(
                message: 'Same',
                onOKTap: () {
                  changePinBloc.onCloseAlert(true);
                },
              ),
            ),
          );
        },
      );
    }
    return Center(child: Text('WTF'),);
  }
</code>```

Here is codes in bloc class

```<code>final alertController = PublishSubject<bool>();
Stream<bool>get alertStream => alertController.stream;

  void onCloseAlert(bool flag) {
    alertController.sink.add(flag);

  }
</code>```

In here although pinValidateSnapshot change state, the alertSnapshot don't change start again from initial state, it always left previous state and alert not show again. How to do with that?

Title: Data not rebuild (restart) with rxdart

Body:
I do floating alert which is controlled with stream. The logic of that alert is, when tap the OK button on it to turn true to stream and then close.

I will show my codes, and please fix me what my logic wrong.

 Widget dataState(
      AsyncSnapshot pinValidateSnapshot, ChangePinBloc changePinBloc) {
    if (pinValidateSnapshot.data == true) {
      WidgetsBinding.instance.addPostFrameCallback(
          (_) => Navigator.pushNamed(context, newConfirmPinRoute));
    }
    else if(pinValidateSnapshot.data == false){
      return StreamBuilder(
        stream: changePinBloc.alertStream,
        builder: (context, AsyncSnapshot<bool> alertSnapshot) {
          // if (alertSnapshot.hasError) {
          //   changePinBloc.onCloseAlert(false);
          // }
          return Positioned.fill(
            child: Visibility(
              visible: alertSnapshot.data != true,
              child: AlertContainerView(
                message: 'Same',
                onOKTap: () {
                  changePinBloc.onCloseAlert(true);
                },
              ),
            ),
          );
        },
      );
    }
    return Center(child: Text('WTF'),);
  }

Here is codes in bloc class

final alertController = PublishSubject<bool>();
Stream<bool>get alertStream => alertController.stream;

  void onCloseAlert(bool flag) {
    alertController.sink.add(flag);

  }

In here although pinValidateSnapshot change state, the alertSnapshot don't change start again from initial state, it always left previous state and alert not show again. How to do with that?


问:
java.lang.NullPointerException in onCreate for some SDK versions
Recently I have updated the webview code and updated the apk on playstore. On update, some of the devices are not able to open the app; specifically Android 12 devices. Tried to take reference from other stack post to solve it, but nothing seems to address this specific issue.

Would appreciate if you go through the code below and let me know the issue.

Stack trace from playstore console-> Type: java.lang.RuntimeException

```<code>Exception java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3846)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4022)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:85)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2336)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:246)
  at android.app.ActivityThread.main (ActivityThread.java:8653)
  at java.lang.reflect.Method.invoke
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:602)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1130)
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebChromeClient(android.webkit.WebChromeClient)' on a null object reference
  at com.careturtle.patient1.MainActivity.onCreate (MainActivity.java:126)
  at android.app.Activity.performCreate (Activity.java:8207)
  at android.app.Activity.performCreate (Activity.java:8191)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1309)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3819)
</code>```

MainActivity

```<code>package com.example.test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

//import com.monstertechno.adblocker.AdBlockerWebView;
//import com.monstertechno.adblocker.util.AdBlocker;

public class MainActivity extends Activity {
    private static final int LOCATION_PERMISSION_CODE = 1;
    public static WebView mWebview;
    private android.content.Context Context;
    private static String getIntentValue = null;
    public static SharedPreferences sharedPreferences;
    private ProgressDialog mProgressDialog;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

        setContentView(R.layout.activity_main);
        Context = this;

        getIntentValue = getIntent().getStringExtra("value");

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String token1 = sharedPreferences.getString("regtoken", null);

        if (!DetectConnection.checkInternetConnection(this)) {
            Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
            finish(); //Calling this method to close this activity when internet is not available.
        } else {
            mWebview = (WebView) findViewById(R.id.webview1);
            //new AdBlockerWebView.init(this).initializeWebView(mWebview);
            WebSettings webSettings = mWebview.getSettings();
            if(welcome.action_var == "3"){
                mWebview.clearCache(true);
                Toast.makeText(getApplicationContext(), "App Reset Successful!", Toast.LENGTH_LONG).show();
                welcome.action_var = "0";
            }
            webSettings.setTextSize(WebSettings.TextSize.NORMAL);
            mWebview.getSettings().setJavaScriptEnabled(true);
            CookieManager.getInstance().setAcceptCookie(true);
            mWebview.setWebChromeClient(new WebChromeClient());
            //mWebview.setWebChromeClient(new JsPopupWebViewChrome());
            mWebview.setWebViewClient(new CustomWebViewClient());
            //mWebview.setWebViewClient(new Browser_home());

            webSettings.setJavaScriptEnabled(true);
            webSettings.setAllowFileAccess(true);
            webSettings.setAppCacheEnabled(true);

            //improve WebView Performance
            mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
            mWebview.getSettings().setAppCacheEnabled(true);
            mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            webSettings.setDomStorageEnabled(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            webSettings.setUseWideViewPort(true);
            webSettings.setSavePassword(true);
            webSettings.setSaveFormData(true);
            webSettings.setEnableSmoothTransition(true);

            //webSettings.setDomStorageEnabled(true);
            webSettings.setJavaScriptEnabled(true);

            // progress dialog
            mProgressDialog = new ProgressDialog(Context);

            if(welcome.action_var == "2") {
                mWebview.loadUrl("https://www.example.com/faq");
            }else if(welcome.action_var == "4") {
                mWebview.loadUrl("https://www.example.com/change_language");
            }else if (welcome.action_var == "666"){

                String qrLink = getIntent().getStringExtra("a");
                        mWebview.loadUrl(qrLink);
            }else{
                if (sharedPreferences.getBoolean("isKeyGenerated", true)) {

                    if (getIntentValue != null) {
                        mWebview.loadUrl("https://www.example.com/active_token");
                        getIntentValue = null;

                    } else {
                        mWebview.loadUrl("https://www.example.com/testa?reg=" + r);
                    }
                }
            }
        }

        mWebview.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("ALERT!")
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.cancel();
                            }
                        })
                        .setCancelable(false)
                        .create()
                        .show();

                // Indicate that we're handling this manually
                return true;
            }
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback){
                callback.invoke(origin, true, false);
            }
        });

        if ( Build.VERSION.SDK_INT >= 23){
            if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED  ){

                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_CODE);

                //return ;
            } else {
                if (canGetLocation()) {
                    //DO SOMETHING USEFUL HERE. ALL GPS PROVIDERS ARE CURRENTLY ENABLED
                } else {
                    //SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
            }
        }
    }

    public boolean canGetLocation() {
        boolean result = true;
        LocationManager lm;
        boolean gpsEnabled = false;
        boolean networkEnabled = false;

        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // exceptions will be thrown if provider is not permitted.
        try {
            gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }

        try {
            networkEnabled = lm
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        return gpsEnabled && networkEnabled;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
                if (canGetLocation()) {

                } else {
                    //SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }

            } else {
                Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // Function to load all URLs in same webview
    private class CustomWebViewClient extends WebViewClient {
        private static final long TIMEOUT = 25000L;

        private Handler timeoutHandler = new Handler();

  //      @SuppressWarnings("deprecation")
    //    @Override
    //    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

      //      return AdBlockerWebView.blockAds(view,url) ? AdBlocker.createEmptyResource() :
        //            super.shouldInterceptRequest(view, url);
//
  //      }

        private Runnable timeoutRunnable = new Runnable() {
            @Override
            public void run() {
                //show some error message here
                Intent intent = new Intent(MainActivity.this, noconnection.class);
                intent.putExtra("a", "mainactivity is source");
                startActivity(intent);
            }
        };

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!DetectConnection.checkInternetConnection(Context)) {
                Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
            } else if (url.contains("example.com")) {
                view.loadUrl(url);
            } else {
                Intent i =   new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
            }
            //} else if (url.contains("www.") && !url.contains("www.example.com")) {
            //    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            //    startActivity(i);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
            timeoutHandler.postDelayed(timeoutRunnable, TIMEOUT);

            //on page started, show loading page
            mProgressDialog.setCancelable(true);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            String currentPage = mWebview.getUrl();

            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("currentpage", currentPage);
            editor.apply();

            //after loading page, remove loading page

            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

            timeoutHandler.removeCallbacks(timeoutRunnable);
            mProgressDialog.dismiss();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            mWebview.clearCache(true);
            timeoutHandler.removeCallbacks(timeoutRunnable);

            Intent intent = new Intent(MainActivity.this, noconnection.class);
            intent.putExtra("a", "mainactivity is source");
            startActivity(intent);

            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            if(Build.VERSION.SDK_INT >= 21) {
                if (errorResponse.getStatusCode() != 404) {
                    mWebview.clearCache(true);
                    timeoutHandler.removeCallbacks(timeoutRunnable);

                    Intent intent = new Intent(MainActivity.this, noconnection.class);
                    intent.putExtra("a", "mainactivity is source");
                    startActivity(intent);

                    super.onReceivedHttpError(view, request, errorResponse);
                }
            }
        }
    }

    //-------------

    @Override
    public void onBackPressed() {

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String currenturl = sharedPreferences.getString("currentpage", null);

        mWebview.requestFocus();

        if (!DetectConnection.checkInternetConnection(Context)) {
            Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
        }else if (currenturl.contains("https://www.example.com/welcome") || currenturl.contains("https://www.example.com/login") || currenturl.contains("https://www.example.com/faq") || currenturl.contains("https://www.example.com/change_language")){
            Intent intent = new Intent(MainActivity.this, welcome.class);
            intent.putExtra("a", "mainactivity is source");
            startActivity(intent);
        }else {
            mWebview.goBack();
        }

        if (mWebview.canGoBack()) {
            if (!DetectConnection.checkInternetConnection(Context)) {
                Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public static void loadUrl(String key) {
        if (getIntentValue != null) {
            mWebview.loadUrl("https://www.example.com/welcome");
            getIntentValue = null;
        } else {
            try {
                mWebview.loadUrl("https://www.example.com/testa?reg=" + r);

            }catch (Exception e){

            }
        }
    }

    public static void reLoad() {
        mWebview.reload();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
    }
}
</code>```

Build.Gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 31
    buildToolsVersion '30.0.3'
    defaultConfig {
        applicationId "com.example.test"
        minSdkVersion 24
        targetSdkVersion 31
        versionCode 48
        versionName "5.6"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    implementation 'com.google.firebase:firebase-messaging:11.0.4'
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0'
    //implementation 'com.github.MonsterTechnoGits:WebViewAdblock:1.1'

  //  implementation 'me.dm7.barcodescanner:zxing:1.9'

    def camerax_version = "1.0.0-beta07"
    implementation "androidx.camera:camera-camera2:$camerax_version"
    implementation "androidx.camera:camera-lifecycle:$camerax_version"
    implementation "androidx.camera:camera-view:1.0.0-alpha14"

    implementation 'com.google.zxing:core:3.3.3'

    implementation 'com.journeyapps:zxing-android-embedded:4.1.0'

}

apply plugin: 'com.google.gms.google-services'
</code>```

Manifest

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>

    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.CAMERA2" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <meta-data
        android:name="android.webkit.WebView.EnableSafeBrowsing"
        android:value="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:allowBackup,icon,theme,label"
        android:usesCleartextTraffic="true">
        <activity
            android:name=".ScannerActivity"
            android:configChanges="orientation|screenSize"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".SimpleScannerActivity"
            android:configChanges="orientation|screenSize"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name="com.example.test.welcome"
            android:configChanges="orientation|screenSize"
            android:screenOrientation="portrait"
            android:exported="true"
            android:launchMode="singleTop"
            tools:replace="android:screenOrientation"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:scheme="http"
                    android:host="www.example.com"
                    />
            </intent-filter>
        </activity>
        <!-- http://play.google.com/store/apps/details?id=com.example.test -->
        <!-- Accepts URIs that begin with "http://example.com/test/test1" -->

        <!--  <data android:scheme="myapp" />
                         <data android:scheme="http" android:host="careturtle1.com" android:pathPrefix="/barcode"/>

         <intent-filter
                android:label="@string/app_name">

                <action android:name="android.intent.action.VIEW" />
        <data
            android:host="play.google.com/store/apps/details?id="
            android:pathPrefix="/com.example.test"
            android:scheme="http"/>
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>

         -->

        <service android:name=".MyFirebaseInstanceId"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".FcmMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_icon" />

        <activity
            android:name=".noconnection"
            android:screenOrientation="portrait"></activity>
    </application>

</manifest>
</code>```

Body:
Recently I have updated the webview code and updated the apk on playstore. On update, some of the devices are not able to open the app; specifically Android 12 devices. Tried to take reference from other stack post to solve it, but nothing seems to address this specific issue.

Would appreciate if you go through the code below and let me know the issue.

Stack trace from playstore console-> Type: java.lang.RuntimeException

Exception java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3846)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4022)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:85)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2336)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:246)
  at android.app.ActivityThread.main (ActivityThread.java:8653)
  at java.lang.reflect.Method.invoke
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:602)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1130)
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebChromeClient(android.webkit.WebChromeClient)' on a null object reference
  at com.careturtle.patient1.MainActivity.onCreate (MainActivity.java:126)
  at android.app.Activity.performCreate (Activity.java:8207)
  at android.app.Activity.performCreate (Activity.java:8191)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1309)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3819)

MainActivity

package com.example.test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

//import com.monstertechno.adblocker.AdBlockerWebView;
//import com.monstertechno.adblocker.util.AdBlocker;

public class MainActivity extends Activity {
    private static final int LOCATION_PERMISSION_CODE = 1;
    public static WebView mWebview;
    private android.content.Context Context;
    private static String getIntentValue = null;
    public static SharedPreferences sharedPreferences;
    private ProgressDialog mProgressDialog;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

        setContentView(R.layout.activity_main);
        Context = this;

        getIntentValue = getIntent().getStringExtra("value");

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String token1 = sharedPreferences.getString("regtoken", null);

        if (!DetectConnection.checkInternetConnection(this)) {
            Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
            finish(); //Calling this method to close this activity when internet is not available.
        } else {
            mWebview = (WebView) findViewById(R.id.webview1);
            //new AdBlockerWebView.init(this).initializeWebView(mWebview);
            WebSettings webSettings = mWebview.getSettings();
            if(welcome.action_var == "3"){
                mWebview.clearCache(true);
                Toast.makeText(getApplicationContext(), "App Reset Successful!", Toast.LENGTH_LONG).show();
                welcome.action_var = "0";
            }
            webSettings.setTextSize(WebSettings.TextSize.NORMAL);
            mWebview.getSettings().setJavaScriptEnabled(true);
            CookieManager.getInstance().setAcceptCookie(true);
            mWebview.setWebChromeClient(new WebChromeClient());
            //mWebview.setWebChromeClient(new JsPopupWebViewChrome());
            mWebview.setWebViewClient(new CustomWebViewClient());
            //mWebview.setWebViewClient(new Browser_home());

            webSettings.setJavaScriptEnabled(true);
            webSettings.setAllowFileAccess(true);
            webSettings.setAppCacheEnabled(true);

            //improve WebView Performance
            mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
            mWebview.getSettings().setAppCacheEnabled(true);
            mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            webSettings.setDomStorageEnabled(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            webSettings.setUseWideViewPort(true);
            webSettings.setSavePassword(true);
            webSettings.setSaveFormData(true);
            webSettings.setEnableSmoothTransition(true);

            //webSettings.setDomStorageEnabled(true);
            webSettings.setJavaScriptEnabled(true);

            // progress dialog
            mProgressDialog = new ProgressDialog(Context);

            if(welcome.action_var == "2") {
                mWebview.loadUrl("https://www.example.com/faq");
            }else if(welcome.action_var == "4") {
                mWebview.loadUrl("https://www.example.com/change_language");
            }else if (welcome.action_var == "666"){

                String qrLink = getIntent().getStringExtra("a");
                        mWebview.loadUrl(qrLink);
            }else{
                if (sharedPreferences.getBoolean("isKeyGenerated", true)) {

                    if (getIntentValue != null) {
                        mWebview.loadUrl("https://www.example.com/active_token");
                        getIntentValue = null;

                    } else {
                        mWebview.loadUrl("https://www.example.com/testa?reg=" + r);
                    }
                }
            }
        }

        mWebview.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("ALERT!")
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.cancel();
                            }
                        })
                        .setCancelable(false)
                        .create()
                        .show();

                // Indicate that we're handling this manually
                return true;
            }
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback){
                callback.invoke(origin, true, false);
            }
        });

        if ( Build.VERSION.SDK_INT >= 23){
            if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED  ){

                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_CODE);

                //return ;
            } else {
                if (canGetLocation()) {
                    //DO SOMETHING USEFUL HERE. ALL GPS PROVIDERS ARE CURRENTLY ENABLED
                } else {
                    //SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
            }
        }
    }

    public boolean canGetLocation() {
        boolean result = true;
        LocationManager lm;
        boolean gpsEnabled = false;
        boolean networkEnabled = false;

        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // exceptions will be thrown if provider is not permitted.
        try {
            gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }

        try {
            networkEnabled = lm
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        return gpsEnabled && networkEnabled;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
                if (canGetLocation()) {

                } else {
                    //SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }

            } else {
                Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // Function to load all URLs in same webview
    private class CustomWebViewClient extends WebViewClient {
        private static final long TIMEOUT = 25000L;

        private Handler timeoutHandler = new Handler();

  //      @SuppressWarnings("deprecation")
    //    @Override
    //    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

      //      return AdBlockerWebView.blockAds(view,url) ? AdBlocker.createEmptyResource() :
        //            super.shouldInterceptRequest(view, url);
//
  //      }

        private Runnable timeoutRunnable = new Runnable() {
            @Override
            public void run() {
                //show some error message here
                Intent intent = new Intent(MainActivity.this, noconnection.class);
                intent.putExtra("a", "mainactivity is source");
                startActivity(intent);
            }
        };

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!DetectConnection.checkInternetConnection(Context)) {
                Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
            } else if (url.contains("example.com")) {
                view.loadUrl(url);
            } else {
                Intent i =   new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
            }
            //} else if (url.contains("www.") && !url.contains("www.example.com")) {
            //    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            //    startActivity(i);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
            timeoutHandler.postDelayed(timeoutRunnable, TIMEOUT);

            //on page started, show loading page
            mProgressDialog.setCancelable(true);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            String currentPage = mWebview.getUrl();

            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("currentpage", currentPage);
            editor.apply();

            //after loading page, remove loading page

            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

            timeoutHandler.removeCallbacks(timeoutRunnable);
            mProgressDialog.dismiss();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            mWebview.clearCache(true);
            timeoutHandler.removeCallbacks(timeoutRunnable);

            Intent intent = new Intent(MainActivity.this, noconnection.class);
            intent.putExtra("a", "mainactivity is source");
            startActivity(intent);

            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            if(Build.VERSION.SDK_INT >= 21) {
                if (errorResponse.getStatusCode() != 404) {
                    mWebview.clearCache(true);
                    timeoutHandler.removeCallbacks(timeoutRunnable);

                    Intent intent = new Intent(MainActivity.this, noconnection.class);
                    intent.putExtra("a", "mainactivity is source");
                    startActivity(intent);

                    super.onReceivedHttpError(view, request, errorResponse);
                }
            }
        }
    }

    //-------------

    @Override
    public void onBackPressed() {

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String currenturl = sharedPreferences.getString("currentpage", null);

        mWebview.requestFocus();

        if (!DetectConnection.checkInternetConnection(Context)) {
            Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
        }else if (currenturl.contains("https://www.example.com/welcome") || currenturl.contains("https://www.example.com/login") || currenturl.contains("https://www.example.com/faq") || currenturl.contains("https://www.example.com/change_language")){
            Intent intent = new Intent(MainActivity.this, welcome.class);
            intent.putExtra("a", "mainactivity is source");
            startActivity(intent);
        }else {
            mWebview.goBack();
        }

        if (mWebview.canGoBack()) {
            if (!DetectConnection.checkInternetConnection(Context)) {
                Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public static void loadUrl(String key) {
        if (getIntentValue != null) {
            mWebview.loadUrl("https://www.example.com/welcome");
            getIntentValue = null;
        } else {
            try {
                mWebview.loadUrl("https://www.example.com/testa?reg=" + r);

            }catch (Exception e){

            }
        }
    }

    public static void reLoad() {
        mWebview.reload();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
    }
}

Build.Gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 31
    buildToolsVersion '30.0.3'
    defaultConfig {
        applicationId "com.example.test"
        minSdkVersion 24
        targetSdkVersion 31
        versionCode 48
        versionName "5.6"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    implementation 'com.google.firebase:firebase-messaging:11.0.4'
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0'
    //implementation 'com.github.MonsterTechnoGits:WebViewAdblock:1.1'

  //  implementation 'me.dm7.barcodescanner:zxing:1.9'

    def camerax_version = "1.0.0-beta07"
    implementation "androidx.camera:camera-camera2:$camerax_version"
    implementation "androidx.camera:camera-lifecycle:$camerax_version"
    implementation "androidx.camera:camera-view:1.0.0-alpha14"

    implementation 'com.google.zxing:core:3.3.3'

    implementation 'com.journeyapps:zxing-android-embedded:4.1.0'

}

apply plugin: 'com.google.gms.google-services'

Manifest

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>

    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.CAMERA2" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <meta-data
        android:name="android.webkit.WebView.EnableSafeBrowsing"
        android:value="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:allowBackup,icon,theme,label"
        android:usesCleartextTraffic="true">
        <activity
            android:name=".ScannerActivity"
            android:configChanges="orientation|screenSize"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name=".SimpleScannerActivity"
            android:configChanges="orientation|screenSize"
            android:screenOrientation="portrait"></activity>
        <activity
            android:name="com.example.test.welcome"
            android:configChanges="orientation|screenSize"
            android:screenOrientation="portrait"
            android:exported="true"
            android:launchMode="singleTop"
            tools:replace="android:screenOrientation"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:scheme="http"
                    android:host="www.example.com"
                    />
            </intent-filter>
        </activity>

        <service android:name=".MyFirebaseInstanceId"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".FcmMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_icon" />

        <activity
            android:name=".noconnection"
            android:screenOrientation="portrait"></activity>
    </application>

</manifest>


问:
Get resource icon from exe generated from pyinstaller
I'm generating an .exe using pyinstaller, but I'm not able to include an file without resources.

command line:

pyinstaller --onefile --icon=./resources/image/icon.ico --add-data="./resources/data.txt;data" ./src/MainGui.py

When I try to open the file ./data/data.txt or data/data.txt or data.txt , it says that the file was not found. The icon was changed sucessfully.

A part of the pyinstaller output:

```<code>447 INFO: Writing RT_GROUP_ICON 0 resource with 104 bytes
448 INFO: Writing RT_ICON 1 resource with 3752 bytes
448 INFO: Writing RT_ICON 2 resource with 2216 bytes
448 INFO: Writing RT_ICON 3 resource with 1384 bytes
449 INFO: Writing RT_ICON 4 resource with 37019 bytes
449 INFO: Writing RT_ICON 5 resource with 9640 bytes
449 INFO: Writing RT_ICON 6 resource with 4264 bytes
450 INFO: Writing RT_ICON 7 resource with 1128 bytes
454 INFO: Copying 0 resources to EXE
454 INFO: Embedding manifest in EXE
</code>```

In line 454 says that 0 resources are copying.

Can I print inside the exe file to know the structure?

Body:
I'm generating an .exe using pyinstaller, but I'm not able to include an file without resources.

command line:

pyinstaller --onefile --icon=./resources/image/icon.ico --add-data="./resources/data.txt;data" ./src/MainGui.py

When I try to open the file ./data/data.txt or data/data.txt or data.txt , it says that the file was not found. The icon was changed sucessfully.

A part of the pyinstaller output:

447 INFO: Writing RT_GROUP_ICON 0 resource with 104 bytes
448 INFO: Writing RT_ICON 1 resource with 3752 bytes
448 INFO: Writing RT_ICON 2 resource with 2216 bytes
448 INFO: Writing RT_ICON 3 resource with 1384 bytes
449 INFO: Writing RT_ICON 4 resource with 37019 bytes
449 INFO: Writing RT_ICON 5 resource with 9640 bytes
449 INFO: Writing RT_ICON 6 resource with 4264 bytes
450 INFO: Writing RT_ICON 7 resource with 1128 bytes
454 INFO: Copying 0 resources to EXE
454 INFO: Embedding manifest in EXE

In line 454 says that 0 resources are copying.

Can I print inside the exe file to know the structure?


问:
Android Stripe library causes a build failure for an empty project
I am trying to integrate the Stripe library for payment with the dependency line:

```<code>implementation 'com.stripe:stripe-android:20.17.0'
</code>```

and gets this error when building the project:

```<code>Could not resolve all files for configuration ':app:debugCompileClasspath'.
   > Failed to transform lifecycle-livedata-2.5.1.aar (androidx.lifecycle:lifecycle-livedata:2.5.1) to match attributes {artifactType=android-databinding, org.gradle.status=release}.
      > Could not find lifecycle-livedata-2.5.1.aar (androidx.lifecycle:lifecycle-livedata:2.5.1).
</code>```

Compile SDK = 33

Gradle plugin version = 7.3.1

Gradle version = 7.4

Android Studio Dolphin

Body:
I am trying to integrate the Stripe library for payment with the dependency line:

implementation 'com.stripe:stripe-android:20.17.0'

and gets this error when building the project:

Could not resolve all files for configuration ':app:debugCompileClasspath'.
   > Failed to transform lifecycle-livedata-2.5.1.aar (androidx.lifecycle:lifecycle-livedata:2.5.1) to match attributes {artifactType=android-databinding, org.gradle.status=release}.
      > Could not find lifecycle-livedata-2.5.1.aar (androidx.lifecycle:lifecycle-livedata:2.5.1).

Compile SDK = 33

Gradle plugin version = 7.3.1

Gradle version = 7.4

Android Studio Dolphin


问:
Couldn't perform click, button not found in: 'click on "OBFormFieldSelectInputRequired"'
Recently, I registered with Testrigor and am using its Free version. We need to test dynamic web applications in Testrigor, then we write scripts for the same. In our Application 3 field use same class selector ,so when i used class in script for enter value in that class but that time Test rigor entered value in another field because of same class,i was try to resolve issue using Name And id Locator but Issue not Solved.
I am getting the following error in one field .
Couldn't perform click, button not found in: 'click on "OBFormFieldSelectInputRequired"'.
Please check attached screenshot.

I'm Tried with Name And Id locator


问:
JS debounce: how does the timer persist between calls
I'm looking at this simple piece of debounce code:

```<code>function debounce(event, wait) {
    let timer = null;
    return function (...args) {
      clearTimeout(timer);
        timer = setTimeout(() => {
            event.apply(this, args)
        }, wait)
    }
}
</code>```

And suppose we use it in an eventListener

```<code>window.addEventListener('resize', debounce(handler, 200))

</code>```

Now what I find confusing is that if the resize event gets fired multiple times, how does the timer inside debounce gets persisted between the calls? The reason I say it gets persisted is that if the same event is triggered within the delay, the timer is
supposed to be cleared. But since it can be cleared, that means it gets persisted between multiple calls?

Shouldn't it be every time the resize function is fired, we call debounce once, and it will give us a new "closure"?

I think I might have some misunderstanding with how eventlistener handle its callback function, so please shine some light on this!

Body:
I'm looking at this simple piece of debounce code:

function debounce(event, wait) {
    let timer = null;
    return function (...args) {
      clearTimeout(timer);
        timer = setTimeout(() => {
            event.apply(this, args)
        }, wait)
    }
}

And suppose we use it in an eventListener

window.addEventListener('resize', debounce(handler, 200))

Now what I find confusing is that if the resize event gets fired multiple times, how does the timer inside debounce gets persisted between the calls? The reason I say it gets persisted is that if the same event is triggered within the delay, the timer is
supposed to be cleared. But since it can be cleared, that means it gets persisted between multiple calls?

Shouldn't it be every time the resize function is fired, we call debounce once, and it will give us a new "closure"?

I think I might have some misunderstanding with how eventlistener handle its callback function, so please shine some light on this!


问:
Why is my DataFrame printing out horizontally?
I am trying to print the dataFrame in the end and the columns are not vertical. The numbers are horizontal:

```<code># Data Manipulation
import pandas as pd
import numpy as np

# DataViz
import seaborn as sns
import matplotlib.pyplot as plt

# Modeling
from sklearn.model_selection import train_test_split
#from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor

#In order to prevent data leakage (when components of the training dataset leak to the #response variable and influences the model fitting, creating a wrong sensation of good #fit), we're spliting the data now, before any other formatting.
df = pd.DataFrame({'x':[1,3,3,4,5,8,10,9],'y': [2,4,6,8,10,12,14,16]})

x = df[['x']].to_numpy()
y = df[['y']].to_numpy()

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size= 0.2, random_state=12)

#x.reshape(-1,1)
#y_test.reshape(-1,1)

print(f'XTrain yTrain shapes: {X_train.shape, y_train.shape}  \n XTest  yTest shapes: {X_test.shape, y_test.shape}')

# Instance and fit
knn_model = KNeighborsRegressor(n_neighbors=5).fit(X_train, y_train)

# Score
score_knn = knn_model.score(X_test, y_test)
score_knn

# Predictions--Use the test data to evlauate the model's performance
preds = knn_model.predict(X_test)
preds
# Performance
performance = pd.DataFrame({ 'True count lost': [y_test],
                            'Prediction': [preds],
                            'Error': [y_test - preds]})
# View
performance

</code>```

I ran the code above and instead of seeing a chart with values vertically, I received horizontal values and strange numbers added in. Her is the output:

```<code>XTrain yTrain shapes: ((6, 1), (6, 1))
 XTest  yTest shapes: ((2, 1), (2, 1))
</code>```

True count           lost             Prediction  Error

0   [[10], [14]] [[9.2], [9.2]] [[0.8000000000000007], [4.800000000000001]]

But I should get this:

True Value        Prediction    Error

10                        9.2               0.8

14                         9.2               4.8

Body:
I am trying to print the dataFrame in the end and the columns are not vertical. The numbers are horizontal:

# Data Manipulation
import pandas as pd
import numpy as np

# DataViz
import seaborn as sns
import matplotlib.pyplot as plt

# Modeling
from sklearn.model_selection import train_test_split
#from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor

#In order to prevent data leakage (when components of the training dataset leak to the #response variable and influences the model fitting, creating a wrong sensation of good #fit), we're spliting the data now, before any other formatting.
df = pd.DataFrame({'x':[1,3,3,4,5,8,10,9],'y': [2,4,6,8,10,12,14,16]})

x = df[['x']].to_numpy()
y = df[['y']].to_numpy()

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size= 0.2, random_state=12)

#x.reshape(-1,1)
#y_test.reshape(-1,1)

print(f'XTrain yTrain shapes: {X_train.shape, y_train.shape}  \n XTest  yTest shapes: {X_test.shape, y_test.shape}')

# Instance and fit
knn_model = KNeighborsRegressor(n_neighbors=5).fit(X_train, y_train)

# Score
score_knn = knn_model.score(X_test, y_test)
score_knn

# Predictions--Use the test data to evlauate the model's performance
preds = knn_model.predict(X_test)
preds
# Performance
performance = pd.DataFrame({ 'True count lost': [y_test],
                            'Prediction': [preds],
                            'Error': [y_test - preds]})
# View
performance

I ran the code above and instead of seeing a chart with values vertically, I received horizontal values and strange numbers added in. Her is the output:

XTrain yTrain shapes: ((6, 1), (6, 1))
 XTest  yTest shapes: ((2, 1), (2, 1))

True count           lost             Prediction  Error

0   [[10], [14]] [[9.2], [9.2]] [[0.8000000000000007], [4.800000000000001]]

But I should get this:

True Value        Prediction    Error

10                        9.2               0.8

14                         9.2               4.8


问:
How to delete line between div & svg
How to fix it?
the line between div and svg

so the problem is, line, and i just started making wave svg, and i want to combine with div white

the line, svg and div

this with pointer

second with pointer

i want to solve this

Title: How to delete line between div & svg


问:
Django Form resubmit issue when press back button
Django Form submit and link to the main page but when press back button, it shows data and ready to submits again. Views.py is here</p>
```<code>def contact(request):
    if request.method == "POST":
        form = ContactsForm(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            form = ContactsForm()
            messages.success(request, 'Contact request submitted successfully.')
            return HttpResponseRedirect(request.path_info)

        else:
            messages.error(request, 'Invalid form submission.')

    else:
        form = ContactsForm()

    projects = Projects.objects.filter(status=1).order_by('-updated_at')

    return render(request,'main/contact.html',{'contact':'current','projects':projects,'form':form})
</code>```

Body:
Django Form submit and link to the main page but when press back button, it shows data and ready to submits again. Views.py is here

def contact(request):
    if request.method == "POST":
        form = ContactsForm(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            form = ContactsForm()
            messages.success(request, 'Contact request submitted successfully.')
            return HttpResponseRedirect(request.path_info)

        else:
            messages.error(request, 'Invalid form submission.')

    else:
        form = ContactsForm()

    projects = Projects.objects.filter(status=1).order_by('-updated_at')

    return render(request,'main/contact.html',{'contact':'current','projects':projects,'form':form})


问:
pyproject.toml exclude some Python sources .py from data directory
I have a data folder which contains a script which is only needed during development preparing some data.

```<code>|--mypackage
|--mypackage/data
|--mypackage/data/prepare.py
</code>```

The problem is that this py file is included in the package. I tried to exclude it with:

[tool.setuptools.packages.find]
where = ["."]
exclude = ["mypackage*data*py"]
```

But this does not seem the correct syntax. Or maybe it is not supported to exclude py files?

Body:
I have a data folder which contains a script which is only needed during development preparing some data.

|--mypackage
|--mypackage/data
|--mypackage/data/prepare.py

The problem is that this py file is included in the package. I tried to exclude it with:

[tool.setuptools.packages.find]
where = ["."]
exclude = ["mypackage*data*py"]

But this does not seem the correct syntax. Or maybe it is not supported to exclude py files?


问:
How do I display PayPal's IPN variables to a blogger.com webpage?
I've written the following PayPal IPN Listener as a stand alone webapp in Google Apps Script; executed as me everyone has access. See Fig 1 and Embedded it with within one of the pages on my blogger site - https://???.blogspot.com/p/MyPage.html. (After checkout in PayPal is completed the customer is automatically redirected to this page) See Fig 2 for embed code.

The problem is that whenever I run the script I keep getting the following error:

Script function not found: doGet

Fig 1.

```<code>function doPost(e) {
  var isProduction = false;

  var strSimulator  = "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr";
  var strLive = "https://ipnpb.paypal.com/cgi-bin/webscr";
  var paypalURL = strSimulator;

  if (isProduction)  paypalURL = strLive;

  var payload = "cmd=_notify-validate&" + e.postData.contents;

  var options =
    {
      "method" : "post",
      "payload" : payload,
    };

  var resp = UrlFetchApp.fetch(paypalURL, options); //Handshake with PayPal - send acknowledgement and get VERIFIED or INVALID response

  if (resp == 'VERIFIED') {
    if (e.parameter.payment_status  == 'Completed') {
      if (e.parameter.receiver_email == 'my-email@example.com') {
        //Implement paid amount validation. If accepting payments in multiple currencies, use e.parameter.exchange_rate to convert to reference currency (USD) if paid in any other currency
        if (amountValid) {

          //All validated - can process the payment here
            var params = JSON.stringify(e);
            return HtmlService.createHtmlOutput(' ').setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);

          if (!(processSuccess)) {
            //Process of payment failed - raise notification to check it out

          }
        } else {
          //Payment does not equal expected purchase value
        }
      } else {
       //Request did not originate from my PayPal account
      }
    } else {
     //Payment status not Completed
    }
  } else
  {
   //PayPal response INVALID
  }
}
</code>```

Fig 2.

Loading...
```
<p>I tried calling the <code>doPost(e)</code> function from a <code>doGet(e)</code> function I created within the file; see Fig 3, but I only get the following error:</p>
<blockquote>
<p>TypeError: Cannot read properties of undefined (reading 'contents') (line 15, file "Code")</p>
</blockquote>
<p>Fig 3.</p>
```function doGet(e) {
doPost(e);
}
```

What should happen is, I would like to print out the PayPal IPN variables sent.

Body:
I've written the following PayPal IPN Listener as a stand alone webapp in Google Apps Script; executed as me everyone has access. See Fig 1 and Embedded it with within one of the pages on my blogger site - https://???.blogspot.com/p/MyPage.html. (After checkout in PayPal is completed the customer is automatically redirected to this page) See Fig 2 for embed code.

The problem is that whenever I run the script I keep getting the following error:

Script function not found: doGet

Fig 1.

function doPost(e) {
  var isProduction = false;

  var strSimulator  = "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr";
  var strLive = "https://ipnpb.paypal.com/cgi-bin/webscr";
  var paypalURL = strSimulator;

  if (isProduction)  paypalURL = strLive;

  var payload = "cmd=_notify-validate&" + e.postData.contents;

  var options =
    {
      "method" : "post",
      "payload" : payload,
    };

  var resp = UrlFetchApp.fetch(paypalURL, options); //Handshake with PayPal - send acknowledgement and get VERIFIED or INVALID response

  if (resp == 'VERIFIED') {
    if (e.parameter.payment_status  == 'Completed') {
      if (e.parameter.receiver_email == 'my-email@example.com') {
        //Implement paid amount validation. If accepting payments in multiple currencies, use e.parameter.exchange_rate to convert to reference currency (USD) if paid in any other currency
        if (amountValid) {

          //All validated - can process the payment here
            var params = JSON.stringify(e);
            return HtmlService.createHtmlOutput(' ').setSandboxMode(HtmlService.SandboxMode.IFRAME).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);

          if (!(processSuccess)) {
            //Process of payment failed - raise notification to check it out

          }
        } else {
          //Payment does not equal expected purchase value
        }
      } else {
       //Request did not originate from my PayPal account
      }
    } else {
     //Payment status not Completed
    }
  } else
  {
   //PayPal response INVALID
  }
}

Fig 2.

Loading...

I tried calling the doPost(e) function from a doGet(e) function I created within the file; see Fig 3, but I only get the following error:

TypeError: Cannot read properties of undefined (reading 'contents') (line 15, file "Code")

Fig 3.

function doGet(e) {
doPost(e);
}

What should happen is, I would like to print out the PayPal IPN variables sent.


问:
How can I create a Public Key from a PEM File (String) in Swift?
I'm pretty new to RSA Keys and Certificates and all of that. So I'm getting a PEM File from a network request, I understand the PEM file is basically the certificate without header and footer, so essentially I have a string. I need to create a PublicKey from that in order to Encrypt some text, but I think I'm doing something wrong. This is my code so far, I have talked to other teams (Android) and when they print out the Encrypted Data, they are getting a regular String and I'm getting lots of weird characters. Thanks in advance guys! (:

```<code>func encryptBase64(text: String, certificateStr: String) throws -> Data {
    let encryptionError = EncrpytionError(message: "There has been an issue with encryption")

    guard
        let certData = Data(base64Encoded: certificateStr),
        let certificate = SecCertificateCreateWithData(nil, certData as CFData),
        let publicKey = SecCertificateCopyKey(certificate)
    else {
        throw encryptionError
    }

    let algorithm: SecKeyAlgorithm = .rsaEncryptionOAEPSHA256AESGCM

    guard SecKeyIsAlgorithmSupported(publicKey, .encrypt, algorithm) else {
        throw encryptionError
    }
    guard let cipherText = SecKeyCreateEncryptedData(
        publicKey,
        algorithm,
        text.data(using: .utf8)! as CFData, nil)
    else {
        throw encryptionError
    }
    return cipherText as Data
}
</code>```

And when I try to print cipherText as a String, I get this weird thing:

```<code>"D�aj�\\m꒤h,�A�{��8�~�\nY\u0003F�Cˤ�@��\"�\u0018�\u0007\u001fX@VC�U_��E\u0005ǆ1���X��\/4Px��P\u0016�8}% ��<��@�I_�K\u000e�\bR*�� ���斋�7,�%���F^q�\u0000\\�'�ZTD\u0013Q�_\u0010\u001f>i]&��B���@1\u0006\b��E\u0004�F���yS\u0013�3����SB)��m\u0017%��5ʲ����s\u0003��r�&�?�8b��W@\u001e��؞ۡ��8�s~��ӹ�u\"�2��U�&\b�3XV���˔Y��xt[\fm&P:\\�\f� y��6jy"
</code>```

Android team is doing something like this on Kotlin:

```<code>private fun extractPublicKey(certificateString: String): PublicKey {
            val encodedCertificateBytes = certificateString.toByteArray()
            val decodedCertificateBytes = Base64.decode(encodedCertificateBytes, Base64.DEFAULT)
            val inStream = decodedCertificateBytes.inputStream()
            val certificateFactory = CertificateFactory.getInstance("X.509")
            val certificate = certificateFactory.generateCertificate(inStream)
            inStream.close()
            return certificate.publicKey
}
</code>```

Body:
I'm pretty new to RSA Keys and Certificates and all of that. So I'm getting a PEM File from a network request, I understand the PEM file is basically the certificate without header and footer, so essentially I have a string. I need to create a PublicKey from that in order to Encrypt some text, but I think I'm doing something wrong. This is my code so far, I have talked to other teams (Android) and when they print out the Encrypted Data, they are getting a regular String and I'm getting lots of weird characters. Thanks in advance guys! (:

func encryptBase64(text: String, certificateStr: String) throws -> Data {
    let encryptionError = EncrpytionError(message: "There has been an issue with encryption")

    guard
        let certData = Data(base64Encoded: certificateStr),
        let certificate = SecCertificateCreateWithData(nil, certData as CFData),
        let publicKey = SecCertificateCopyKey(certificate)
    else {
        throw encryptionError
    }

    let algorithm: SecKeyAlgorithm = .rsaEncryptionOAEPSHA256AESGCM

    guard SecKeyIsAlgorithmSupported(publicKey, .encrypt, algorithm) else {
        throw encryptionError
    }
    guard let cipherText = SecKeyCreateEncryptedData(
        publicKey,
        algorithm,
        text.data(using: .utf8)! as CFData, nil)
    else {
        throw encryptionError
    }
    return cipherText as Data
}

And when I try to print cipherText as a String, I get this weird thing:

"D�aj�\\m꒤h,�A�{��8�~�\nY\u0003F�Cˤ�@��\"�\u0018�\u0007\u001fX@VC�U_��E\u0005ǆ1���X��\/4Px��P\u0016�8}% ��<��@�I_�K\u000e�\bR*�� ���斋�7,�%���F^q�\u0000\\�'�ZTD\u0013Q�_\u0010\u001f>i]&��B���@1\u0006\b��E\u0004�F���yS\u0013�3����SB)��m\u0017%��5ʲ����s\u0003��r�&�?�8b��W@\u001e��؞ۡ��8�s~��ӹ�u\"�2��U�&\b�3XV���˔Y��xt[\fm&P:\\�\f� y��6jy"

Android team is doing something like this on Kotlin:

private fun extractPublicKey(certificateString: String): PublicKey {
            val encodedCertificateBytes = certificateString.toByteArray()
            val decodedCertificateBytes = Base64.decode(encodedCertificateBytes, Base64.DEFAULT)
            val inStream = decodedCertificateBytes.inputStream()
            val certificateFactory = CertificateFactory.getInstance("X.509")
            val certificate = certificateFactory.generateCertificate(inStream)
            inStream.close()
            return certificate.publicKey
}


问:
R - bigrquery::bq_auth() function does not work - I can not reauthenticate to connect with BigQuery
First things first:

Operating System: Windows 10

R version: 4.2.2

Story
I am trying to import data from Google BigQuery to R. I am using bigrquery package. However any operations after creating DBI connection results in the same way - I get error message saying Access Denied.

Here is the code:

```<code># libs
library(bigrquery)
library(DBI)

# connection
con <- dbConnect(
  bigrquery::bigquery(),
  project = "project-nmae",
  dataset = "dataset",
  billing = "project-for_billing"
)

dbListTables(con)
</code>```

Error I get:

Error in signal_reason():
! Access Denied: Dataset x:y: Permission bigquery.tables.list denied on >dataset x:y (or it may not exist). [accessDenied]

Problem
So OK. I have got multiple google accounts so I would like to force bigrquery to reauthenticate to make sure I am using proper one.

So as described in the documentation I am calling bq_auth(email=NA) and I expect that R should open browser with authentication page but nothing happens. No errors and totally no action.

I have also manually removed all tokens stored by gargle package. When I check tokens using gargle::gargle_oauth_sitrep() I get info that 0 tokens have been found. However it has not helped.

Question
Does anyone know how to force bigrquery to reauthenticate and why bq_auth(email = NA) doesn't work?

Body:
First things first:

Operating System: Windows 10

R version: 4.2.2

Story
I am trying to import data from Google BigQuery to R. I am using bigrquery package. However any operations after creating DBI connection results in the same way - I get error message saying Access Denied.

Here is the code:

# libs
library(bigrquery)
library(DBI)

# connection
con <- dbConnect(
  bigrquery::bigquery(),
  project = "project-nmae",
  dataset = "dataset",
  billing = "project-for_billing"
)

dbListTables(con)

Error I get:

Error in signal_reason():
! Access Denied: Dataset x:y: Permission bigquery.tables.list denied on >dataset x:y (or it may not exist). [accessDenied]

Problem
So OK. I have got multiple google accounts so I would like to force bigrquery to reauthenticate to make sure I am using proper one.

So as described in the documentation I am calling bq_auth(email=NA) and I expect that R should open browser with authentication page but nothing happens. No errors and totally no action.

I have also manually removed all tokens stored by gargle package. When I check tokens using gargle::gargle_oauth_sitrep() I get info that 0 tokens have been found. However it has not helped.

Question
Does anyone know how to force bigrquery to reauthenticate and why bq_auth(email = NA) doesn't work?


问:
How to iterate child in golang with parent id?
I want to iterate children that have parent id and put on children properti in json?
I have try to do that, but children just show in 1 level on children, and not working on 2 level, how to do that?

```<code>type ResponseMenu struct {
    ID          primitive.ObjectID `json:"_id" form:"_id" bson:"_id"`
    Title       string             `json:"title" form:"title" bson:"title"`
    Children    []ResponseMenu     `json:"children" form:"children" bson:"children"`
    ParentId    string             `json:"parent_id" form:"parent_id" bson:"parent_id"`
}

func iterateChild(resChild []model.ResponseMenu, obj *model.ResponseMenu) {
    var ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
    // fmt.Println("len child: ", len(resChild))

    obj.Children = make([]model.ResponseMenu, len(resChild))
    if len(resChild) > 0 {
        jsonData, _ := json.Marshal(resChild)
        fmt.Println("resChild: ", string(jsonData))
        obj.Children = append([]model.ResponseMenu{}, resChild...)
        for _, sv := range resChild {
            var resSc []model.ResponseMenu
            fc := bson.M{"parent_id": sv.ID.Hex()}
            cursor, err := menuCollection.Find(ctx, fc)
            defer cancel()
            if err != nil {
                fmt.Println("halo")
            }
            if err = cursor.All(ctx, &resSc); err != nil {
                fmt.Println("loha")
            }
            iterateChild(resSc, &sv)
        }
    }
}

func GetListMenu(c *gin.Context) {
    var ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
    var response []*model.ResponseMenu
    var resChild []model.ResponseMenu
    q := c.Query("q")
    perPage, err := strconv.Atoi(c.Query("per_page"))
    if err != nil || perPage == 0 {
        perPage = 10
    }
    page, _ := strconv.Atoi(c.Query("page"))
    if page > 0 { // page start from index 0
        page -= 1
    }
    filter := bson.M{
        "title": primitive.Regex{
            Pattern: q,
            Options: "i", // i for case sensitive uppercase or lowercase
        },
        "is_parent": true,
        "parent_id": "",
    }
    options := options.Find()
    options.SetSkip(int64(page * perPage))
    options.SetLimit(int64(perPage))
    options.SetSort(bson.D{{"created_at", -1}})
    cursor, err := menuCollection.Find(ctx, filter, options)
    defer cancel()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "status":  false,
            "message": http.StatusInternalServerError,
            "error":   err.Error(),
        })
        return
    }
    if err = cursor.All(ctx, &response); err != nil {
        log.Fatal(err)
        c.JSON(http.StatusInternalServerError, gin.H{
            "status":  false,
            "message": err.Error(),
        })
        return
    }

    for _, v := range response {
        // fmt.Println(v.ID.Hex())
        filterChild := bson.M{"parent_id": v.ID.Hex()}
        cursor, err := menuCollection.Find(ctx, filterChild)
        defer cancel()
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "status":  false,
                "message": http.StatusInternalServerError,
                "error":   err.Error(),
            })
            return
        }
        if err = cursor.All(ctx, &resChild); err != nil {
            log.Fatal(err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "status":  false,
                "message": err.Error(),
            })
            return
        }
        iterateChild(resChild, v)
    }
    if len(response) > 0 {
        c.JSON(http.StatusOK, gin.H{
            "status":  true,
            "message": "Success retrieve data",
            "data":    response,
        })
    } else {
        c.JSON(http.StatusOK, gin.H{
            "status":  false,
            "message": "Data not found",
            "data":    response,
        })
    }
}
</code>```

this is the database that I have

and this is the response:

```<code>{
    "data": [
        {
            "_id": "63a63cc231bc5e0d42efe54f",
            "title": "Dashboard",
            "translate": "",
            "type": "group",
            "children": [
                {
                    "_id": "63a63d0c31bc5e0d42efe551",
                    "title": "Settings",
                    "translate": "",
                    "type": "item",
                    "children": null,
                    "parent_id": "63a63cc231bc5e0d42efe54f",
                    "level": 1,
                    "icon": "home",
                    "url": "admin/setting",
                    "permissions": [
                        "view",
                        "add",
                        "edit",
                        "delete"
                    ],
                    "created_at": "2022-12-23T23:43:08Z",
                    "updated_at": "2022-12-23T23:43:08Z"
                },
                {
                    "_id": "63a63d3c31bc5e0d42efe552",
                    "title": "Roles",
                    "translate": "",
                    "type": "item",
                    "children": null,
                    "parent_id": "63a63cc231bc5e0d42efe54f",
                    "level": 1,
                    "icon": "home",
                    "url": "admin/setting",
                    "permissions": [
                        "view",
                        "add",
                        "edit",
                        "delete"
                    ],
                    "created_at": "2022-12-23T23:43:56Z",
                    "updated_at": "2022-12-23T23:43:56Z"
                }
            ],
            "parent_id": "",
            "level": 0,
            "icon": "home",
            "url": "admin/dashboard",
            "permissions": null,
            "created_at": "2022-12-23T23:41:54Z",
            "updated_at": "2022-12-23T23:41:54Z"
        }
    ],
    "message": "Success retrieve data",
    "status": true
}
</code>```

children with title Setting should have children with Title Origo, but not show children.
How to show children in nested children?

Body:
I want to iterate children that have parent id and put on children properti in json?
I have try to do that, but children just show in 1 level on children, and not working on 2 level, how to do that?

type ResponseMenu struct {
    ID          primitive.ObjectID `json:"_id" form:"_id" bson:"_id"`
    Title       string             `json:"title" form:"title" bson:"title"`
    Children    []ResponseMenu     `json:"children" form:"children" bson:"children"`
    ParentId    string             `json:"parent_id" form:"parent_id" bson:"parent_id"`
}

func iterateChild(resChild []model.ResponseMenu, obj *model.ResponseMenu) {
    var ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
    // fmt.Println("len child: ", len(resChild))

    obj.Children = make([]model.ResponseMenu, len(resChild))
    if len(resChild) > 0 {
        jsonData, _ := json.Marshal(resChild)
        fmt.Println("resChild: ", string(jsonData))
        obj.Children = append([]model.ResponseMenu{}, resChild...)
        for _, sv := range resChild {
            var resSc []model.ResponseMenu
            fc := bson.M{"parent_id": sv.ID.Hex()}
            cursor, err := menuCollection.Find(ctx, fc)
            defer cancel()
            if err != nil {
                fmt.Println("halo")
            }
            if err = cursor.All(ctx, &resSc); err != nil {
                fmt.Println("loha")
            }
            iterateChild(resSc, &sv)
        }
    }
}

func GetListMenu(c *gin.Context) {
    var ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
    var response []*model.ResponseMenu
    var resChild []model.ResponseMenu
    q := c.Query("q")
    perPage, err := strconv.Atoi(c.Query("per_page"))
    if err != nil || perPage == 0 {
        perPage = 10
    }
    page, _ := strconv.Atoi(c.Query("page"))
    if page > 0 { // page start from index 0
        page -= 1
    }
    filter := bson.M{
        "title": primitive.Regex{
            Pattern: q,
            Options: "i", // i for case sensitive uppercase or lowercase
        },
        "is_parent": true,
        "parent_id": "",
    }
    options := options.Find()
    options.SetSkip(int64(page * perPage))
    options.SetLimit(int64(perPage))
    options.SetSort(bson.D{{"created_at", -1}})
    cursor, err := menuCollection.Find(ctx, filter, options)
    defer cancel()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "status":  false,
            "message": http.StatusInternalServerError,
            "error":   err.Error(),
        })
        return
    }
    if err = cursor.All(ctx, &response); err != nil {
        log.Fatal(err)
        c.JSON(http.StatusInternalServerError, gin.H{
            "status":  false,
            "message": err.Error(),
        })
        return
    }

    for _, v := range response {
        // fmt.Println(v.ID.Hex())
        filterChild := bson.M{"parent_id": v.ID.Hex()}
        cursor, err := menuCollection.Find(ctx, filterChild)
        defer cancel()
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{
                "status":  false,
                "message": http.StatusInternalServerError,
                "error":   err.Error(),
            })
            return
        }
        if err = cursor.All(ctx, &resChild); err != nil {
            log.Fatal(err)
            c.JSON(http.StatusInternalServerError, gin.H{
                "status":  false,
                "message": err.Error(),
            })
            return
        }
        iterateChild(resChild, v)
    }
    if len(response) > 0 {
        c.JSON(http.StatusOK, gin.H{
            "status":  true,
            "message": "Success retrieve data",
            "data":    response,
        })
    } else {
        c.JSON(http.StatusOK, gin.H{
            "status":  false,
            "message": "Data not found",
            "data":    response,
        })
    }
}

this is the database that I have

and this is the response:

{
    "data": [
        {
            "_id": "63a63cc231bc5e0d42efe54f",
            "title": "Dashboard",
            "translate": "",
            "type": "group",
            "children": [
                {
                    "_id": "63a63d0c31bc5e0d42efe551",
                    "title": "Settings",
                    "translate": "",
                    "type": "item",
                    "children": null,
                    "parent_id": "63a63cc231bc5e0d42efe54f",
                    "level": 1,
                    "icon": "home",
                    "url": "admin/setting",
                    "permissions": [
                        "view",
                        "add",
                        "edit",
                        "delete"
                    ],
                    "created_at": "2022-12-23T23:43:08Z",
                    "updated_at": "2022-12-23T23:43:08Z"
                },
                {
                    "_id": "63a63d3c31bc5e0d42efe552",
                    "title": "Roles",
                    "translate": "",
                    "type": "item",
                    "children": null,
                    "parent_id": "63a63cc231bc5e0d42efe54f",
                    "level": 1,
                    "icon": "home",
                    "url": "admin/setting",
                    "permissions": [
                        "view",
                        "add",
                        "edit",
                        "delete"
                    ],
                    "created_at": "2022-12-23T23:43:56Z",
                    "updated_at": "2022-12-23T23:43:56Z"
                }
            ],
            "parent_id": "",
            "level": 0,
            "icon": "home",
            "url": "admin/dashboard",
            "permissions": null,
            "created_at": "2022-12-23T23:41:54Z",
            "updated_at": "2022-12-23T23:41:54Z"
        }
    ],
    "message": "Success retrieve data",
    "status": true
}

children with title Setting should have children with Title Origo, but not show children.
How to show children in nested children?


问:
Configuration of pmadb… not OK
When I open the phpMyAdmin, there showing one error message about, "The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. Find out why.
Or alternately go to 'Operations' tab of any database to set it up there." like this. after I click, "Find out why" option, then showing me, "create database phpMyAdmin" but there already have similar database.

[This is the error] (https://i.stack.imgur.com/LRiR5.png)

I tried to create names as "phpMyAdmin". But it's not allowed, because there already had database. I don't understand how to add those settings?

[This is that database inside tables] (https://i.stack.imgur.com/DycVr.png)

There have

configuration of pmadb not OK,

General relation features Disabled.

Please help me for fix those points what mentioned above.

Title: Configuration of pmadb… not OK