问:
EMBEDDED_SUBSCRIPTION_RESULT_ERROR in eSIM implementation on Android using kotlin
EMBEDDED_SUBSCRIPTION_RESULT_ERROR

Hi all, I'm trying to implement eSim installation app using kotlin.
I've been looking at google's documentation (https://source.android.com/devices/tech/connect/esim-overview?hl=en) about it and yet I have serval unfigured questions. Right now, In my app I'm getting the broadcast with onReceive function and I'm starting the flow by giving permission on errorCode 1 and then I'm stuck on errorCode 2 - > EMBEDDED_SUBSCRIPTION_RESULT_ERROR
I can't figure out how to pass this error and what am I doing wrong. Additionally, when I'm passing to the registerReceiver function the LPA_DECLARED_PERMISSION with my bundle id the app doesn't go into the onReceive function. and my last unfigured question is what should I do when I need to pass a custom confirmation code for installing the eSim.

This is my application code:

```<code>package com.example.testesimsdk

//import android.telephony.euicc.DownloadableSubscription
//import android.telephony.euicc.EuiccManager
import android.R.attr.action
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.telephony.euicc.DownloadableSubscription
import android.telephony.euicc.EuiccManager
import android.telephony.euicc.EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE
//import android.telephony.euicc.*
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity(), View.OnClickListener {
    private val ACTIVATION_CODE = "LPA:1ֿ\$tl2.prod.ondemandconnectivity.com\$XWSAGDHOHV2VBGLN"
    private val Success = "Success"
    private val ACTIVATION_CODE2 = "LPA:1\$tl2.prod.ondemandconnectivity.com\$TRN3M6IW62V7ET5B"
    private val ACTION_DOWNLOAD_SUBSCRIPTION = "download_subscription"
    private val ACTION_DELETE_SUBSCRIPTION = "delete_subscription"
    private val LPA_DECLARED_PERMISSION = "com.example.testesimsdk.lpa.permission.BROADCAST"

    private lateinit var resultIntent: Intent
    private var mgr: EuiccManager? = null
    private lateinit var broadcastReceiver: BroadcastReceiver
    private lateinit var btn: Button;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext, ACTIVATION_CODE, Toast.LENGTH_LONG).show()
        implementEsim()
        btn = findViewById(R.id.button)
        btn.setOnClickListener(this)
    }

    private fun implementEsim() {
        setupEsim()
    }

    private fun initMgr() {
        if (mgr == null) {
            mgr = this.getSystemService(EUICC_SERVICE) as EuiccManager
        }
    }

    fun isEsimSupported(): Boolean {
        initMgr()
        return mgr?.isEnabled ?: false
    }

    fun setupEsim() {
        initMgr()
        if (isEsimSupported()) {
            val broadcastReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    if (ACTION_DOWNLOAD_SUBSCRIPTION != intent.action) {
                        Log.d(
                            "[MainActivity lala]: ",
                            "Can't setup eSim du to wrong Intent:" + intent.getAction() + " instead of "
                                    + ACTION_DOWNLOAD_SUBSCRIPTION
                        );
                        return;
                    }
                    val resultCode: Int = resultCode
                    val detailedCode = intent.getIntExtra(
                        EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE,
                        0 /* defaultValue*/
                    );
                    if (resultCode == EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR && mgr != null) {
                        Toast.makeText(applicationContext, "EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR", Toast.LENGTH_LONG).show()
                        Log.d(
                            "[MainActivity lala]:",
                            "EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR"
                        )
                        handleResolvableError(intent, resultCode)
                    } else if (resultCode == EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK) {
                        Toast.makeText(applicationContext, Success, Toast.LENGTH_LONG).show()
                        Log.d(
                            "[MainActivity lala]:",
                            "EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK"
                        )
                    } else if (resultCode == EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR) {
                        Toast.makeText(applicationContext, "EMBEDDED_SUBSCRIPTION_RESULT_ERROR", Toast.LENGTH_LONG).show()
                        // Embedded Subscription Error
                        handleResolvableError(intent, resultCode)
                        Log.d(
                            "[MainActivity lala]:",
                            "EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR"
                        )
                    } else {
                        // Unknown Error
                        Log.d(
                            "[MainActivity lala]:",
                            "Can't add an Esim subscription due to unknown error, resultCode is:$resultCode"
                        )
                    }
                }
            }

            this.registerReceiver(
                broadcastReceiver,
                IntentFilter(ACTION_DOWNLOAD_SUBSCRIPTION),
                null,
                null
            )
//        this.registerReceiver(broadcastReceiver, IntentFilter(ACTION_DOWNLOAD_SUBSCRIPTION), LPA_DECLARED_PERMISSION, null)

            val sub = DownloadableSubscription.forActivationCode(ACTIVATION_CODE)
            val intent = Intent(ACTION_DOWNLOAD_SUBSCRIPTION)
            val callbackIntent = PendingIntent.getBroadcast(
                this, 0 /* requestCode */, intent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
            mgr?.downloadSubscription(sub, true, callbackIntent);
        }
    }

    private fun handleResolvableError(intent: Intent, resCode: Int) {
        try {
            // Resolvable error, attempt to resolve it by a user action
            // FIXME: review logic of resolve functions
            val resolutionRequestCode = resCode
            val callbackIntent = PendingIntent.getBroadcast(
                this, resolutionRequestCode,
                Intent(ACTION_DOWNLOAD_SUBSCRIPTION), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )
            mgr?.startResolutionActivity(
                this,
                resolutionRequestCode,
                intent,
                callbackIntent
            )
        } catch (e: Exception) {
            Log.d(
                "[MainActivity lala]:",
                "EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR - Can't setup eSim du to Activity error "
                        + e.localizedMessage
            )
        }
    }

    private fun deleteSubs(){
        val intent = Intent(ACTION_DELETE_SUBSCRIPTION)
        val callbackIntent = PendingIntent.getBroadcast(
            this, 0 /* requestCode */, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        mgr?.deleteSubscription(1 /* subscriptionId */, callbackIntent);
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.button -> deleteSubs()
        }
    }

    override fun onDestroy() {
        if (broadcastReceiver != null) {
            this.unregisterReceiver(broadcastReceiver)
        }
        super.onDestroy()
    }

}

</code>```

I will be happy to get examples of implementing it correctly.
Thank you!

Body:
EMBEDDED_SUBSCRIPTION_RESULT_ERROR

Hi all, I'm trying to implement eSim installation app using kotlin.
I've been looking at google's documentation (https://source.android.com/devices/tech/connect/esim-overview?hl=en) about it and yet I have serval unfigured questions. Right now, In my app I'm getting the broadcast with onReceive function and I'm starting the flow by giving permission on errorCode 1 and then I'm stuck on errorCode 2 - > EMBEDDED_SUBSCRIPTION_RESULT_ERROR
I can't figure out how to pass this error and what am I doing wrong. Additionally, when I'm passing to the registerReceiver function the LPA_DECLARED_PERMISSION with my bundle id the app doesn't go into the onReceive function. and my last unfigured question is what should I do when I need to pass a custom confirmation code for installing the eSim.

This is my application code:

package com.example.testesimsdk

//import android.telephony.euicc.DownloadableSubscription
//import android.telephony.euicc.EuiccManager
import android.R.attr.action
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.telephony.euicc.DownloadableSubscription
import android.telephony.euicc.EuiccManager
import android.telephony.euicc.EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE
//import android.telephony.euicc.*
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity(), View.OnClickListener {
    private val ACTIVATION_CODE = "LPA:1ֿ\$tl2.prod.ondemandconnectivity.com\$XWSAGDHOHV2VBGLN"
    private val Success = "Success"
    private val ACTIVATION_CODE2 = "LPA:1\$tl2.prod.ondemandconnectivity.com\$TRN3M6IW62V7ET5B"
    private val ACTION_DOWNLOAD_SUBSCRIPTION = "download_subscription"
    private val ACTION_DELETE_SUBSCRIPTION = "delete_subscription"
    private val LPA_DECLARED_PERMISSION = "com.example.testesimsdk.lpa.permission.BROADCAST"

    private lateinit var resultIntent: Intent
    private var mgr: EuiccManager? = null
    private lateinit var broadcastReceiver: BroadcastReceiver
    private lateinit var btn: Button;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext, ACTIVATION_CODE, Toast.LENGTH_LONG).show()
        implementEsim()
        btn = findViewById(R.id.button)
        btn.setOnClickListener(this)
    }

    private fun implementEsim() {
        setupEsim()
    }

    private fun initMgr() {
        if (mgr == null) {
            mgr = this.getSystemService(EUICC_SERVICE) as EuiccManager
        }
    }

    fun isEsimSupported(): Boolean {
        initMgr()
        return mgr?.isEnabled ?: false
    }

    fun setupEsim() {
        initMgr()
        if (isEsimSupported()) {
            val broadcastReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    if (ACTION_DOWNLOAD_SUBSCRIPTION != intent.action) {
                        Log.d(
                            "[MainActivity lala]: ",
                            "Can't setup eSim du to wrong Intent:" + intent.getAction() + " instead of "
                                    + ACTION_DOWNLOAD_SUBSCRIPTION
                        );
                        return;
                    }
                    val resultCode: Int = resultCode
                    val detailedCode = intent.getIntExtra(
                        EuiccManager.EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE,
                        0 /* defaultValue*/
                    );
                    if (resultCode == EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR && mgr != null) {
                        Toast.makeText(applicationContext, "EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR", Toast.LENGTH_LONG).show()
                        Log.d(
                            "[MainActivity lala]:",
                            "EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR"
                        )
                        handleResolvableError(intent, resultCode)
                    } else if (resultCode == EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK) {
                        Toast.makeText(applicationContext, Success, Toast.LENGTH_LONG).show()
                        Log.d(
                            "[MainActivity lala]:",
                            "EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_OK"
                        )
                    } else if (resultCode == EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR) {
                        Toast.makeText(applicationContext, "EMBEDDED_SUBSCRIPTION_RESULT_ERROR", Toast.LENGTH_LONG).show()
                        // Embedded Subscription Error
                        handleResolvableError(intent, resultCode)
                        Log.d(
                            "[MainActivity lala]:",
                            "EuiccManager.EMBEDDED_SUBSCRIPTION_RESULT_ERROR"
                        )
                    } else {
                        // Unknown Error
                        Log.d(
                            "[MainActivity lala]:",
                            "Can't add an Esim subscription due to unknown error, resultCode is:$resultCode"
                        )
                    }
                }
            }

            this.registerReceiver(
                broadcastReceiver,
                IntentFilter(ACTION_DOWNLOAD_SUBSCRIPTION),
                null,
                null
            )
//        this.registerReceiver(broadcastReceiver, IntentFilter(ACTION_DOWNLOAD_SUBSCRIPTION), LPA_DECLARED_PERMISSION, null)

            val sub = DownloadableSubscription.forActivationCode(ACTIVATION_CODE)
            val intent = Intent(ACTION_DOWNLOAD_SUBSCRIPTION)
            val callbackIntent = PendingIntent.getBroadcast(
                this, 0 /* requestCode */, intent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
            mgr?.downloadSubscription(sub, true, callbackIntent);
        }
    }

    private fun handleResolvableError(intent: Intent, resCode: Int) {
        try {
            // Resolvable error, attempt to resolve it by a user action
            // FIXME: review logic of resolve functions
            val resolutionRequestCode = resCode
            val callbackIntent = PendingIntent.getBroadcast(
                this, resolutionRequestCode,
                Intent(ACTION_DOWNLOAD_SUBSCRIPTION), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )
            mgr?.startResolutionActivity(
                this,
                resolutionRequestCode,
                intent,
                callbackIntent
            )
        } catch (e: Exception) {
            Log.d(
                "[MainActivity lala]:",
                "EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR - Can't setup eSim du to Activity error "
                        + e.localizedMessage
            )
        }
    }

    private fun deleteSubs(){
        val intent = Intent(ACTION_DELETE_SUBSCRIPTION)
        val callbackIntent = PendingIntent.getBroadcast(
            this, 0 /* requestCode */, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        mgr?.deleteSubscription(1 /* subscriptionId */, callbackIntent);
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.button -> deleteSubs()
        }
    }

    override fun onDestroy() {
        if (broadcastReceiver != null) {
            this.unregisterReceiver(broadcastReceiver)
        }
        super.onDestroy()
    }

}

I will be happy to get examples of implementing it correctly.
Thank you!


来源: stackexchange

问:
remove Duplicate in mongodb using PHP
I have a mongodb that there are many duplicate data in it, the problem is: when I search throw my db using php it will retrieve duplicate data too , I wander is there any way to prevent duplicate and just show 1 of the duplicate data.

Any Idea?

I try array_unique on PHP array that contain data but as long as data retrieve with different id this function is useless.

 $tbl_customer_limit = $db->find($where, ['limit' => $limitrRow, 'skip' => $offsetCustomer])->toArray(); $tbl_customer_limit =array_unique($tbl_customer_limit);

ContentLicense: CC BY-SA 4.0

Title: remove Duplicate in mongodb using PHP


问:
Normalized Dataset creates wore performance with model
Practicing building classification models using tensor flow. I'm using the "make_moons()" dataset available off the sklearn.datasets library.

here's a snip of the model:

```<code>norm_model = tf.keras.Sequential([
    tf.keras.layers.Dense(100, activation="relu", name = "Output"),
    tf.keras.layers.Dense(10, activation ="relu", name = "hidden"),
    tf.keras.layers.Dense(1, activation= "sigmoid", name = "Input")
])

# compile the norm_model
norm_model.compile(
    loss = tf.keras.losses.BinaryCrossentropy(),
    optimizer = tf.keras.optimizers.Adam(),
    metrics = ["accuracy"]
)

# fit the model to the training set
norm_history = norm_model.fit(xTrain_norm, yTrain, epochs=100, validation_data=(xTest_norm, yTest))
</code>```

Without normalizing the data, the model performs pretty well ~ 90% accuracy and 0.19 loss (Binary CrossEntropy).

But when I normalize the data, it performs very poorly. here's the data range: (min, max) = (-1, 2)

Normalization takes the following steps:
** remove negatives: add one to all the values
** (0,1)-normaize by dividing by by '3'

And here, the accuracy is ~ 0.54 and loss : 0.69 (Binary CrossEntropy)

Body:
Practicing building classification models using tensor flow. I'm using the "make_moons()" dataset available off the sklearn.datasets library.

here's a snip of the model:

norm_model = tf.keras.Sequential([
    tf.keras.layers.Dense(100, activation="relu", name = "Output"),
    tf.keras.layers.Dense(10, activation ="relu", name = "hidden"),
    tf.keras.layers.Dense(1, activation= "sigmoid", name = "Input")
])

# compile the norm_model
norm_model.compile(
    loss = tf.keras.losses.BinaryCrossentropy(),
    optimizer = tf.keras.optimizers.Adam(),
    metrics = ["accuracy"]
)

# fit the model to the training set
norm_history = norm_model.fit(xTrain_norm, yTrain, epochs=100, validation_data=(xTest_norm, yTest))

Without normalizing the data, the model performs pretty well ~ 90% accuracy and 0.19 loss (Binary CrossEntropy).

But when I normalize the data, it performs very poorly. here's the data range: (min, max) = (-1, 2)

Normalization takes the following steps:
** remove negatives: add one to all the values
** (0,1)-normaize by dividing by by '3'

And here, the accuracy is ~ 0.54 and loss : 0.69 (Binary CrossEntropy)


问:
How to filter out specific rows in a dask dataframe using a custom function?
I have dataframe consisting of the following columns:

```<code>    act     section     female_judge    time_taken
0   17.0    121384.0    0 nonfemale        321.0
1   423.0   273193.0    0 nonfemale        0.0
2   423.0   332490.0    0 nonfemale        0.0
3   481.0   1440.0      0 nonfemale        0.0
4   481.0   5145.0      0 nonfemale        0.0

</code>```

Basically I have grouped the records by the act,section and female_judge columns. Now I want to keep the rows where for a given act and section, there exists both a row where the judge is female and a row where the judge is male.(I want to compare time taken between make and female judges for the same act and section).

How would I filter out the rows?

Body:
I have dataframe consisting of the following columns:

    act     section     female_judge    time_taken
0   17.0    121384.0    0 nonfemale        321.0
1   423.0   273193.0    0 nonfemale        0.0
2   423.0   332490.0    0 nonfemale        0.0
3   481.0   1440.0      0 nonfemale        0.0
4   481.0   5145.0      0 nonfemale        0.0

Basically I have grouped the records by the act,section and female_judge columns. Now I want to keep the rows where for a given act and section, there exists both a row where the judge is female and a row where the judge is male.(I want to compare time taken between make and female judges for the same act and section).

How would I filter out the rows?


问:
migration error django.db.utils.DatabaseError in Django
```<code>File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__
    self.parse()
  File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse
    self._alter(statement)
  File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter
    raise SQLDecodeError(f'Unknown token: {tok}')
djongo.exceptions.SQLDecodeError:

        Keyword: Unknown token: TYPE
        Sub SQL: None
        FAILED SQL: ('ALTER TABLE "corsheaders_corsmodel" ALTER COLUMN "id" TYPE long',)
        Params: ([],)
        Version: 1.3.6

The above exception was the direct cause of the following exception:

return self.\_execute_with_wrappers(sql, params, many=False, executor=self.\_execute)
File "D:\\kice\\flask\\venv\\lib\\site-packages\\django\\db\\backends\\utils.py", line 75, in \_execute_with_wrappers
return executor(sql, params, many, context)
File "D:\\kice\\flask\\venv\\lib\\site-packages\\django\\db\\backends\\utils.py", line 79, in \_execute
with self.db.wrap_database_errors:
File "D:\\kice\\flask\\venv\\lib\\site-packages\\django\\db\\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "D:\\kice\\flask\\venv\\lib\\site-packages\\django\\db\\backends\\utils.py", line 84, in \_execute
return self.cursor.execute(sql, params)
File "D:\\kice\\flask\\venv\\lib\\site-packages\\djongo\\cursor.py", line 59, in execute
raise db_exe from e
django.db.utils.DatabaseError
</code>```


问:
How to get URL param for pagination in WordPress shortcode?
I have made the shortcode which displays data from database.
There are so many rows and so I made pagination.
But I can't get the URL param which means page number.

```<code><?php

/**
 * Plugin Name: Plugin hell
 */

if (!defined('ABSPATH')) {
    die;
}

function count_rows()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'strong_concordance';
    $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
    return intval($count);
}
function get_data($offset, $per_page)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'strong_concordance';
    $data = $wpdb->get_results("SELECT * FROM $table_name LIMIT $offset, $per_page");
    return $data;
}

function display_data_shortcode($atts)
{
    $atts = shortcode_atts(
        array(
            'page' => 1,
            'per_page' => 10,
        ), $atts, 'display_data');

    $page = intval($atts['page']);

    $per_page = intval($atts['per_page']) ? : 10;

    $num_pages = ceil(count_rows() / $per_page);

    $offset = ($page - 1) * $per_page;

    $data = get_data($offset, $per_page);

    $output = '';
    foreach ($data as $row) {
        $output .= '<h3>' . $row->strong_reference . '</h3>';
        $output .= '<p style="font-weight: bold;">' . $row->greek_word . '</p>';
        $output .= '<p>' . $row->explanation . '</p>';
    }

    if ($page > 1) {
        $output .= '<a href="?page=' . ($page - 1) . '">Previous</a>';
    }
    for ($i = 1; $i <= $num_pages; $i++) {
        $output .= '<a href="?page=' . $i . '">' . ' ' . $i . ' ' . '</a>';
    }
    if ($page < $num_pages) {
        $output .= '<a href="?page=' . ($page + 1) . '">Next</a>';
    }

    return $output;
}

add_shortcode('display_data', 'display_data_shortcode');

?>
</code>```

There will be page numbers like "1 2 3 4 5 ... ".
I click any number-for example 4, but it still displays same.
How can I solve this issue?

I tried to display data according to the page number, but I can't move to any page.

Body:
I have made the shortcode which displays data from database.
There are so many rows and so I made pagination.
But I can't get the URL param which means page number.

<?php

/**
 * Plugin Name: Plugin hell
 */

if (!defined('ABSPATH')) {
    die;
}

function count_rows()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'strong_concordance';
    $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
    return intval($count);
}
function get_data($offset, $per_page)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'strong_concordance';
    $data = $wpdb->get_results("SELECT * FROM $table_name LIMIT $offset, $per_page");
    return $data;
}

function display_data_shortcode($atts)
{
    $atts = shortcode_atts(
        array(
            'page' => 1,
            'per_page' => 10,
        ), $atts, 'display_data');

    $page = intval($atts['page']);

    $per_page = intval($atts['per_page']) ? : 10;

    $num_pages = ceil(count_rows() / $per_page);

    $offset = ($page - 1) * $per_page;

    $data = get_data($offset, $per_page);

    $output = '';
    foreach ($data as $row) {
        $output .= '
' . $row->strong_reference . '
';
        $output .= '
' . $row->greek_word . '
';
        $output .= '
' . $row->explanation . '
';
    }

    if ($page > 1) {
        $output .= 'Previous';
    }
    for ($i = 1; $i <= $num_pages; $i++) {
        $output .= '' . ' ' . $i . ' ' . '';
    }
    if ($page < $num_pages) {
        $output .= 'Next';
    }

    return $output;
}

add_shortcode('display_data', 'display_data_shortcode');

?>

There will be page numbers like "1 2 3 4 5 ... ".
I click any number-for example 4, but it still displays same.
How can I solve this issue?

I tried to display data according to the page number, but I can't move to any page.


问:
Puppeteer does not get element by absolute XPath while google tools does
I need to get to a button but I need to get it by absolute XPath because on each reload the id of that button changes.
So when I try to get the button with xPath in dev tools I get the next result:

Which is the result that I need

But when I try to do it in puppeteer with the next code:

```<code>const screeners = await page.$x(
  '/html/body/div[1]/div[3]/div[2]/div/div/div[3]/div[2]/div[2]/div/div/div/div/div/div/div/div[2]/div/div/a[2]',
);console.log(screeners);
</code>```

I get : []

What may be the reason that dev tools gets the element but puppeteer doesnt?

Body:
I need to get to a button but I need to get it by absolute XPath because on each reload the id of that button changes.
So when I try to get the button with xPath in dev tools I get the next result:

Which is the result that I need

But when I try to do it in puppeteer with the next code:

const screeners = await page.$x(
  '/html/body/div[1]/div[3]/div[2]/div/div/div[3]/div[2]/div[2]/div/div/div/div/div/div/div/div[2]/div/div/a[2]',
);console.log(screeners);

I get : []

What may be the reason that dev tools gets the element but puppeteer doesnt?


问:
How to Pass a string parameter with space in C#
I am trying to retrieve data from an API. The API has its JSON properties as

```<code>
</code>```

[
{
"Name": "Dan",
"age": 10,
"isActive":true,
"Street Address": "14 VI avenue, London",
}
]

```<code>
</code>```

Am trying to map the json properties to a class I created so that I can access the view the Deseriaized object. But am having issues with creating a Property in my class that maps exactly to the JSON property "Street Address".

How can I create a property in .NET that maps exactly to the JSON property that has space.

Currently I receive an error when I do Public string Street Address {get; set;}.

I want to be able to map the Street Address property from the JSON to my defined property but I cannot because of the space

Body:
I am trying to retrieve data from an API. The API has its JSON properties as

[
{
"Name": "Dan",
"age": 10,
"isActive":true,
"Street Address": "14 VI avenue, London",
}
]

Am trying to map the json properties to a class I created so that I can access the view the Deseriaized object. But am having issues with creating a Property in my class that maps exactly to the JSON property "Street Address".

How can I create a property in .NET that maps exactly to the JSON property that has space.

Currently I receive an error when I do Public string Street Address {get; set;}.

I want to be able to map the Street Address property from the JSON to my defined property but I cannot because of the space


问:
How to setup an ASP.NET MVC 5 application in Web Farm in Windows Server 2019 / 2022?
We have a Windows Server 2019, and have deployed an ASP.NET MVC 5 application on it.

Now we are facing at some point, our web site is increasing the traffic. So we want to setup another server with it.

Now what we have is three servers. One server is used for centralize the database (SQL Server 2017 Web Edition).

Two servers are used for the deployment of the ASP.NET MVC 5 web application.

If I try to look for the documentation over Microsoft site then here is the link for guidance

https://learn.microsoft.com/en-us/iis/web-hosting/microsoft-web-farm-framework-20-for-iis-7/overview-of-the-web-farm-framework-20-for-iis

The Web Farm Framework 2.0 using Web Platform Installer tool which is mentioned in the following article

https://learn.microsoft.com/en-us/iis/web-hosting/microsoft-web-farm-framework-20-for-iis-7/setting-up-a-server-farm-with-the-web-farm-framework-20-for-iis

has been removed by Microsoft.

Please guide me, If I don't install it then How can I setup a Web Farm.

Please share the documentation If this is an absolute documentation with respect to Windows Server 2019.

We need to deploy an ASP.NET MVC 5 application.


问:
C++, How make Array List with multiple Values Per Key
I have come from Java and now want to use C++ with my Pi Pico; I am trying to make a Array list with multiple values per key.

Typically in Java, I make a setter getter class and set that to a hashmap, though I don't need this yet.

Basically I want to be able to make:

[key]
[x]
[y]
[r]
[g]
[b]

0
1
1
255
255
0.

1
2
1
200
32
32.

I tried the following, but I am not sure:

```<code>#include <iostream>

#include <unordered_map>

struct Pixel {
    int x;
    int y;
    int r;
    int g;
    int b;
};

int main() {
    std::unordered_map<int, Pixel> pixelMap;

    pixelMap[0] = { 1,1,255,255,0 };
    pixelMap[1] = { 2,1,200,32,32 };

    for (const auto& [key,pixel] : pixelMap) {
        std::cout << "Key: " << key << "\tPixel:  x: " << pixel.x  << "  y: " << pixel.y <<
            "  r: " << pixel.r << "  g: " << pixel.g << "  b: " << pixel.b << '\n';
    }
}
</code>```

Since I am new to C++, I would be happy to get some reassurance. I heard that the Stack Overflow community is very nice to newbies like me and kindly ask you for some advice.

If you need additional details for clarification, then please comment, and I will provide it.

Body:
I have come from Java and now want to use C++ with my Pi Pico; I am trying to make a Array list with multiple values per key.

Typically in Java, I make a setter getter class and set that to a hashmap, though I don't need this yet.

Basically I want to be able to make:

[key]
[x]
[y]
[r]
[g]
[b]

0
1
1
255
255
0.

1
2
1
200
32
32.

I tried the following, but I am not sure:

#include <iostream>

#include <unordered_map>

struct Pixel {
    int x;
    int y;
    int r;
    int g;
    int b;
};

int main() {
    std::unordered_map<int, Pixel> pixelMap;

    pixelMap[0] = { 1,1,255,255,0 };
    pixelMap[1] = { 2,1,200,32,32 };

    for (const auto& [key,pixel] : pixelMap) {
        std::cout << "Key: " << key << "\tPixel:  x: " << pixel.x  << "  y: " << pixel.y <<
            "  r: " << pixel.r << "  g: " << pixel.g << "  b: " << pixel.b << '\n';
    }
}

Since I am new to C++, I would be happy to get some reassurance. I heard that the Stack Overflow community is very nice to newbies like me and kindly ask you for some advice.

If you need additional details for clarification, then please comment, and I will provide it.


问:
how do I link a form to a button on react
I created a page with a register button that is supposed to take you to a form once you click on it. I did this using React. I have not been able to link the form to the button. kindly explain how I can do this

```<code>let navigate = useNavigate();
  function handleClick() {
    navigate('/Form')
    return (
      <>
        <FormComp />
        <button className='btn' onClick={handleClick}>
          <b>Register Now</b>
        </button>
      </>
</code>```

I wrote this code within the button component but it didnt work

Body:
I created a page with a register button that is supposed to take you to a form once you click on it. I did this using React. I have not been able to link the form to the button. kindly explain how I can do this

let navigate = useNavigate();
  function handleClick() {
    navigate('/Form')
    return (
      <>
        <FormComp />
        <button className='btn' onClick={handleClick}>
          Register Now
        </button>
      </>

I wrote this code within the button component but it didnt work


问:
Read copied text from clipboard when Javascript is called from native method

I am trying to read clipboard data from java native method in turn calls javascript. Below is the code

```<code> public static native String readText()/*-{
   try
     {
      var promise = $wnd.navigator.clipboard.readText();
      var resolve = function(text){
      console.log(text);
      }
      catch (e){
      //futher code goes here
      }
     }-*/;

</code>```

above code works fine till, i can get the copied value, but not sure how to return that value as String. Are there any ways to return that string.

I am expecting above function to return text copied to clipboard. In my application's context await is not supported.

Body:
I am trying to read clipboard data from java native method in turn calls javascript. Below is the code

 public static native String readText()/*-{
   try
     {
      var promise = $wnd.navigator.clipboard.readText();
      var resolve = function(text){
      console.log(text);
      }
      catch (e){
      //futher code goes here
      }
     }-*/;

above code works fine till, i can get the copied value, but not sure how to return that value as String. Are there any ways to return that string.

I am expecting above function to return text copied to clipboard. In my application's context await is not supported.


问:
store variable in a memory address x86
how to store variable in a memory address x86?

```<code>    LETTER DB ?
</code>```

MOV [0X3100], LETTER

I tried the previous solution and it gives an error message:
wrong parameters

Title: store variable in a memory address x86

Body:
how to store variable in a memory address x86?

    LETTER DB ?

MOV [0X3100], LETTER

I tried the previous solution and it gives an error message:
wrong parameters


问:
scrollIntoView functionality broken after loading changing navigation (router-link)
I have this little Ionic 6 Vue app which has two menu's - left and right.

```<code>    <IonSplitPane content-id="main-content">
      <ion-menu menuId="left-menu" side="start" content-id="main-content" type="push">
        <ion-content>
          <ion-menu-toggle menu="right-menu" autoHide="false">
            ...
          </ion-menu-toggle>
        </ion-content>
      </ion-menu>
      <ion-menu menuId="right-menu" side="end" contentId="main-content" type="overlay" :disabled="!bookHasChildren">
        <ion-content>
          <ion-menu-toggle menu="right-menu" autoHide="false">
            ...
          </ion-menu-toggle>
        </ion-content>
      </ion-menu>
      <ion-router-outlet id="main-content" ref="ionRouter"></ion-router-outlet>
    </IonSplitPane>
</code>```

When selecting a book, the right menu lists sub-chapter-links. Scrolling to those sub-chapters in the main view is implemented with the [scrollIntoView][1] method.

```<code>function scrollToElement() {
  try {
    const elementToScrollTo = divs.value.find((element) => element.localName == scrollStore.scrollElementMain);
    if (elementToScrollTo != undefined && elementToScrollTo != elementToScrollTo.offsetTop) {
      // scrolling
      elementToScrollTo.scrollIntoView();
    }
  } catch (e) {
    // logging scrolling error
  }
}
</code>```

This works fine until user clicks on left menu links where another books is loaded.
No error logging, the scrollIntoView-functionality just doesn't work anymore.

I am not sure why this breaks the scrollIntoView functionality.

Have tried so many other options and approaches, but without any success.

Demo:

Code
is on GitHub

PS:  Cannot show in code sandbox as I am using Vue with script setup and I couldn't find a free code sandbox which supports this.

Body:
I have this little Ionic 6 Vue app which has two menu's - left and right.

    <IonSplitPane content-id="main-content">
      <ion-menu menuId="left-menu" side="start" content-id="main-content" type="push">
        <ion-content>
          <ion-menu-toggle menu="right-menu" autoHide="false">
            ...
          </ion-menu-toggle>
        </ion-content>
      </ion-menu>
      <ion-menu menuId="right-menu" side="end" contentId="main-content" type="overlay" :disabled="!bookHasChildren">
        <ion-content>
          <ion-menu-toggle menu="right-menu" autoHide="false">
            ...
          </ion-menu-toggle>
        </ion-content>
      </ion-menu>
      <ion-router-outlet id="main-content" ref="ionRouter"></ion-router-outlet>
    </IonSplitPane>

When selecting a book, the right menu lists sub-chapter-links. Scrolling to those sub-chapters in the main view is implemented with the [scrollIntoView][1] method.

function scrollToElement() {
  try {
    const elementToScrollTo = divs.value.find((element) => element.localName == scrollStore.scrollElementMain);
    if (elementToScrollTo != undefined && elementToScrollTo != elementToScrollTo.offsetTop) {
      // scrolling
      elementToScrollTo.scrollIntoView();
    }
  } catch (e) {
    // logging scrolling error
  }
}

This works fine until user clicks on left menu links where another books is loaded.
No error logging, the scrollIntoView-functionality just doesn't work anymore.

I am not sure why this breaks the scrollIntoView functionality.

Have tried so many other options and approaches, but without any success.

Demo:

Code
is on GitHub

PS:  Cannot show in code sandbox as I am using Vue with script setup and I couldn't find a free code sandbox which supports this.


问:
Next.js - When accessing the same route, useEffect is not firing
I implemented the API to run when the screen is accessed using useEffect in Next.js

The code is simply written as below.

When I first access, the API of the useEffect runs normally.

However, if I go to another screen and then access the screen again, useEffect does not work.

This is the same for useEffect on other screens.

Can I run useEffect every time I access the screen?

Currently, the dependency is set to [], but if [] is removed at all, the application stops.

Which solution will help me?

```<code>  useEffect(() => {
    dispatch(getCartAction());
    dispatch(getWishlistAction());
    dispatch(getProductsAction());
  }, []);
</code>```

No matter how much I look, I can't find a problem like this.

Body:
I implemented the API to run when the screen is accessed using useEffect in Next.js

The code is simply written as below.

When I first access, the API of the useEffect runs normally.

However, if I go to another screen and then access the screen again, useEffect does not work.

This is the same for useEffect on other screens.

Can I run useEffect every time I access the screen?

Currently, the dependency is set to [], but if [] is removed at all, the application stops.

Which solution will help me?

  useEffect(() => {
    dispatch(getCartAction());
    dispatch(getWishlistAction());
    dispatch(getProductsAction());
  }, []);

No matter how much I look, I can't find a problem like this.


问:
Material Tap target prompt : Focused spinner is completely white
I am implementing Material Tap target prompt library to make a tutorial screen. I want to focus on my spinner, this is my code:

```<code>new MaterialTapTargetPrompt.Builder(MainActivity.this)
                .setTarget(spin_01)
                .setPrimaryText("Welcome")
                .setSecondaryText("You can select the bill type by clicking here")
                .setPromptBackground(new RectanglePromptBackground())
                .setPromptFocal(new RectanglePromptFocal())
                .show();
</code>```

This is my output:

enter image description here

As you can see, unlike the examples shown in the documentation page, my focused element has a complete white foreground. How do I resolve this issue? Please help me.

Body:
I am implementing Material Tap target prompt library to make a tutorial screen. I want to focus on my spinner, this is my code:

new MaterialTapTargetPrompt.Builder(MainActivity.this)
                .setTarget(spin_01)
                .setPrimaryText("Welcome")
                .setSecondaryText("You can select the bill type by clicking here")
                .setPromptBackground(new RectanglePromptBackground())
                .setPromptFocal(new RectanglePromptFocal())
                .show();

This is my output:

enter image description here

As you can see, unlike the examples shown in the documentation page, my focused element has a complete white foreground. How do I resolve this issue? Please help me.


问:
Unresolved reference: preferencesKey Android Kotlin
I'm trying to store boolean in DataStore.

```<code>class OnboardingPrefs(val context: Context) {

    companion object {
        const val ON_BOARDING_PREFS = "on_boarding_prefs"
        const val ONBOARD_KEY = "onBoard"

    }

    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
        name = ON_BOARDING_PREFS
    )

    suspend fun saveOnboarding(save: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[preferencesKey<Boolean>(ONBOARD_KEY)] = save
        }
    }
}
</code>```

Problem is preferencesKey cannot be resolved.

Gradle:

implementation 'androidx.datastore:datastore-preferences:1.0.0'

Body:
I'm trying to store boolean in DataStore.

class OnboardingPrefs(val context: Context) {

    companion object {
        const val ON_BOARDING_PREFS = "on_boarding_prefs"
        const val ONBOARD_KEY = "onBoard"

    }

    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
        name = ON_BOARDING_PREFS
    )

    suspend fun saveOnboarding(save: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[preferencesKey<Boolean>(ONBOARD_KEY)] = save
        }
    }
}

Problem is preferencesKey cannot be resolved.

Gradle:

implementation 'androidx.datastore:datastore-preferences:1.0.0'


问:
Ag-charts canvas zoom bug
I would like to comment on my problem in case someone has an idea of what it is due to or proposes an alternative solution.

Currently I have a large ag-charts graph that does not fit and it is always necessary to scroll to be able to see it in its entirety but when scrolling the axes are not maintained, so I resorted to the alternative of cloning the graph canvas twice to generate 2 new canvas clipped with "position:fixed" so that they always stay at the ends.

So far there is no problem except that if the browser zoom and/or the windows scale differs from 100%, it affects the cropping of said canvas in an inconsistent way. I was not able to get a rule of 3 to apply the correct zoom multiplier ( with ctx.drawImage() ) due to its inconsistency.

The error stops happening when you test it with a normal canvas that has not been generated by ag-charts

Here I have a very simple Live Demo to test it.
(To reproduce the bug you need to have the zoom applied before the generation of the graph).

I also tried to get the zoom level using:

```<code>(Math.round(window.devicePixelRatio*100)/100, -1);
</code>```

and applying the correspondent ratio using:

```<code>.drawImage(canvas,0, 0, canvas.width*ratio, canvas.height*ratio);
</code>```

but it only works in specific percentages of zoom

Title: Ag-charts canvas zoom bug

Body:
I would like to comment on my problem in case someone has an idea of what it is due to or proposes an alternative solution.

Currently I have a large ag-charts graph that does not fit and it is always necessary to scroll to be able to see it in its entirety but when scrolling the axes are not maintained, so I resorted to the alternative of cloning the graph canvas twice to generate 2 new canvas clipped with "position:fixed" so that they always stay at the ends.

So far there is no problem except that if the browser zoom and/or the windows scale differs from 100%, it affects the cropping of said canvas in an inconsistent way. I was not able to get a rule of 3 to apply the correct zoom multiplier ( with ctx.drawImage() ) due to its inconsistency.

The error stops happening when you test it with a normal canvas that has not been generated by ag-charts

Here I have a very simple Live Demo to test it.
(To reproduce the bug you need to have the zoom applied before the generation of the graph).

I also tried to get the zoom level using:

(Math.round(window.devicePixelRatio*100)/100, -1);

and applying the correspondent ratio using:

.drawImage(canvas,0, 0, canvas.width*ratio, canvas.height*ratio);

but it only works in specific percentages of zoom


问:
Uncaught (in promise) FirebaseError: Expected type 'pa', but it was: a custom Promise object

Expected type 'pa', but it was: a custom Promise object

Hello everyone, I am new on asking questions on Stack overflow so,

i need a guide to solve this issue here. Here in this code, I am trying to implement the Stripe checkout functionality to redirect the user to the stripe checkout page. But, when i click on the loadCheckout() button this error keeps coming. Can anybody help me fix this error ?

```<code>import { collection, getDocs, where, query, addDoc } from 'firebase/firestore/lite';
import { onSnapshot } from 'firebase/firestore';
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { selectUser } from '../features/userSlice';
import db from '../firebase';
import './Plans.css';
import { loadStripe } from '@stripe/stripe-js';

const Plans = () => {

    const [products, setProducts] = useState([]);
    const user = useSelector(selectUser);

    useEffect(() => {
        if(collection) {
            getDocs(query(collection(db, 'products'), where('active', "==", true)))
            .then((querySnapshot) => {
                const products = {}
                querySnapshot.forEach(async (productDoc) => {
                    products[productDoc.id] = productDoc.data();
                    const priceSnap = await getDocs(query(collection(db, `products/${productDoc.id}/prices`)));
                    priceSnap.docs.forEach((price) => {
                        products[productDoc.id].prices = {
                            priceId: price.id,
                            ...price.data(),
                        };
                    });
                    setProducts(products);
                });
                return querySnapshot;
            });
        }
    }, []);

    const loadCheckout = async (priceId) => {
        const firstQ = collection(db, `customers/${user.uid}/checkout_sessions`);
        const secondQ = query(
            addDoc(firstQ, {
                price: priceId,
                success_url: window.location.origin,
                cancel_url: window.location.origin,
            })
        );
        onSnapshot(secondQ, async (snap) => {
            const { error, sessionId } = snap.data();
            if(error) {
                // show error to the customer
                // inspect the cloud function logs in the firebase console.
                alert(`An error occurred: ${error.message}`);
            }
            if (sessionId) {
                // we have a stripe checkout url, let's redirect
                const stripe = await loadStripe(
                    'pk_test_51LnQj5K41BCUjAV1QSW7AAeX3XMzWJZLUNPNPKPKtHojs4wj9ECSky68tcluQQkCGMsgrA6wMQ58C0uYEWdUALja00CNIYgnnb');
                stripe.redirectToCheckout({ sessionId });
            }
        });
    }

  return (
    <div className='plans'>
      {Object.entries(products).map(([productId, productData], index) => {
        // add some logic to check if the user's subscription is active...
        return (
            <div key={index} className='plans__plan'>
                <div className='plans__info'>
                    <h5>{productData.name}</h5>
                    <h6>{productData.description}</h6>
                </div>
                <button onClick={() => loadCheckout(productData.prices.priceId)}>
                    Subscribe
                </button>
            </div>
        );
      })}
    </div>
  )
}

export default Plans;

</code>```

Error shown image

Body:
Expected type 'pa', but it was: a custom Promise object

Hello everyone, I am new on asking questions on Stack overflow so,

i need a guide to solve this issue here. Here in this code, I am trying to implement the Stripe checkout functionality to redirect the user to the stripe checkout page. But, when i click on the loadCheckout() button this error keeps coming. Can anybody help me fix this error ?

import { collection, getDocs, where, query, addDoc } from 'firebase/firestore/lite';
import { onSnapshot } from 'firebase/firestore';
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { selectUser } from '../features/userSlice';
import db from '../firebase';
import './Plans.css';
import { loadStripe } from '@stripe/stripe-js';

const Plans = () => {

    const [products, setProducts] = useState([]);
    const user = useSelector(selectUser);

    useEffect(() => {
        if(collection) {
            getDocs(query(collection(db, 'products'), where('active', "==", true)))
            .then((querySnapshot) => {
                const products = {}
                querySnapshot.forEach(async (productDoc) => {
                    products[productDoc.id] = productDoc.data();
                    const priceSnap = await getDocs(query(collection(db, `products/${productDoc.id}/prices`)));
                    priceSnap.docs.forEach((price) => {
                        products[productDoc.id].prices = {
                            priceId: price.id,
                            ...price.data(),
                        };
                    });
                    setProducts(products);
                });
                return querySnapshot;
            });
        }
    }, []);

    const loadCheckout = async (priceId) => {
        const firstQ = collection(db, `customers/${user.uid}/checkout_sessions`);
        const secondQ = query(
            addDoc(firstQ, {
                price: priceId,
                success_url: window.location.origin,
                cancel_url: window.location.origin,
            })
        );
        onSnapshot(secondQ, async (snap) => {
            const { error, sessionId } = snap.data();
            if(error) {
                // show error to the customer
                // inspect the cloud function logs in the firebase console.
                alert(`An error occurred: ${error.message}`);
            }
            if (sessionId) {
                // we have a stripe checkout url, let's redirect
                const stripe = await loadStripe(
                    'pk_test_51LnQj5K41BCUjAV1QSW7AAeX3XMzWJZLUNPNPKPKtHojs4wj9ECSky68tcluQQkCGMsgrA6wMQ58C0uYEWdUALja00CNIYgnnb');
                stripe.redirectToCheckout({ sessionId });
            }
        });
    }

  return (

      {Object.entries(products).map(([productId, productData], index) => {
        // add some logic to check if the user's subscription is active...
        return (

{productData.name}

{productData.description}

                <button onClick={() => loadCheckout(productData.prices.priceId)}>
                    Subscribe
                </button>

        );
      })}

  )
}

export default Plans;

Error shown image


问:
Excel Formula: How do I import data that match a certain team, AND only display the result until a certain date?
I trying to import our staff profile that joined from the the beginning until a month, at the same time will only display the result of a specific department.

Here is the example of my sheet

I can copy-paste until the month that I want, of course. But that would need to be updated every time I need it, so I want to turn this process from manual to auto. Unfortunately I'm not good at coming up with formulas just yet, so I would like to ask for help on this problem.

I want to import the staff data from a specific department and joined before a certain date. IT would be great if it can be automatic. Thank you in advance!


Title: How switch off wakelocks on the Android 12 automotive?

Body:
I send the system to the "Suspend-to-RAM" mode. I see active wakelocks after i run  a command "echo "1 2" > /sys/devices/platform/vehicle-dummy/power_req".

mek_8q:/ #  dumpsys suspend_control_internal

  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 |                                                                                WAKELOCK STATS                                                                                |
  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 | NAME                           | PID    | TYPE   | STATUS   | ACTIVE COUNT | TOTAL TIME   | MAX TIME     | EVENT COUNT  | WAKEUP COUNT | EXPIRE COUNT | PREVENT SUSPEND TIME | LAST CHANGE      |
  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 | usb_wakelock                   |    544 | Native | Inactive |            1 |    1622595ms |    1622595ms |          --- |          --- |          --- |                  --- |        1654936ms |
 | suspend_stats_lock             |    355 | Native | Inactive |            4 |          9ms |          3ms |          --- |          --- |          --- |                  --- |        1629116ms |
 | PowerManagerService.Broadcasts |    733 | Native | Inactive |            1 |        796ms |        796ms |          --- |          --- |          --- |                  --- |        1621593ms |
 | PowerManagerService.Display    |    733 | Native | Inactive |            1 |    1593211ms |    1593211ms |          --- |          --- |          --- |                  --- |        1620799ms |
 | ApmOutput                      |    557 | Native | Inactive |          264 |        383ms |         27ms |          --- |          --- |          --- |                  --- |        1619679ms |
 | ApmAudio                       |    557 | Native | Inactive |          234 |        817ms |         57ms |          --- |          --- |          --- |                  --- |        1619246ms |
 | PowerManagerService.WakeLocks  |    733 | Native | Active   |            1 |    1633178ms |    1633178ms |          --- |          --- |          --- |                  --- |        1667307ms |
 | PowerManager.SuspendLockout    |    733 | Native | Active   |            1 |    1639712ms |    1639712ms |          --- |          --- |          --- |                  --- |        1667307ms |
 | usb                            |    --- | Kernel | Inactive |            1 |          0ms |          0ms |            1 |            0 |            0 |                  0ms |           3005ms |
 | inotify                        |    --- | Kernel | Inactive |            2 |          4ms |          4ms |            2 |            0 |            0 |                  0ms |          50890ms |
 | alarmtimer.0.auto              |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
 | [timerfd]                      |    --- | Kernel | Inactive |            2 |         21ms |         13ms |            2 |            0 |            0 |                  0ms |          30482ms |
 | sc-powerkey                    |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
 | tcpm-source-psy-4-0051         |    --- | Kernel | Inactive |            8 |          2ms |          0ms |            8 |            0 |            0 |                  0ms |        1654945ms |
 | [timerfd]                      |    --- | Kernel | Inactive |           54 |        169ms |         74ms |           54 |            0 |            0 |                  0ms |        1607466ms |
 | [timerfd]                      |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
 | event1                         |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
 | mmc0                           |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
 | eventpoll                      |    --- | Kernel | Inactive |           64 |          2ms |          1ms |           64 |            0 |            0 |                  0ms |        1607466ms |
 |                                |    --- | Kernel | Inactive |          128 |        121ms |         24ms |          128 |            0 |            0 |                  0ms |        1646829ms |
 | battery                        |    --- | Kernel | Inactive |            1 |          0ms |          0ms |            1 |            0 |            0 |                  0ms |           2998ms |
 | eventpoll                      |    --- | Kernel | Inactive |          130 |         12ms |         10ms |          130 |            0 |            0 |                  0ms |        1646829ms |
 | scu:rtc                        |    --- | Kernel | Inactive |            1 |          0ms |          0ms |            1 |            0 |            0 |                  0ms |          30464ms |
 | [timerfd]                      |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
 | mmc1                           |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
 | [timerfd]                      |    --- | Kernel | Inactive |            8 |         15ms |          4ms |            8 |            0 |            0 |                  0ms |         694141ms |
 | event0                         |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
 | [timerfd]                      |    --- | Kernel | Inactive |            0 |          0ms |          0ms |            0 |            0 |            0 |                  0ms |              0ms |
  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

How to disable the  rest of wakelocks?

Thank you!


问:
How to implement JWT authentication from ASP.NET Core Web API to Vue.js SPA?
I made Vue.js single page application for using almost 10-15 API's which are written in ASP.NET Core Web API by me. I would like to use JWT authentication with this project. However I don't have any idea about how should I implement JWT authentication.

On backend side I store token, passwordHash and passwordSalt in User.cs model (I mean, I store in database). Then I created JWT token in controller which does register and login operations. After that I did some configuring in program.cs and tried authentication by Swagger, it works! Actually on backend side everything is okay.

```<code>public class User
{
    [Key]
    public int Id { get; set; }

    public string? Name { get; set; }
    public string? Surname { get; set; }

    public string Username { get; set; }
    public string Password { get; set; }

    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }

    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }

    public string? Gender { get; set; }
    public string? Token { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime CreatingDate { get; set; }

    public string? BioText { get; set; }

    public ICollection<Friendship> Friendships { get; set; }
    public ICollection<Content> Contents { get; set; }
}

[ApiController]
public class AuthController : ControllerBase
{
    private IUserService _service;
    private IMapper _mapper;
    private readonly IConfiguration _configuration;

    public AuthController(IMapper mapper, IConfiguration configuration)
    {
        _service = new UserManager();
        _mapper = mapper;
        _configuration = configuration;
    }

    [HttpPost("register")]
    public async Task<ActionResult<User>> Register(UserAuthDto request)
    {
        CreatePasswordHash(request.Password, out byte[] passwordHash, out byte[] passwordSalt);
        User user = _mapper.Map<User>(request);
        user.Username = request.Username;
        user.PasswordHash= passwordHash;
        user.PasswordSalt = passwordSalt;

        _service.CreateUser(user);

        return Ok(user);
    }

    [HttpPost("login")]
    public async Task<ActionResult<bool>> Login(UserAuthDto request)
    {
        User user = _service.GetAllUsers()
                            .Where(x => x.Username == request.Username)
                            .FirstOrDefault();

        if (user == null)
        {
            return BadRequest("User not found.");
        }
        else
        {
            if(!VerifyPasswordHash(request.Password, user.PasswordSalt, user.PasswordHash))
            {
                return BadRequest("Wrong Password.");
            }
            else
            {
                string token = CreateToken(user);
                user.Token = token;
                return Ok(token);
            }
        }
    }

    private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
    {
        using(var hmac = new HMACSHA512())
        {
            passwordSalt = hmac.Key;
            passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
        }
    }

    private bool VerifyPasswordHash(string password, byte[] passwordSalt, byte[] passwordHash)
    {
        using(var hmac = new HMACSHA512(passwordSalt))
        {
            var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes((string)password));
            return computedHash.SequenceEqual(passwordHash);
        }
    }

    private string CreateToken(User user)
    {
        List<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.Username),
        };

        var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value));

        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

        var token = new JwtSecurityToken(
            claims: claims,
            expires: DateTime.Now.AddDays(1),
            signingCredentials: cred);

        var jwt = new JwtSecurityTokenHandler().WriteToken(token);

        return jwt;
    }
}
</code>```

The problem is I don't know how can I use token on frontend side. I mean should I use it in body of every requests or doesn't backend need anymore token? I am open to ideas I need your help, thank you.

Body:
I made Vue.js single page application for using almost 10-15 API's which are written in ASP.NET Core Web API by me. I would like to use JWT authentication with this project. However I don't have any idea about how should I implement JWT authentication.

On backend side I store token, passwordHash and passwordSalt in User.cs model (I mean, I store in database). Then I created JWT token in controller which does register and login operations. After that I did some configuring in program.cs and tried authentication by Swagger, it works! Actually on backend side everything is okay.

public class User
{
    [Key]
    public int Id { get; set; }

    public string? Name { get; set; }
    public string? Surname { get; set; }

    public string Username { get; set; }
    public string Password { get; set; }

    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }

    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }

    public string? Gender { get; set; }
    public string? Token { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime CreatingDate { get; set; }

    public string? BioText { get; set; }

    public ICollection<Friendship> Friendships { get; set; }
    public ICollection<Content> Contents { get; set; }
}

[ApiController]
public class AuthController : ControllerBase
{
    private IUserService _service;
    private IMapper _mapper;
    private readonly IConfiguration _configuration;

    public AuthController(IMapper mapper, IConfiguration configuration)
    {
        _service = new UserManager();
        _mapper = mapper;
        _configuration = configuration;
    }

    [HttpPost("register")]
    public async Task<ActionResult<User>> Register(UserAuthDto request)
    {
        CreatePasswordHash(request.Password, out byte[] passwordHash, out byte[] passwordSalt);
        User user = _mapper.Map<User>(request);
        user.Username = request.Username;
        user.PasswordHash= passwordHash;
        user.PasswordSalt = passwordSalt;

        _service.CreateUser(user);

        return Ok(user);
    }

    [HttpPost("login")]
    public async Task<ActionResult<bool>> Login(UserAuthDto request)
    {
        User user = _service.GetAllUsers()
                            .Where(x => x.Username == request.Username)
                            .FirstOrDefault();

        if (user == null)
        {
            return BadRequest("User not found.");
        }
        else
        {
            if(!VerifyPasswordHash(request.Password, user.PasswordSalt, user.PasswordHash))
            {
                return BadRequest("Wrong Password.");
            }
            else
            {
                string token = CreateToken(user);
                user.Token = token;
                return Ok(token);
            }
        }
    }

    private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
    {
        using(var hmac = new HMACSHA512())
        {
            passwordSalt = hmac.Key;
            passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
        }
    }

    private bool VerifyPasswordHash(string password, byte[] passwordSalt, byte[] passwordHash)
    {
        using(var hmac = new HMACSHA512(passwordSalt))
        {
            var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes((string)password));
            return computedHash.SequenceEqual(passwordHash);
        }
    }

    private string CreateToken(User user)
    {
        List<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.Username),
        };

        var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value));

        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

        var token = new JwtSecurityToken(
            claims: claims,
            expires: DateTime.Now.AddDays(1),
            signingCredentials: cred);

        var jwt = new JwtSecurityTokenHandler().WriteToken(token);

        return jwt;
    }
}

The problem is I don't know how can I use token on frontend side. I mean should I use it in body of every requests or doesn't backend need anymore token? I am open to ideas I need your help, thank you.


问:
Issue with Pytest : "import error : Module not found error "
```<code>repo/
   |--app.py
   |--settings.py
   |--models.py
   |--tests/
     |--uploders
      |--test_app.py
      |--utility.py
</code>```

I have my pytest file in uploaders folder. I have utility.py file from which i want to call the functions in my test file. but i am able to import the utility.py module.I am getting error as

```<code>ModuleNotFoundError: No module named 'utility'.
</code>```

I have tried to add init.py file in uploaders. But that doesn't work

Body:
repo/
   |--app.py
   |--settings.py
   |--models.py
   |--tests/
     |--uploders
      |--test_app.py
      |--utility.py

I have my pytest file in uploaders folder. I have utility.py file from which i want to call the functions in my test file. but i am able to import the utility.py module.I am getting error as

ModuleNotFoundError: No module named 'utility'.

I have tried to add init.py file in uploaders. But that doesn't work


问:
Remove documents not linked by DBRef mongodb
Hello everyone I try to remove all documents which are no link by an DBRef field.

For example I have 2 collections User and Order.

Let's say User collection has this structure :

```<code>{
  "_id": "12345",
  "lastName": "Michael",
  "firstName": "Bernard"
}
</code>```

And Order collection has this structure :

```<code>{
  "_id": "123456",
  "orderDate": "2022-12-26",
  "userWhoOrder": {
    "$ref": "user",
    "$id": "12345"
  },
  "userWhoPay": {
    "$ref": "user",
    "$id": "123456"
  }
}
</code>```

Note : userWhoOrder and userWhoPay are DBRef fields (and it can be the same user).

So I want remove all users who are not present in order collection (neither userWhoOrder neither userWhoPay).

I know I can do this in 2 steps :

Get a list of userWhoOrder and userWhoPay from order collection.

Filter users list which not contains users of step 1 and remove them.

But I want to know if there are a properly way to do this with a single request (using $lookup for example).

Here is what I tried for getting a users list to remove :

```<code>db.getCollection("user").aggregate[{$lookup: {
  from: "order",
  let: {userId: "$_id"},
  pipeline: [
    {$match: {$expr: {
      $and: [
        {$ne: ["$userWhoOrder.$id", "$$userId"]},
        {$ne: ["$userWhoPay.$id", "$$userId"]}
      ]
    }}}
  ],

  as: "result"
}]
</code>```

Body:
Hello everyone I try to remove all documents which are no link by an DBRef field.

For example I have 2 collections User and Order.

Let's say User collection has this structure :

{
  "_id": "12345",
  "lastName": "Michael",
  "firstName": "Bernard"
}

And Order collection has this structure :

{
  "_id": "123456",
  "orderDate": "2022-12-26",
  "userWhoOrder": {
    "$ref": "user",
    "$id": "12345"
  },
  "userWhoPay": {
    "$ref": "user",
    "$id": "123456"
  }
}

Note : userWhoOrder and userWhoPay are DBRef fields (and it can be the same user).

So I want remove all users who are not present in order collection (neither userWhoOrder neither userWhoPay).

I know I can do this in 2 steps :

Get a list of userWhoOrder and userWhoPay from order collection.

Filter users list which not contains users of step 1 and remove them.

But I want to know if there are a properly way to do this with a single request (using $lookup for example).

Here is what I tried for getting a users list to remove :

db.getCollection("user").aggregate[{$lookup: {
  from: "order",
  let: {userId: "$_id"},
  pipeline: [
    {$match: {$expr: {
      $and: [
        {$ne: ["$userWhoOrder.$id", "$$userId"]},
        {$ne: ["$userWhoPay.$id", "$$userId"]}
      ]
    }}}
  ],

  as: "result"
}]