问:
Delete function and update function could not perform in cloud firestore
```<code>1) This is the create campaign activity which creates the campaign and candidate

class CreateCampaignActivity : AppCompatActivity() {

    private lateinit var startDateTimeTextView: TextView
    private lateinit var endDateTimeTextView: TextView
    private lateinit var titleEditText: TextInputEditText
    private lateinit var db: FirebaseFirestore

    private lateinit var candidate1Text: TextInputEditText
    private lateinit var candidate2Text: TextInputEditText
    private lateinit var candidate3Text: TextInputEditText
    private lateinit var addCampaignButton : Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_create_campaign)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.title = "Create New Campaign"

        titleEditText = findViewById(R.id.textTitle)
        startDateTimeTextView = findViewById(R.id.start_date_time)
        endDateTimeTextView = findViewById(R.id.end_date_time)
        addCampaignButton = findViewById(R.id.btnAddCampaign)

        candidate1Text = findViewById(R.id.textCandidate1)
        candidate2Text = findViewById(R.id.textCandidate2)
        candidate3Text = findViewById(R.id.textCandidate3)

        db = FirebaseFirestore.getInstance()

        addCampaignButton.setOnClickListener {
            val title = titleEditText.text.toString().trim()
            val startDateTime = startDateTimeTextView.text.toString().trim()
            val endDateTime = endDateTimeTextView.text.toString().trim()
            val candidate1Name = candidate1Text.text.toString().trim()
            val candidate2Name = candidate2Text.text.toString().trim()
            val candidate3Name = candidate3Text.text.toString().trim()

            if (title.isEmpty() || startDateTime.isEmpty() || endDateTime.isEmpty() || candidate1Name.isEmpty() || candidate2Name.isEmpty() || candidate3Name.isEmpty()) {
                Toast.makeText(this@CreateCampaignActivity, "Please fill up empty fields", Toast.LENGTH_SHORT).show()
            } else if (!isEndTimeValid(startDateTime, endDateTime)) {
                // Show error message or toast indicating that end time must be after start time
                Toast.makeText(this@CreateCampaignActivity, "The end time must be after start time", Toast.LENGTH_SHORT).show()
            } else {
                val format = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US)
                val startTimestamp = Timestamp(format.parse(startDateTime)!!)
                val endTimestamp = Timestamp(format.parse(endDateTime)!!)
                val campaign = Campaign(
                    id = UUID.randomUUID().toString(),
                    title = title,
                    startDateTime = startTimestamp,
                    endDateTime = endTimestamp,
                    candidate1 = Candidate(
                        id = UUID.randomUUID().toString(),
                        name = candidate1Name
                    ),
                    candidate2 = Candidate(
                        id = UUID.randomUUID().toString(),
                        name = candidate2Name
                    ),
                    candidate3 = Candidate(id = UUID.randomUUID().toString(), name = candidate3Name)
                )
                // Add the campaign to the Firestore database
                db.collection("campaigns")
                    .add(campaign)
                    .addOnSuccessListener { documentReference ->
                        campaign.id = documentReference.id
                        Log.d(
                            TAG,
                            "Campaign successfully added to Firestore with ID: ${documentReference.id}"
                        )
                // Show success message or toast indicating that the campaign was successfully added
                        Toast.makeText(this@CreateCampaignActivity, "Campaign successfully added", Toast.LENGTH_SHORT).show()
                // Clear the input fields
                        titleEditText.setText("")
                        startDateTimeTextView.text = ""
                        endDateTimeTextView.text = ""
                        candidate1Text.setText("")
                        candidate2Text.setText("")
                        candidate3Text.setText("")
                    // Navigate back to the previous activity
                        finish()
                    }
                    .addOnFailureListener { e ->
                        Log.w(TAG, "Error adding campaign to Firestore", e)
                        // Show error message or toast indicating that there was an error adding the campaign
                        Toast.makeText(this@CreateCampaignActivity, "Error adding campaign", Toast.LENGTH_SHORT).show()
                    }
            }

            startDateTimeTextView.setOnClickListener {
                showStartDateTimeDialog()
            }

            endDateTimeTextView.setOnClickListener {
                showEndDateTimeDialog()
            }
        }
    }
    private fun showStartDateTimeDialog() {
        // Code to show the DatePicker and TimePicker dialogs
        val calendar = Calendar.getInstance()
        val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, day ->
            calendar.set(Calendar.YEAR, year)
            calendar.set(Calendar.MONTH, month)
            calendar.set(Calendar.DAY_OF_MONTH, day)
            val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hour)
                calendar.set(Calendar.MINUTE, minute)
                startDateTimeTextView.text =
                    SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(calendar.time)
            }
            TimePickerDialog(
                this@CreateCampaignActivity,
                timeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
            ).show()
        }
        DatePickerDialog(
            this@CreateCampaignActivity,
            dateSetListener,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    private fun showEndDateTimeDialog() {
        // Code to show the DatePicker and TimePicker dialogs
        val calendar = Calendar.getInstance()
        val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, day ->
            calendar.set(Calendar.YEAR, year)
            calendar.set(Calendar.MONTH, month)
            calendar.set(Calendar.DAY_OF_MONTH, day)
            val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hour)
                calendar.set(Calendar.MINUTE, minute)
                endDateTimeTextView.text =
                    SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(calendar.time)
            }
            TimePickerDialog(
                this@CreateCampaignActivity,
                timeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),
                true
            ).show()
        }
        DatePickerDialog(
            this@CreateCampaignActivity,
            dateSetListener,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    private fun isEndTimeValid(startDateTime: String, endDateTime: String): Boolean {
        // Code to check if the end time is valid (i.e. after the start time)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        val startDate = sdf.parse(startDateTime)
        val endDate = sdf.parse(endDateTime)
        return endDate?.after(startDate) ?: false
    }

    companion object {
        private const val TAG = "CreateCampaignActivity"
    }
}

2) This is the edit campaign Activity to edit and delete campaign

class EditCampaignActivity : AppCompatActivity() {

    private lateinit var datetimeTextView: TextView
    private lateinit var titleEditText: TextInputEditText
    private lateinit var db: FirebaseFirestore

    private lateinit var candidate1Text: TextInputEditText
    private lateinit var candidate2Text: TextInputEditText
    private lateinit var candidate3Text: TextInputEditText
    private lateinit var editCampaign : Button
    private lateinit var delCampaign: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_campaign)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.title = "Edit Campaign"

        titleEditText = findViewById(R.id.textTitle)
        datetimeTextView = findViewById(R.id.DateTime)
        delCampaign = findViewById(R.id.btndelCampaign)
        editCampaign = findViewById(R.id.btnSaveCampaign)
        db = FirebaseFirestore.getInstance()

        candidate1Text = findViewById(R.id.textCandidate1)
        candidate2Text = findViewById(R.id.textCandidate2)
        candidate3Text = findViewById(R.id.textCandidate3)

        intent.getStringExtra("CAMPAIGN_ID")
        val campaign = intent.getParcelableExtra<Campaign>("CAMPAIGN_DATA")

        if (campaign != null) {
            intent.putExtra("CAMPAIGN_ID", campaign.id)
        }
        if (campaign != null) {
            titleEditText.setText(campaign.title)
        }
        if (campaign != null) {
            datetimeTextView.text = campaign.endDateTime.toDate().toString()
        }
        if (campaign != null) {
            candidate1Text.setText(campaign.candidate1.name)
        }
        if (campaign != null) {
            candidate2Text.setText(campaign.candidate2.name)
        }
        if (campaign != null) {
            candidate3Text.setText(campaign.candidate3.name)
        }

        //Update function
        editCampaign.setOnClickListener {
            // Update the fields of the Campaign object
            val updatedTitle = titleEditText.text.toString()
            val updatedCandidate1 = candidate1Text.text.toString()
            val updatedCandidate2 = candidate2Text.text.toString()
            val updatedCandidate3 = candidate3Text.text.toString()

            campaign?.apply {
                title = updatedTitle
                endDateTime = Timestamp.now()
                candidate1.name = updatedCandidate1
                candidate2.name = updatedCandidate2
                candidate3.name = updatedCandidate3
            }

            if (campaign != null) {
                db.collection("campaigns").document(campaign.id)
                    .update(mapOf(
                        "title" to updatedTitle,
                        "endDateTime" to Timestamp.now(),
                        "candidate1" to mapOf(
                            "name" to updatedCandidate1
                        ),
                        "candidate2" to mapOf(
                            "name" to updatedCandidate2
                        ),
                        "candidate3" to mapOf(
                            "name" to updatedCandidate3
                        )
                    ))
                    .addOnSuccessListener {
                        // Update successful, show a message to the user
                        Toast.makeText(this, "Campaign updated", Toast.LENGTH_SHORT).show()
                    }
                    .addOnFailureListener {
                        // Update failed, show an error message
                        Toast.makeText(this, "Error updating campaign: $it", Toast.LENGTH_SHORT).show()
                    }
            }
                    // Confirm the edit action with the user
                    AlertDialog.Builder(this)
                        .setTitle("Edit Campaign")
                        .setMessage("Are you sure you want to save the changes to this campaign?")
                        .setPositiveButton("Yes") { _, _ ->
                            // Navigate back to the OrganiserActivity
                            finish()
                        }
                        .setNegativeButton("No", null)
                        .show()
        }

       // perform delete function
        delCampaign.setOnClickListener {
            // Show a message dialog to confirm the delete action
            AlertDialog.Builder(this)
                .setTitle("Delete Campaign")
                .setMessage("Are you sure you want to delete this campaign?")
                .setPositiveButton("Yes") { _, _ ->
                    if (campaign != null) {
                        deleteCampaign(campaign)
                    }
                }
                .setNegativeButton("No", null)
                .show()
        }

    }

    private fun deleteCampaign(campaign: Campaign) {
        db.collection("campaigns").document(campaign.id).delete()
            .addOnSuccessListener {
                // Navigate back to the OrganiserActivity
                finish()
            }
            .addOnFailureListener { e ->
                // Show an error message
                Toast.makeText(this, "Error deleting campaign: ${e.message}", Toast.LENGTH_SHORT).show()
            }
    }
}
</code>```

The problem is I can't perform the delete and update function in the edit campaign activity. Whenever I created a new campaign from createCampaignActivity, I tried to edit the campaign and it states in the message dialog that firestore database has no document to update even though the document exists in the firestorm. How to solve this issue?

Body:
1) This is the create campaign activity which creates the campaign and candidate

class CreateCampaignActivity : AppCompatActivity() {

    private lateinit var startDateTimeTextView: TextView
    private lateinit var endDateTimeTextView: TextView
    private lateinit var titleEditText: TextInputEditText
    private lateinit var db: FirebaseFirestore

    private lateinit var candidate1Text: TextInputEditText
    private lateinit var candidate2Text: TextInputEditText
    private lateinit var candidate3Text: TextInputEditText
    private lateinit var addCampaignButton : Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_create_campaign)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.title = "Create New Campaign"

        titleEditText = findViewById(R.id.textTitle)
        startDateTimeTextView = findViewById(R.id.start_date_time)
        endDateTimeTextView = findViewById(R.id.end_date_time)
        addCampaignButton = findViewById(R.id.btnAddCampaign)

        candidate1Text = findViewById(R.id.textCandidate1)
        candidate2Text = findViewById(R.id.textCandidate2)
        candidate3Text = findViewById(R.id.textCandidate3)

        db = FirebaseFirestore.getInstance()

        addCampaignButton.setOnClickListener {
            val title = titleEditText.text.toString().trim()
            val startDateTime = startDateTimeTextView.text.toString().trim()
            val endDateTime = endDateTimeTextView.text.toString().trim()
            val candidate1Name = candidate1Text.text.toString().trim()
            val candidate2Name = candidate2Text.text.toString().trim()
            val candidate3Name = candidate3Text.text.toString().trim()

            if (title.isEmpty() || startDateTime.isEmpty() || endDateTime.isEmpty() || candidate1Name.isEmpty() || candidate2Name.isEmpty() || candidate3Name.isEmpty()) {
                Toast.makeText(this@CreateCampaignActivity, "Please fill up empty fields", Toast.LENGTH_SHORT).show()
            } else if (!isEndTimeValid(startDateTime, endDateTime)) {
                // Show error message or toast indicating that end time must be after start time
                Toast.makeText(this@CreateCampaignActivity, "The end time must be after start time", Toast.LENGTH_SHORT).show()
            } else {
                val format = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US)
                val startTimestamp = Timestamp(format.parse(startDateTime)!!)
                val endTimestamp = Timestamp(format.parse(endDateTime)!!)
                val campaign = Campaign(
                    id = UUID.randomUUID().toString(),
                    title = title,
                    startDateTime = startTimestamp,
                    endDateTime = endTimestamp,
                    candidate1 = Candidate(
                        id = UUID.randomUUID().toString(),
                        name = candidate1Name
                    ),
                    candidate2 = Candidate(
                        id = UUID.randomUUID().toString(),
                        name = candidate2Name
                    ),
                    candidate3 = Candidate(id = UUID.randomUUID().toString(), name = candidate3Name)
                )
                // Add the campaign to the Firestore database
                db.collection("campaigns")
                    .add(campaign)
                    .addOnSuccessListener { documentReference ->
                        campaign.id = documentReference.id
                        Log.d(
                            TAG,
                            "Campaign successfully added to Firestore with ID: ${documentReference.id}"
                        )
                // Show success message or toast indicating that the campaign was successfully added
                        Toast.makeText(this@CreateCampaignActivity, "Campaign successfully added", Toast.LENGTH_SHORT).show()
                // Clear the input fields
                        titleEditText.setText("")
                        startDateTimeTextView.text = ""
                        endDateTimeTextView.text = ""
                        candidate1Text.setText("")
                        candidate2Text.setText("")
                        candidate3Text.setText("")
                    // Navigate back to the previous activity
                        finish()
                    }
                    .addOnFailureListener { e ->
                        Log.w(TAG, "Error adding campaign to Firestore", e)
                        // Show error message or toast indicating that there was an error adding the campaign
                        Toast.makeText(this@CreateCampaignActivity, "Error adding campaign", Toast.LENGTH_SHORT).show()
                    }
            }

            startDateTimeTextView.setOnClickListener {
                showStartDateTimeDialog()
            }

            endDateTimeTextView.setOnClickListener {
                showEndDateTimeDialog()
            }
        }
    }
    private fun showStartDateTimeDialog() {
        // Code to show the DatePicker and TimePicker dialogs
        val calendar = Calendar.getInstance()
        val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, day ->
            calendar.set(Calendar.YEAR, year)
            calendar.set(Calendar.MONTH, month)
            calendar.set(Calendar.DAY_OF_MONTH, day)
            val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hour)
                calendar.set(Calendar.MINUTE, minute)
                startDateTimeTextView.text =
                    SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(calendar.time)
            }
            TimePickerDialog(
                this@CreateCampaignActivity,
                timeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
            ).show()
        }
        DatePickerDialog(
            this@CreateCampaignActivity,
            dateSetListener,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    private fun showEndDateTimeDialog() {
        // Code to show the DatePicker and TimePicker dialogs
        val calendar = Calendar.getInstance()
        val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, day ->
            calendar.set(Calendar.YEAR, year)
            calendar.set(Calendar.MONTH, month)
            calendar.set(Calendar.DAY_OF_MONTH, day)
            val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hour)
                calendar.set(Calendar.MINUTE, minute)
                endDateTimeTextView.text =
                    SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(calendar.time)
            }
            TimePickerDialog(
                this@CreateCampaignActivity,
                timeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),
                true
            ).show()
        }
        DatePickerDialog(
            this@CreateCampaignActivity,
            dateSetListener,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    private fun isEndTimeValid(startDateTime: String, endDateTime: String): Boolean {
        // Code to check if the end time is valid (i.e. after the start time)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        val startDate = sdf.parse(startDateTime)
        val endDate = sdf.parse(endDateTime)
        return endDate?.after(startDate) ?: false
    }

    companion object {
        private const val TAG = "CreateCampaignActivity"
    }
}

2) This is the edit campaign Activity to edit and delete campaign

class EditCampaignActivity : AppCompatActivity() {

    private lateinit var datetimeTextView: TextView
    private lateinit var titleEditText: TextInputEditText
    private lateinit var db: FirebaseFirestore

    private lateinit var candidate1Text: TextInputEditText
    private lateinit var candidate2Text: TextInputEditText
    private lateinit var candidate3Text: TextInputEditText
    private lateinit var editCampaign : Button
    private lateinit var delCampaign: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_campaign)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.title = "Edit Campaign"

        titleEditText = findViewById(R.id.textTitle)
        datetimeTextView = findViewById(R.id.DateTime)
        delCampaign = findViewById(R.id.btndelCampaign)
        editCampaign = findViewById(R.id.btnSaveCampaign)
        db = FirebaseFirestore.getInstance()

        candidate1Text = findViewById(R.id.textCandidate1)
        candidate2Text = findViewById(R.id.textCandidate2)
        candidate3Text = findViewById(R.id.textCandidate3)

        intent.getStringExtra("CAMPAIGN_ID")
        val campaign = intent.getParcelableExtra<Campaign>("CAMPAIGN_DATA")

        if (campaign != null) {
            intent.putExtra("CAMPAIGN_ID", campaign.id)
        }
        if (campaign != null) {
            titleEditText.setText(campaign.title)
        }
        if (campaign != null) {
            datetimeTextView.text = campaign.endDateTime.toDate().toString()
        }
        if (campaign != null) {
            candidate1Text.setText(campaign.candidate1.name)
        }
        if (campaign != null) {
            candidate2Text.setText(campaign.candidate2.name)
        }
        if (campaign != null) {
            candidate3Text.setText(campaign.candidate3.name)
        }

        //Update function
        editCampaign.setOnClickListener {
            // Update the fields of the Campaign object
            val updatedTitle = titleEditText.text.toString()
            val updatedCandidate1 = candidate1Text.text.toString()
            val updatedCandidate2 = candidate2Text.text.toString()
            val updatedCandidate3 = candidate3Text.text.toString()

            campaign?.apply {
                title = updatedTitle
                endDateTime = Timestamp.now()
                candidate1.name = updatedCandidate1
                candidate2.name = updatedCandidate2
                candidate3.name = updatedCandidate3
            }

            if (campaign != null) {
                db.collection("campaigns").document(campaign.id)
                    .update(mapOf(
                        "title" to updatedTitle,
                        "endDateTime" to Timestamp.now(),
                        "candidate1" to mapOf(
                            "name" to updatedCandidate1
                        ),
                        "candidate2" to mapOf(
                            "name" to updatedCandidate2
                        ),
                        "candidate3" to mapOf(
                            "name" to updatedCandidate3
                        )
                    ))
                    .addOnSuccessListener {
                        // Update successful, show a message to the user
                        Toast.makeText(this, "Campaign updated", Toast.LENGTH_SHORT).show()
                    }
                    .addOnFailureListener {
                        // Update failed, show an error message
                        Toast.makeText(this, "Error updating campaign: $it", Toast.LENGTH_SHORT).show()
                    }
            }
                    // Confirm the edit action with the user
                    AlertDialog.Builder(this)
                        .setTitle("Edit Campaign")
                        .setMessage("Are you sure you want to save the changes to this campaign?")
                        .setPositiveButton("Yes") { _, _ ->
                            // Navigate back to the OrganiserActivity
                            finish()
                        }
                        .setNegativeButton("No", null)
                        .show()
        }

       // perform delete function
        delCampaign.setOnClickListener {
            // Show a message dialog to confirm the delete action
            AlertDialog.Builder(this)
                .setTitle("Delete Campaign")
                .setMessage("Are you sure you want to delete this campaign?")
                .setPositiveButton("Yes") { _, _ ->
                    if (campaign != null) {
                        deleteCampaign(campaign)
                    }
                }
                .setNegativeButton("No", null)
                .show()
        }

    }

    private fun deleteCampaign(campaign: Campaign) {
        db.collection("campaigns").document(campaign.id).delete()
            .addOnSuccessListener {
                // Navigate back to the OrganiserActivity
                finish()
            }
            .addOnFailureListener { e ->
                // Show an error message
                Toast.makeText(this, "Error deleting campaign: ${e.message}", Toast.LENGTH_SHORT).show()
            }
    }
}

The problem is I can't perform the delete and update function in the edit campaign activity. Whenever I created a new campaign from createCampaignActivity, I tried to edit the campaign and it states in the message dialog that firestore database has no document to update even though the document exists in the firestorm. How to solve this issue?


来源: stackexchange

问:
OnInitializedAsync() Issue with Blazor Telerik
Im using Telerik Blazor controls, I am using mt API to return data which works fine when I check it from an API perspective. My web app has issues as it errors as I believe there is no data. To my knowledge this is due to OnInitializedAsync(). Below is my code:

```<code><TelerikScheduler Data="@HolidayPlanners" @bind-Date="@StartDate" @bind-View="@selectedView" Height="100%" Class="Scheduler" OnCreate="@AddAppointment"
              OnUpdate="@UpdateAppointment" OnDelete="@DeleteAppointment"
              AllowCreate="true" AllowDelete="true" AllowUpdate="true"
              IdField="@(nameof(UvwHolidayPlanner.Pk))"
              StartField="@(nameof(UvwHolidayPlanner.StartDate))"
              EndField="@(nameof(UvwHolidayPlanner.EndDate))"
              TitleField="@(nameof(UvwHolidayPlanner.Title))"
              DescriptionField="@(nameof(UvwHolidayPlanner.Description))"
              IsAllDayField="@(nameof(UvwHolidayPlanner.IsAllDay))"
              RecurrenceRuleField="@(nameof(UvwHolidayPlanner.RecurrenceRule))"
              RecurrenceExceptionsField="@(nameof(UvwHolidayPlanner.RecurrenceExceptions))"
              RecurrenceIdField="@(nameof(UvwHolidayPlanner.RecurrenceFk))">
<SchedulerViews>
    <SchedulerMonthView></SchedulerMonthView>
</SchedulerViews>
</code>```

@code {

```<code>public string _URL = String.Empty;

IEnumerable<UvwHolidayPlanner> HolidayPlanners { get; set; }

DateTime StartDate = DateTime.Now;

SchedulerView selectedView { get; set; } = SchedulerView.Month;

protected override async Task OnInitializedAsync()
{
    _URL = settingsAccessor.AllClientSettings().BaseServiceURI;

    HolidayPlanners = (await http.CreateClient("ClientSettings").GetFromJsonAsync<List<UvwHolidayPlanner>>($"{_URL}/lookup/HolidayPlanner"))
    .OrderBy(t => t.Title)
    .ToList();

    StateHasChanged();

}

//private void LoadData()
//{
    //Appointments = appointmentService.GetAppointments();
//}

void UpdateAppointment(SchedulerUpdateEventArgs args)
{
    //appointmentService.UpdateAppointment((AppointmentDto)args.Item);
    //LoadData();
}

void AddAppointment(SchedulerCreateEventArgs args)
{
    //appointmentService.CreateAppointment((AppointmentDto)args.Item);
    //LoadData();
}

void DeleteAppointment(SchedulerDeleteEventArgs args)
{
    //appointmentService.DeleteAppointment((AppointmentDto)args.Item);
    //LoadData();
}
</code>```

}

My HolidayPlanners property seems to return null & it errors. Unsure if this is because the UI Components have already initialized.

Below is a message within the 404 error unsure if thats an issue:

```<code>ProjectManager.Pages.Pages__Host.<ExecuteAsync>b__15_1() in _Host.cshtml

    <component type="typeof(App)" render-mode="ServerPrerendered" />
</code>```

I have tried render-mode="Server" & "Static"

ContentLicense: CC BY-SA 4.0

Body:
Im using Telerik Blazor controls, I am using mt API to return data which works fine when I check it from an API perspective. My web app has issues as it errors as I believe there is no data. To my knowledge this is due to OnInitializedAsync(). Below is my code:

<TelerikScheduler Data="@HolidayPlanners" @bind-Date="@StartDate" @bind-View="@selectedView" Height="100%" Class="Scheduler" OnCreate="@AddAppointment"
              OnUpdate="@UpdateAppointment" OnDelete="@DeleteAppointment"
              AllowCreate="true" AllowDelete="true" AllowUpdate="true"
              IdField="@(nameof(UvwHolidayPlanner.Pk))"
              StartField="@(nameof(UvwHolidayPlanner.StartDate))"
              EndField="@(nameof(UvwHolidayPlanner.EndDate))"
              TitleField="@(nameof(UvwHolidayPlanner.Title))"
              DescriptionField="@(nameof(UvwHolidayPlanner.Description))"
              IsAllDayField="@(nameof(UvwHolidayPlanner.IsAllDay))"
              RecurrenceRuleField="@(nameof(UvwHolidayPlanner.RecurrenceRule))"
              RecurrenceExceptionsField="@(nameof(UvwHolidayPlanner.RecurrenceExceptions))"
              RecurrenceIdField="@(nameof(UvwHolidayPlanner.RecurrenceFk))">
<SchedulerViews>
    <SchedulerMonthView></SchedulerMonthView>
</SchedulerViews>

@code {

public string _URL = String.Empty;

IEnumerable<UvwHolidayPlanner> HolidayPlanners { get; set; }

DateTime StartDate = DateTime.Now;

SchedulerView selectedView { get; set; } = SchedulerView.Month;

protected override async Task OnInitializedAsync()
{
    _URL = settingsAccessor.AllClientSettings().BaseServiceURI;

    HolidayPlanners = (await http.CreateClient("ClientSettings").GetFromJsonAsync<List<UvwHolidayPlanner>>($"{_URL}/lookup/HolidayPlanner"))
    .OrderBy(t => t.Title)
    .ToList();

    StateHasChanged();

}

//private void LoadData()
//{
    //Appointments = appointmentService.GetAppointments();
//}

void UpdateAppointment(SchedulerUpdateEventArgs args)
{
    //appointmentService.UpdateAppointment((AppointmentDto)args.Item);
    //LoadData();
}

void AddAppointment(SchedulerCreateEventArgs args)
{
    //appointmentService.CreateAppointment((AppointmentDto)args.Item);
    //LoadData();
}

void DeleteAppointment(SchedulerDeleteEventArgs args)
{
    //appointmentService.DeleteAppointment((AppointmentDto)args.Item);
    //LoadData();
}

}

My HolidayPlanners property seems to return null & it errors. Unsure if this is because the UI Components have already initialized.

Below is a message within the 404 error unsure if thats an issue:

ProjectManager.Pages.Pages__Host.<ExecuteAsync>b__15_1() in _Host.cshtml

    <component type="typeof(App)" render-mode="ServerPrerendered" />

I have tried render-mode="Server" & "Static"


问:
Adding a runtime to Docker Desktop
I am trying to add a runtime to Docker. The caveat is that it is Docker Desktop.

Normally you add the runtime to the deamon.json file like shown in Docker runtime execution options:

{
  "runtimes": {
    "custom": {
      "path": "/path/to/runtime"
    }
  }
}
```
<p>The problem is that Docker does not find that path, although I have it in my WSL distribution. Therefore, I suspect it's not looking inside the distribution for that path.</p>
<p>I also tried to add the binary to the other WSL distributions <code>docker-desktop</code> and  <code>docker-desktop-data</code> without success.</p>
<p>When I try to run a container, I get an error:</p>
<pre class="lang-none prettyprint-override"><code>docker run --runtime=custom myapp
</code>```

Output:

...
OCI runtime create failed:
fork/exec /path/to/runtime: no such file or directory: unknown
```

Title: Adding a runtime to Docker Desktop

Body:
I am trying to add a runtime to Docker. The caveat is that it is Docker Desktop.

Normally you add the runtime to the deamon.json file like shown in Docker runtime execution options:

{
  "runtimes": {
    "custom": {
      "path": "/path/to/runtime"
    }
  }
}

The problem is that Docker does not find that path, although I have it in my WSL distribution. Therefore, I suspect it's not looking inside the distribution for that path.

I also tried to add the binary to the other WSL distributions docker-desktop and  docker-desktop-data without success.

When I try to run a container, I get an error:

docker run --runtime=custom myapp

Output:

...
OCI runtime create failed:
fork/exec /path/to/runtime: no such file or directory: unknown


问:
why Visual Studio Code is get slower and freezes and suddenly gives not responsing message
I have a problem with VS Code: whenever I code, debug, or run the code on my physical device using Flutter, it gets very slow, freezes, and shows "Windows is not responding: Reopen!" I disabled all the extensions, but nothing worked. I even tried some commands like deleting the user directory and disabling the extensions, but I still faced the same issue. I deleted the cache in AppData/Roaming/code, but still no luck. I also deleted the code file, and the same issue still exists! I even did this: -Open the Command Palette (Ctrl+Shift+P). Run the Preferences: Configure Runtime Arguments -Add "disable-hardware-acceleration": true. -Restart VS Code. I have looked it up all over the internet, and nothing worked! Please help me! these are the extntion:

Device Specifications:
Device name BadriyaHaddad
Processor   Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz   2.60 GHz
Installed RAM   12.0 GB (11.9 GB usable)
Device ID   7B1CE693-8DEC-426E-B6FB-54CC3FADE82A
Product ID  00331-10000-00001-AA635
System type 64-bit operating system, x64-based processor
Pen and touch   No pen or touch input is available for this display
Windows Specifications:
Edition Windows 10 Pro
Version 22H2
Installed on    11/27/2022
OS build    19045.2364
Experience  Windows Feature Experience Pack 120.2212.4190.0
```

enter image description here

Body:
I have a problem with VS Code: whenever I code, debug, or run the code on my physical device using Flutter, it gets very slow, freezes, and shows "Windows is not responding: Reopen!" I disabled all the extensions, but nothing worked. I even tried some commands like deleting the user directory and disabling the extensions, but I still faced the same issue. I deleted the cache in AppData/Roaming/code, but still no luck. I also deleted the code file, and the same issue still exists! I even did this: -Open the Command Palette (Ctrl+Shift+P). Run the Preferences: Configure Runtime Arguments -Add "disable-hardware-acceleration": true. -Restart VS Code. I have looked it up all over the internet, and nothing worked! Please help me! these are the extntion:

Device Specifications:
Device name BadriyaHaddad
Processor   Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz   2.60 GHz
Installed RAM   12.0 GB (11.9 GB usable)
Device ID   7B1CE693-8DEC-426E-B6FB-54CC3FADE82A
Product ID  00331-10000-00001-AA635
System type 64-bit operating system, x64-based processor
Pen and touch   No pen or touch input is available for this display
Windows Specifications:
Edition Windows 10 Pro
Version 22H2
Installed on    11/27/2022
OS build    19045.2364
Experience  Windows Feature Experience Pack 120.2212.4190.0

enter image description here


问:
IndexedDB/React: Can't create a new store or perform any crud after DB creation
I'm building a React test app to understand better how the IndexedDB API works.

However, I'm struggling updating the data (creating store).

The db will only be updated if I refresh the page and the DB has been already created. Otherwise the onsuccess and the onupgradeneeded are not invoked at all.

iddb.ts

```<code>let request: IDBOpenDBRequest;
let db: IDBDatabase;
let version = 1;

// we will use this function to create a new store in our indexedDB
    export const initDB = () => {
  console.log('initDB');
  request = window.indexedDB.open(DBName.Main); // keep the existing version if it exists
  /*
  onupgradeneeded is called when the database is created or the version is changed
  the version should only change when we add, remove or modify a store
  */
  request.onupgradeneeded = (_event) => {
    db = request.result;
    if (!db.objectStoreNames.contains(StoreName.Users)) {
      console.log(`Creating ${StoreName.Users} store`);
      db.createObjectStore(StoreName.Users, { keyPath: 'id' });
    }
    if (!db.objectStoreNames.contains(StoreName.Posts)) {
      console.log(`Creating ${StoreName.Posts} store`);
      db.createObjectStore(StoreName.Posts, { keyPath: 'id' });
    }
  };

  // discard the old connection
  request.onsuccess = (_event) => {
    // this is not needed apparently (check it)
    console.log('request.onsuccess - initDB');
    version = request.result.version;
  };

};

export const deleteDB = () => {
  request = window.indexedDB.deleteDatabase(DBName.Main);
  request.onsuccess = (_event) => {
    console.log('Database deleted successfully');
  };
};

export const createStore = (storeName: StoreName) => {
  version += 1;
  request = window.indexedDB.open(DBName.Main, version); // open a new connection to the database

  request.onupgradeneeded = (_event) => {
    db = request.result;
    if (!db.objectStoreNames.contains(storeName)) {
      console.log(`Creating ${storeName} store`);
      db.createObjectStore(storeName, { keyPath: 'id' });
    }
  };

  request.onsuccess = (_event) => {
    console.log(`Store ${storeName} created successfully`);
    // close the database connection
  };

  request.onerror = (event) => {
    console.error('Error creating store', event);
  };
};

// we will use this function to add data to our indexedDB
export const addData = <T>(storeName: StoreName, data: T) => {
  // close prev connection
  // open a new connection to the database
  request = window.indexedDB.open(DBName.Main, version);

  // this works
  request.onsuccess = (_event) => {
    console.log('request.onsuccess');
    db = request.result;
    const tx = db.transaction(storeName, 'readwrite');
    const store = tx.objectStore(storeName);
    store.add(data);
  };
};
</code>```

types definitions

```<code>export enum DBName {
  Main = 'main',
}

export enum StoreName {
  Users = 'users',
  Posts = 'posts',
  News = 'news',
}
</code>```

These methods are later invoked in the client

```<code>// someComponent.tsx
import { StoreName, addData, initDB, createStore, deleteDB } from "../lib/iddb";

<button onClick={() => initDB()}>Init DB</button>
<button onClick={() => deleteDB()}>Delete DB</button>
<button onClick={() => createStore(StoreName.News)}>Create News DB</button>
</code>```

As per my understading:

To add a store -> increase the version and open a new DB, then update onupgradeneeded.

To perform CRUDs -> open the DB and perfrom a transaction onsuccess.

What I can see, given an existing DB and whenever there's a previous open connection, the IDBDatabase listeners won't be invoked. That's why I must restart the app to make them work.

Here's a sandbox with repro

EDIT
I made the addData work by simply not passing any version. However, trying to open a new connection increasing the version breaks the CRUD operations and no store is created unles I refresh (as mentioned earlier).

Body:
I'm building a React test app to understand better how the IndexedDB API works.

However, I'm struggling updating the data (creating store).

The db will only be updated if I refresh the page and the DB has been already created. Otherwise the onsuccess and the onupgradeneeded are not invoked at all.

iddb.ts

let request: IDBOpenDBRequest;
let db: IDBDatabase;
let version = 1;

// we will use this function to create a new store in our indexedDB
    export const initDB = () => {
  console.log('initDB');
  request = window.indexedDB.open(DBName.Main); // keep the existing version if it exists
  /*
  onupgradeneeded is called when the database is created or the version is changed
  the version should only change when we add, remove or modify a store
  */
  request.onupgradeneeded = (_event) => {
    db = request.result;
    if (!db.objectStoreNames.contains(StoreName.Users)) {
      console.log(`Creating ${StoreName.Users} store`);
      db.createObjectStore(StoreName.Users, { keyPath: 'id' });
    }
    if (!db.objectStoreNames.contains(StoreName.Posts)) {
      console.log(`Creating ${StoreName.Posts} store`);
      db.createObjectStore(StoreName.Posts, { keyPath: 'id' });
    }
  };

  // discard the old connection
  request.onsuccess = (_event) => {
    // this is not needed apparently (check it)
    console.log('request.onsuccess - initDB');
    version = request.result.version;
  };

};

export const deleteDB = () => {
  request = window.indexedDB.deleteDatabase(DBName.Main);
  request.onsuccess = (_event) => {
    console.log('Database deleted successfully');
  };
};

export const createStore = (storeName: StoreName) => {
  version += 1;
  request = window.indexedDB.open(DBName.Main, version); // open a new connection to the database

  request.onupgradeneeded = (_event) => {
    db = request.result;
    if (!db.objectStoreNames.contains(storeName)) {
      console.log(`Creating ${storeName} store`);
      db.createObjectStore(storeName, { keyPath: 'id' });
    }
  };

  request.onsuccess = (_event) => {
    console.log(`Store ${storeName} created successfully`);
    // close the database connection
  };

  request.onerror = (event) => {
    console.error('Error creating store', event);
  };
};

// we will use this function to add data to our indexedDB
export const addData = <T>(storeName: StoreName, data: T) => {
  // close prev connection
  // open a new connection to the database
  request = window.indexedDB.open(DBName.Main, version);

  // this works
  request.onsuccess = (_event) => {
    console.log('request.onsuccess');
    db = request.result;
    const tx = db.transaction(storeName, 'readwrite');
    const store = tx.objectStore(storeName);
    store.add(data);
  };
};

types definitions

export enum DBName {
  Main = 'main',
}

export enum StoreName {
  Users = 'users',
  Posts = 'posts',
  News = 'news',
}

These methods are later invoked in the client

// someComponent.tsx
import { StoreName, addData, initDB, createStore, deleteDB } from "../lib/iddb";

<button onClick={() => initDB()}>Init DB</button>
<button onClick={() => deleteDB()}>Delete DB</button>
<button onClick={() => createStore(StoreName.News)}>Create News DB</button>

As per my understading:

To add a store -> increase the version and open a new DB, then update onupgradeneeded.

To perform CRUDs -> open the DB and perfrom a transaction onsuccess.

What I can see, given an existing DB and whenever there's a previous open connection, the IDBDatabase listeners won't be invoked. That's why I must restart the app to make them work.

Here's a sandbox with repro

EDIT
I made the addData work by simply not passing any version. However, trying to open a new connection increasing the version breaks the CRUD operations and no store is created unles I refresh (as mentioned earlier).


问:
IsotopeJS with Vertical-only positioning updates possible?
Isotope JS will probably work nicely to filter events in a calendar-style display, but the trouble is getting it to keep items in the appropriate column.

The problem, when items for tues-thursday are filtered out:

```<code>|monday|tuesday|wednesday|thursday|friday|saturday|
---------------------------------------------------
| mon 1| fri 1 | sat 1 |

</code>```

My config:

```<code>var iso = new Isotope( '.schedule tbody', {
  itemSelector: 'td',
  layoutMode: 'masonry',
  resize: true
});
</code>```

And a Codepen example.

Thinking maybe fitColumns is the tool, but the .arrange method doesn't seem to work in that layout mode:

```<code>var iso = new Isotope(".schedule tbody", {
  layoutMode: 'fitColumns',
  itemSelector: '.grid-item'
});

...

iso.arrange({ filter: filterValue }); // nothing

</code>```

Another codepen.

Any suggestions?

Body:
Isotope JS will probably work nicely to filter events in a calendar-style display, but the trouble is getting it to keep items in the appropriate column.

The problem, when items for tues-thursday are filtered out:

|monday|tuesday|wednesday|thursday|friday|saturday|
---------------------------------------------------
| mon 1| fri 1 | sat 1 |

My config:

var iso = new Isotope( '.schedule tbody', {
  itemSelector: 'td',
  layoutMode: 'masonry',
  resize: true
});

And a Codepen example.

Thinking maybe fitColumns is the tool, but the .arrange method doesn't seem to work in that layout mode:

var iso = new Isotope(".schedule tbody", {
  layoutMode: 'fitColumns',
  itemSelector: '.grid-item'
});

...

iso.arrange({ filter: filterValue }); // nothing

Another codepen.

Any suggestions?


问:
Next js hot reload for local dependency
I'm using Next.js (javascript) for a new project and have included a fork of a dependency locally within the project by modifying the "package" field in the package.json file as follows:

```<code>"package": "file:./path/to/the/package"
</code>```

This works, but now I'm trying to enable hot reloading for this dependency by changing the "package" field to:

```<code>"package": "link:./path/to/the/package"
</code>```

However, this results in the following error:

```<code>Error: require() of ES Module
Instead change the require of index.js in .../.next/server/pages/page.js to a dynamic import() which is available in all CommonJS modules.
</code>```

Is there a way to fix this error and enable hot reloading for local dependencies in Next.js, or is there another approach I can take to achieve this?

Title: Next js hot reload for local dependency

Body:
I'm using Next.js (javascript) for a new project and have included a fork of a dependency locally within the project by modifying the "package" field in the package.json file as follows:

"package": "file:./path/to/the/package"

This works, but now I'm trying to enable hot reloading for this dependency by changing the "package" field to:

"package": "link:./path/to/the/package"

However, this results in the following error:

Error: require() of ES Module
Instead change the require of index.js in .../.next/server/pages/page.js to a dynamic import() which is available in all CommonJS modules.

Is there a way to fix this error and enable hot reloading for local dependencies in Next.js, or is there another approach I can take to achieve this?


问:
Pytube get_by_resolution method
I've tried to test pytube library and whenever I am trying to get a video by method

```<code>get_by_resolution()
</code>```

there always comes an error with a stream instance. Debugging stop at line 8 points to me that it didn't created a SteamQuery instance, instead I got NonType. So i made an alternative with other methods (getbylowest, get by highest) on same link. No problem with downloading the file.

Source code:

https://github.com/Cybernetic-Ransomware/proving_ground/blob/master/TiffinTech/yt_downloader.py

```<code>requirements:
Python 3.11.0
pytube==12.1.2
</code>```

I've checked all resolution parameters from method docstring (e.g. "720p") and others (e.g. "720p60"). There is no problem with link, because function "to-download-optional" works well. Could it be a problem with current library version?

Title: Pytube get_by_resolution method

Body:
I've tried to test pytube library and whenever I am trying to get a video by method

get_by_resolution()

there always comes an error with a stream instance. Debugging stop at line 8 points to me that it didn't created a SteamQuery instance, instead I got NonType. So i made an alternative with other methods (getbylowest, get by highest) on same link. No problem with downloading the file.

Source code:

https://github.com/Cybernetic-Ransomware/proving_ground/blob/master/TiffinTech/yt_downloader.py

requirements:
Python 3.11.0
pytube==12.1.2

I've checked all resolution parameters from method docstring (e.g. "720p") and others (e.g. "720p60"). There is no problem with link, because function "to-download-optional" works well. Could it be a problem with current library version?


问:
How to export dynamically generated SCSS variables for use in React
I have a _Variables.scss file where I am dynamically generating all my colors.  I would like to get access to just one of those colors in my React code, instead of hard coding the value in the code.

My variables file:

```<code>$colors-light: (
        'color-primary': #EFEFEF,
        'color-primary-variant': #D7D7D7,
        'color-primary-variant-light': #AAAAAA,
        'color-secondary': #23805C,
        'color-secondary-variant': #009687,
        'text': #4E4E4E,
        'text-alt': #FFFFFF
);

$colors-dark: (
        'color-primary': #2F302F,
        'color-primary-variant': #4E4E4E,
        'color-primary-variant-light': #6E6E6E,
        'color-secondary': #48BF91,
        'color-secondary-variant': #009687,
        'color-header': #484e3d,
        'text': #FFFFFF,
        'text-alt': #222222,
);

/* SASS Functions to create all the CSS variables from the SASS colors above */

@function hexToRGB($hex) {
  @return red($hex), green($hex), blue($hex);
}

@mixin generate_colors($colors) {
  // Colors
  @each $color, $value in $colors {
    @if str-slice(#{$value}, 1, 1) == '#' {
      --#{$color}: #{$value};
    }
    @else {
      --#{$color}: var(--#{$value});
    }
  }

  // RGB Colors
  @each $color, $value in $colors {
    @if str-slice(#{$value}, 1, 1) == '#' {

      /* stylelint-disable function-name-case  */

      --RGB-#{$color}: #{hexToRGB($value)};

      /* stylelint-enable function-name-case  */
    }

    @else {
      --RGB_#{$color}: var(--RGB_#{$value});
    }
  }
}

/* End of SASS functions */

/* Use the SASS functions and the SASS variables to actually create all the CSS color variables;
    e.g. --color-black: #222222 and --RGB-color-black: 34, 34, 34
 */

:root[data-theme='theme-light'] {
  @include generate_colors($colors-light);

  --color-true-black: #000000;
  --RGB-color-true-black: 0, 0, 0;
  --color-white: #FFFFFF;
  --RGB-color-white: 255, 255, 255;
  //--color-orchestrator: #d0ced0;
  --color-red: #BB0000;
  --RGB-color-red: 187, 0, 0;
  --color-red-lighter: #FF2E2E;
  --color-pink: #E4BFBF;
  --RGB-color-red-lighter: 255, 46, 46;
  --color-green: #348D00;
  --color-blue: #0000CC;
  --RGB-color-blue: 0, 0, 204;
  --RGB-color-green: 52, 141, 0;
  --label-alpha: 0.3;
}

:root[data-theme='theme-dark'] {
  @include generate_colors($colors-dark);

  // this does not work
  :export {
    color-primary: var(--color-primary);
  }

  --label-alpha: 0.9;
}
</code>```

In my App.scss file I import Variables and can use them like this:
.answer { color: var(--color-secondary);...

But I am trying to also export them(or just one for now) to use in my React.

Body:
I have a _Variables.scss file where I am dynamically generating all my colors.  I would like to get access to just one of those colors in my React code, instead of hard coding the value in the code.

My variables file:

$colors-light: (
        'color-primary': #EFEFEF,
        'color-primary-variant': #D7D7D7,
        'color-primary-variant-light': #AAAAAA,
        'color-secondary': #23805C,
        'color-secondary-variant': #009687,
        'text': #4E4E4E,
        'text-alt': #FFFFFF
);

$colors-dark: (
        'color-primary': #2F302F,
        'color-primary-variant': #4E4E4E,
        'color-primary-variant-light': #6E6E6E,
        'color-secondary': #48BF91,
        'color-secondary-variant': #009687,
        'color-header': #484e3d,
        'text': #FFFFFF,
        'text-alt': #222222,
);

/* SASS Functions to create all the CSS variables from the SASS colors above */

@function hexToRGB($hex) {
  @return red($hex), green($hex), blue($hex);
}

@mixin generate_colors($colors) {
  // Colors
  @each $color, $value in $colors {
    @if str-slice(#{$value}, 1, 1) == '#' {
      --#{$color}: #{$value};
    }
    @else {
      --#{$color}: var(--#{$value});
    }
  }

  // RGB Colors
  @each $color, $value in $colors {
    @if str-slice(#{$value}, 1, 1) == '#' {

      /* stylelint-disable function-name-case  */

      --RGB-#{$color}: #{hexToRGB($value)};

      /* stylelint-enable function-name-case  */
    }

    @else {
      --RGB_#{$color}: var(--RGB_#{$value});
    }
  }
}

/* End of SASS functions */

/* Use the SASS functions and the SASS variables to actually create all the CSS color variables;
    e.g. --color-black: #222222 and --RGB-color-black: 34, 34, 34
 */

:root[data-theme='theme-light'] {
  @include generate_colors($colors-light);

  --color-true-black: #000000;
  --RGB-color-true-black: 0, 0, 0;
  --color-white: #FFFFFF;
  --RGB-color-white: 255, 255, 255;
  //--color-orchestrator: #d0ced0;
  --color-red: #BB0000;
  --RGB-color-red: 187, 0, 0;
  --color-red-lighter: #FF2E2E;
  --color-pink: #E4BFBF;
  --RGB-color-red-lighter: 255, 46, 46;
  --color-green: #348D00;
  --color-blue: #0000CC;
  --RGB-color-blue: 0, 0, 204;
  --RGB-color-green: 52, 141, 0;
  --label-alpha: 0.3;
}

:root[data-theme='theme-dark'] {
  @include generate_colors($colors-dark);

  // this does not work
  :export {
    color-primary: var(--color-primary);
  }

  --label-alpha: 0.9;
}

In my App.scss file I import Variables and can use them like this:
.answer { color: var(--color-secondary);...

But I am trying to also export them(or just one for now) to use in my React.


问:
Cell editing breaks if editor is used quickly, bug in ExtJS / Chrome
Working with ExtJS (7) using modular windows (not React), I've recently encountered a bug where editing a cell too quickly before the rendering or backend functions finish SOMETIMES will create a scenario where the given editor for a column vanishes from the dom property of the editor. Stepping through the core ExtJS code was necessary to find this snippet which didn't provide any solutions:

https://bugs.chromium.org/p/chromium/issues/detail?id=432392

The problem being, once ExtJS loses this dom element, I haven't found a way to get it to refresh or replace it without wiping the entire grid and that's obviously unacceptable for usability reasons. The problem is in the CellEditing.js file of classic/grid/plugin/CellEditing.js area when it calls the line (roughly line #410 ish):

p = editor.el.dom.parentNode;

This throws:

```<code>Uncaught TypeError: Cannot read properties of null (reading 'parentNode')
    at ctor.activateCell (app.js?_dc=20230104061611:formatted:123916:30)
    at ctor.activateCell (app.js?_dc=20230104061611:formatted:112576:35)
    at ctor.setActionableMode (app.js?_dc=20230104061611:formatted:112771:27)
    at ctor.setActionableMode (app.js?_dc=20230104061611:formatted:108918:41)
    at ctor.onCellClick (app.js?_dc=20230104061611:formatted:123793:15)
    at ctor.fire (app.js?_dc=20230104061611:formatted:11634:32)
    at ctor.doFireEvent (app.js?_dc=20230104061611:formatted:12125:41)
    at ctor.doFireEvent (app.js?_dc=20230104061611:formatted:37543:45)
    at b.doFireEvent (app.js?_dc=20230104061611:formatted:33414:19)
    at ctor.fireEventArgs (app.js?_dc=20230104061611:formatted:12051:23)
</code>```

Since dom is somehow dropped (I have been unable to figure out why exactly dom is dropped other than the aforementioned bug link), this throws a null pointer and blows up the app. Anything after this point fails to work properly and the whole page must be refreshed.

This is not an easily reproducible bug, but the slower the computer and connection, the more likely it is to pop up. I reproduce it manually by setting a breakpoint right before the p = editor.el.dom.parentNode; line and then making whatever attempts in the code that I can think of.

The full context of this error occurs withing the activateCell method on in the CellEditing.js class. I've overriden the class in hopes of making a patch, and can make changes there if anyone has a solution!

I've tried wrapping this in a try/catch block, I've tried to add a block to re-render the editor if the dom is missing, I've tried to destroy the editor and rebuild it in the cached editor section, and all of them have failed with various levels of still being pretty broken such as:

```<code>Error.js?_dc=1672869371981:103 Uncaught Error: Missing DOM node in element garbage collection: celleditor-1529
    at new Ext.Error (Error.js?_dc=1672869371981:103:21)
    at Function.raise (Error.js?_dc=1672869371981:180:23)
    at Ext.raise (Error.js?_dc=1672869371981:269:21)
    at constructor.collect (GarbageCollector.js?_dc=1672869371980:67:21)
    at constructor.resume (GarbageCollector.js?_dc=1672869371980:160:16)
    at constructor.onTouchEnd (Gesture.js?_dc=1672869371981:588:54)
    at constructor.publishDelegatedDomEvent (Gesture.js?_dc=1672869371981:457:33)
    at constructor.doDelegatedEvent (Dom.js?_dc=1672869371981:506:16)
    at constructor.onDelegatedEvent (Dom.js?_dc=1672869371981:487:18)
</code>```

Body:
Working with ExtJS (7) using modular windows (not React), I've recently encountered a bug where editing a cell too quickly before the rendering or backend functions finish SOMETIMES will create a scenario where the given editor for a column vanishes from the dom property of the editor. Stepping through the core ExtJS code was necessary to find this snippet which didn't provide any solutions:

https://bugs.chromium.org/p/chromium/issues/detail?id=432392

The problem being, once ExtJS loses this dom element, I haven't found a way to get it to refresh or replace it without wiping the entire grid and that's obviously unacceptable for usability reasons. The problem is in the CellEditing.js file of classic/grid/plugin/CellEditing.js area when it calls the line (roughly line #410 ish):

p = editor.el.dom.parentNode;

This throws:

Uncaught TypeError: Cannot read properties of null (reading 'parentNode')
    at ctor.activateCell (app.js?_dc=20230104061611:formatted:123916:30)
    at ctor.activateCell (app.js?_dc=20230104061611:formatted:112576:35)
    at ctor.setActionableMode (app.js?_dc=20230104061611:formatted:112771:27)
    at ctor.setActionableMode (app.js?_dc=20230104061611:formatted:108918:41)
    at ctor.onCellClick (app.js?_dc=20230104061611:formatted:123793:15)
    at ctor.fire (app.js?_dc=20230104061611:formatted:11634:32)
    at ctor.doFireEvent (app.js?_dc=20230104061611:formatted:12125:41)
    at ctor.doFireEvent (app.js?_dc=20230104061611:formatted:37543:45)
    at b.doFireEvent (app.js?_dc=20230104061611:formatted:33414:19)
    at ctor.fireEventArgs (app.js?_dc=20230104061611:formatted:12051:23)

Since dom is somehow dropped (I have been unable to figure out why exactly dom is dropped other than the aforementioned bug link), this throws a null pointer and blows up the app. Anything after this point fails to work properly and the whole page must be refreshed.

This is not an easily reproducible bug, but the slower the computer and connection, the more likely it is to pop up. I reproduce it manually by setting a breakpoint right before the p = editor.el.dom.parentNode; line and then making whatever attempts in the code that I can think of.

The full context of this error occurs withing the activateCell method on in the CellEditing.js class. I've overriden the class in hopes of making a patch, and can make changes there if anyone has a solution!

I've tried wrapping this in a try/catch block, I've tried to add a block to re-render the editor if the dom is missing, I've tried to destroy the editor and rebuild it in the cached editor section, and all of them have failed with various levels of still being pretty broken such as:

Error.js?_dc=1672869371981:103 Uncaught Error: Missing DOM node in element garbage collection: celleditor-1529
    at new Ext.Error (Error.js?_dc=1672869371981:103:21)
    at Function.raise (Error.js?_dc=1672869371981:180:23)
    at Ext.raise (Error.js?_dc=1672869371981:269:21)
    at constructor.collect (GarbageCollector.js?_dc=1672869371980:67:21)
    at constructor.resume (GarbageCollector.js?_dc=1672869371980:160:16)
    at constructor.onTouchEnd (Gesture.js?_dc=1672869371981:588:54)
    at constructor.publishDelegatedDomEvent (Gesture.js?_dc=1672869371981:457:33)
    at constructor.doDelegatedEvent (Dom.js?_dc=1672869371981:506:16)
    at constructor.onDelegatedEvent (Dom.js?_dc=1672869371981:487:18)


问:
Error when trying to run python voice assistant on raspberry pi
Hello I am trying to run my python voice assistant on my raspberry pi and I am getting a weird error that I don't understand here is my code and the error.

code:

```<code>import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command

def run_alexa():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        talk('Current time is ' + time)
    elif 'who is' in command:
        person = command.replace('who the heck is', '')
        info = wikipedia.summary(person, 1)
        print(info)
        talk(info)
    elif 'date' in command:
        talk('sorry, I have a headache')
    elif 'are you single' in command:
        talk('I am in a relationship with wifi')
    elif 'joke' in command:
        talk(pyjokes.get_joke())
    else:
        talk('Please say the command again.')

while True:
    run_alexa()
</code>```

The Error :

```<code>Traceback (most recent call last):
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "/usr/lib/python3.9/weakref.py", line 134, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mohamed/Desktop/project/voiceassistant.py", line 9, in <module>
    engine = pyttsx3.init()
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/__init__.py", line 22, in init
    eng = Engine(driverName, debug)
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
  File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/drivers/espeak.py", line 9, in <module>
    from . import _espeak, toUtf8, fromUtf8
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/drivers/_espeak.py", line 18, in <module>
    dll = cdll.LoadLibrary('libespeak.so.1')
  File "/usr/lib/python3.9/ctypes/__init__.py", line 452, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib/python3.9/ctypes/__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: libespeak.so.1: cannot open shared object file: No such file or directory
</code>```

I installed pyaudio I didn't forget

I tried to search on Google for any help but Couldn't so I Uninstalled all the libraries and installed it again changed the location of the file I expect the code to run with no problem like on windows.

Body:
Hello I am trying to run my python voice assistant on my raspberry pi and I am getting a weird error that I don't understand here is my code and the error.

code:

import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command

def run_alexa():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        talk('Current time is ' + time)
    elif 'who is' in command:
        person = command.replace('who the heck is', '')
        info = wikipedia.summary(person, 1)
        print(info)
        talk(info)
    elif 'date' in command:
        talk('sorry, I have a headache')
    elif 'are you single' in command:
        talk('I am in a relationship with wifi')
    elif 'joke' in command:
        talk(pyjokes.get_joke())
    else:
        talk('Please say the command again.')

while True:
    run_alexa()

The Error :

Traceback (most recent call last):
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "/usr/lib/python3.9/weakref.py", line 134, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mohamed/Desktop/project/voiceassistant.py", line 9, in <module>
    engine = pyttsx3.init()
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/__init__.py", line 22, in init
    eng = Engine(driverName, debug)
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
  File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/drivers/espeak.py", line 9, in <module>
    from . import _espeak, toUtf8, fromUtf8
  File "/home/mohamed/.local/lib/python3.9/site-packages/pyttsx3/drivers/_espeak.py", line 18, in <module>
    dll = cdll.LoadLibrary('libespeak.so.1')
  File "/usr/lib/python3.9/ctypes/__init__.py", line 452, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib/python3.9/ctypes/__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: libespeak.so.1: cannot open shared object file: No such file or directory

I installed pyaudio I didn't forget

I tried to search on Google for any help but Couldn't so I Uninstalled all the libraries and installed it again changed the location of the file I expect the code to run with no problem like on windows.


问:
kotlin member reference - grabbing child object data
(using kotlin JS btw)
if i have a class that looks like this

```<code>data class AppUserDTO(
    override val email:String,
    override val client: DTOMin? = null
)
</code>```

and the DTOmin looks like

```<code>data class DTOMin(
override val id: Int,
override val display: String)
</code>```

is there any way to access client.display via a member reference?

i can access AppUserDTO::email
would love to basically do something like AppUserDTO::client::display

I am trying to build out a generic data table with sorting/filtering and it is working great for AppUserDTO::email but i need something similar to AppUserDTO::client::display

Body:
(using kotlin JS btw)
if i have a class that looks like this

data class AppUserDTO(
    override val email:String,
    override val client: DTOMin? = null
)

and the DTOmin looks like

data class DTOMin(
override val id: Int,
override val display: String)

is there any way to access client.display via a member reference?

i can access AppUserDTO::email
would love to basically do something like AppUserDTO::client::display

I am trying to build out a generic data table with sorting/filtering and it is working great for AppUserDTO::email but i need something similar to AppUserDTO::client::display


问:
SOAP WebServiceTemplate call with self-signed certificate - SunCertPathBuilderException
The API I'm connecting to in the test environment requires a specific certificate from the client. The certificate is self-signed, so I get this error:

```<code>Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

I received a certificate from the vendor in .pfx, and then I created a keystore with

```<code>keytool -importkeystore -srckeystore cert_dev.pfx -srcstoretype pkcs12 -destkeystore clientcert.jks -deststoretype JKS
</code>```

WebServiceTemplate configuration

    @Bean
    public WebServiceTemplate webServiceTemplate() throws Exception {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setMarshallerProperties(Map.of(JAXB_FORMATTED_OUTPUT, true));

        WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
        webServiceTemplate.setDefaultUri(properties.getBaseUrl());
        webServiceTemplate.setMessageSender(sender());
        webServiceTemplate.setMarshaller(marshaller);
        webServiceTemplate.setUnmarshaller(marshaller);

        return webServiceTemplate;
    }

    @Bean
    public HttpsUrlConnectionMessageSender sender() throws Exception {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(
                properties.getAuthentication().getKeyStore().getInputStream(),
                properties.getAuthentication().getKeyStorePassword().toCharArray()
        );

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(ks, properties.getAuthentication().getKeyStorePassword().toCharArray());

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(
                properties.getAuthentication().getTrustStore().getInputStream(),
                properties.getAuthentication().getTrustStorePassword().toCharArray()
        );

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(ts);

        HttpsUrlConnectionMessageSender messageSender = new HttpsUrlConnectionMessageSender();

        messageSender.setKeyManagers(keyManagerFactory.getKeyManagers());
        messageSender.setTrustManagers(trustManagerFactory.getTrustManagers());
        messageSender.setHostnameVerifier((hostname, sslSession) -> {
            return true;
        });

        return messageSender;
    }
```
<p>and I receive</p>
```Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
```

What is wrong with the configuration?
SoapUI handles the requests perfectly.

Body:
The API I'm connecting to in the test environment requires a specific certificate from the client. The certificate is self-signed, so I get this error:

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I received a certificate from the vendor in .pfx, and then I created a keystore with

keytool -importkeystore -srckeystore cert_dev.pfx -srcstoretype pkcs12 -destkeystore clientcert.jks -deststoretype JKS

WebServiceTemplate configuration

    @Bean
    public WebServiceTemplate webServiceTemplate() throws Exception {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setMarshallerProperties(Map.of(JAXB_FORMATTED_OUTPUT, true));

        WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
        webServiceTemplate.setDefaultUri(properties.getBaseUrl());
        webServiceTemplate.setMessageSender(sender());
        webServiceTemplate.setMarshaller(marshaller);
        webServiceTemplate.setUnmarshaller(marshaller);

        return webServiceTemplate;
    }

    @Bean
    public HttpsUrlConnectionMessageSender sender() throws Exception {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(
                properties.getAuthentication().getKeyStore().getInputStream(),
                properties.getAuthentication().getKeyStorePassword().toCharArray()
        );

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(ks, properties.getAuthentication().getKeyStorePassword().toCharArray());

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(
                properties.getAuthentication().getTrustStore().getInputStream(),
                properties.getAuthentication().getTrustStorePassword().toCharArray()
        );

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(ts);

        HttpsUrlConnectionMessageSender messageSender = new HttpsUrlConnectionMessageSender();

        messageSender.setKeyManagers(keyManagerFactory.getKeyManagers());
        messageSender.setTrustManagers(trustManagerFactory.getTrustManagers());
        messageSender.setHostnameVerifier((hostname, sslSession) -> {
            return true;
        });

        return messageSender;
    }

and I receive

Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

What is wrong with the configuration?
SoapUI handles the requests perfectly.


问:
Cannot read existing register value
I found this problem after try to login in game launcher which give me error with reading HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
After some time and trying solve problem with LAUNCHER i figure out it problem with my system.

When i try read in cmd

```<code>reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography /v MachineGuid
</code>```

ANY reg value by cmd it give me error about register value doesn't exist.

But if i try read register folders by

```<code>reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
</code>```

it read without problem and output folders

Also i checked perms - everyone can read it

UPD: Yeah program and cmd was run from administrate. Also i fixed commands (i type both by mistake)

UPD2: Seems like reading registry values work only with powershell for some reason. By cmd it only read folders of registry but not values

Title: Cannot read existing register value

Body:
I found this problem after try to login in game launcher which give me error with reading HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
After some time and trying solve problem with LAUNCHER i figure out it problem with my system.

When i try read in cmd

reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography /v MachineGuid

ANY reg value by cmd it give me error about register value doesn't exist.

But if i try read register folders by

reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography

it read without problem and output folders

Also i checked perms - everyone can read it

UPD: Yeah program and cmd was run from administrate. Also i fixed commands (i type both by mistake)

UPD2: Seems like reading registry values work only with powershell for some reason. By cmd it only read folders of registry but not values


问:
I want to build a voice recognition calculator
i want to built voice recognition calculatos. my recognition event is working but i have a problem with evaluation. when i am trying to evaluate multiplication i am saying ,,five times three" and trancription gives me (5 X 3), then there is an error. eval() can not see X as multiplication.

also i cant use percentage or brackets with voice recognition. can someone help me with this?
`

```<code>    function speechRecognition() {
      const recognition = new webkitSpeechRecognition();
      recognition.lang = "en-US";

      recognition.onstart = function () {
        microphone.classList.add(`listening`);
      };
      recognition.onspeechend = function () {
        microphone.classList.remove(`listening`);
        recognition.stop();
      };
      recognition.onresult = function (event) {
        console.log(event);
        const transcript = event.results[0][0].transcript;

       let result = eval(transcript);
        displayOutput.innerHTML = cleanOutput(result);
      };

      recognition.start();
    }
</code>```

Body:
i want to built voice recognition calculatos. my recognition event is working but i have a problem with evaluation. when i am trying to evaluate multiplication i am saying ,,five times three" and trancription gives me (5 X 3), then there is an error. eval() can not see X as multiplication.

also i cant use percentage or brackets with voice recognition. can someone help me with this?
`

    function speechRecognition() {
      const recognition = new webkitSpeechRecognition();
      recognition.lang = "en-US";

      recognition.onstart = function () {
        microphone.classList.add(`listening`);
      };
      recognition.onspeechend = function () {
        microphone.classList.remove(`listening`);
        recognition.stop();
      };
      recognition.onresult = function (event) {
        console.log(event);
        const transcript = event.results[0][0].transcript;

       let result = eval(transcript);
        displayOutput.innerHTML = cleanOutput(result);
      };

      recognition.start();
    }


问:
How can I post an audio file (either blob file or its generated url) from Angular frontend to flask backend?
I'm trying to send a recorded audio file (blob file) to an API. I sent it as a single blob file or as a file with FormData. But neither of the approaches worked.

I receive the audio file using flask restful API (reqparse.RequestParser()) which is different from request.files['file'].

I tried adding reqparse argument as types werkzeug.datastructures.FileStorage or bytesarray. They didn't work as well.

I get 400 errors (BAD REQUEST) and the data received in a flask is empty.

component.ts

```<code>var data = new FormData();
data.append('file', blob)

this.appService.send(data).subscribe({
  next: data => {
    console.log(data);
  },
  error: err => {
    console.log(err)
  }
});
</code>```

app.service.ts

```<code>send(data:FormData): Observable<any> {
  const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data'})
  };
  return this.http.post('/audioFile', data, httpOptions);
}
</code>```

app.py

```<code>app = Flask(__name__)
api = Api(app)

class Receive(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument(name='file', type=werkzeug.datastructures.FileStorage, location='files', required=True, help='audio bytes')

    def post(self):
        data = Receive.parser.parse_args()
        print(data["file"].audioFile, file=sys.stderr)
        f = open('file.wav', 'wb')
        f.write(data["file"])
        f.close()

api.add_resource(Receive, '/audioFile')
</code>```

Body:
I'm trying to send a recorded audio file (blob file) to an API. I sent it as a single blob file or as a file with FormData. But neither of the approaches worked.

I receive the audio file using flask restful API (reqparse.RequestParser()) which is different from request.files['file'].

I tried adding reqparse argument as types werkzeug.datastructures.FileStorage or bytesarray. They didn't work as well.

I get 400 errors (BAD REQUEST) and the data received in a flask is empty.

component.ts

var data = new FormData();
data.append('file', blob)

this.appService.send(data).subscribe({
  next: data => {
    console.log(data);
  },
  error: err => {
    console.log(err)
  }
});

app.service.ts

send(data:FormData): Observable<any> {
  const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data'})
  };
  return this.http.post('/audioFile', data, httpOptions);
}

app.py

app = Flask(__name__)
api = Api(app)

class Receive(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument(name='file', type=werkzeug.datastructures.FileStorage, location='files', required=True, help='audio bytes')

    def post(self):
        data = Receive.parser.parse_args()
        print(data["file"].audioFile, file=sys.stderr)
        f = open('file.wav', 'wb')
        f.write(data["file"])
        f.close()

api.add_resource(Receive, '/audioFile')


问:
Getting an RPC Request Error with Brownie Using Ganache
Getting an RPC Request Error: Web3 is not connected. when I run brownie test after compiling the token mix. It appears to be related to ganache.py because of the following error message: ../../../.local/pipx/venvs/eth-brownie/lib/python3.9/site-packages/brownie/network/rpc/ganache.py:129: RPCRequestError. Furthermore, when I run brownie console it does not show the launching of ganache-cli.

I am following this tutorial for eth-brownie on MacOS Monterey M1 (https://betterprogramming.pub/getting-started-with-brownie-part-2-615a1eec167f) and after installing all the dependencies to the correct versions and pipx installing eth-brownie, I ran the following commands:

```<code>$ mkdir brownie
$ cd brownie
$ brownie init
$ brownie bake token
$ cd token
$ brownie compile
$ brownie test
</code>```

I expected for brownie test to pass and to see launching ganache-cli... after initiating  brownie console. Please note that I still get errors even when I change my Ganache port to 8545 through the Ganache GUI.

Body:
Getting an RPC Request Error: Web3 is not connected. when I run brownie test after compiling the token mix. It appears to be related to ganache.py because of the following error message: ../../../.local/pipx/venvs/eth-brownie/lib/python3.9/site-packages/brownie/network/rpc/ganache.py:129: RPCRequestError. Furthermore, when I run brownie console it does not show the launching of ganache-cli.

I am following this tutorial for eth-brownie on MacOS Monterey M1 (https://betterprogramming.pub/getting-started-with-brownie-part-2-615a1eec167f) and after installing all the dependencies to the correct versions and pipx installing eth-brownie, I ran the following commands:

$ mkdir brownie
$ cd brownie
$ brownie init
$ brownie bake token
$ cd token
$ brownie compile
$ brownie test

I expected for brownie test to pass and to see launching ganache-cli... after initiating  brownie console. Please note that I still get errors even when I change my Ganache port to 8545 through the Ganache GUI.


问:
How to limit ZSH autocomplete to the current directory
I'm having a base zsh + oh-my-zsh install on a WSL2 Ubuntu. Zsh's autocomplete system (maybe coupled with oh-my-zsh's setup) by default completes anything from a path lookup, so when I'm in a folder, and I type a few letters, it annoyingly gives me a list of all unrelated .dll files, instead of completing to a subfolder from the current directory.

I've read different answers from stackoverflow, none of it worked. I asked ChatGPT ;), which gave me this:

zstyle ':completion:*' file-patterns './**'

which didn't work either.


问:
web scraping of concurrent review pages
How can I scrape concurrent web pages  of customer reviews in Python for which follows A) a regular order B)irregular order, let me explain:
In this link there is a page number=2 means second page of the review

https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=2',

And when click next button link becomes '.....pageNumber=3..' and so on... I sometimes find the last page , sometimes not...

But in any case, I want to write a line of code that covers all the pages instead of  generating all pages and pasting them to Jupiter notebook

My code was like this, number of URL s are reduced:

```<code>`import requests
from bs4 import BeautifulSoup
import pandas as pd
from urllib.parse import urlencode
import csv

# Define a list of URL's that will be scraped.
list_of_urls = ['https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=1',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=2',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=3',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=4',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=5',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=6',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=7',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=8',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=9'
]

# Retrieve each of the url's HTML data and convert the data into a beautiful soup object.
# Find, extract and store reviewer names and review text into a list.

names = []
reviews = []
data_string = ""

for url in list_of_urls:
    params = {'api_key': "f00ffd18cb3cb9e64c315b9aa54e29f3", 'url': url}
    response = requests.get('http://api.scraperapi.com/',   params=urlencode(params))
    soup = BeautifulSoup(response.text, 'html.parser')

    for item in soup.find_all("span", class_="a-profile-name"):
      data_string = data_string + item.get_text()
      names.append(data_string)
      data_string = ""

    for item in soup.find_all("span", {"data-hook": "review-body"}):
      data_string = data_string + item.get_text()
      reviews.append(data_string)
      data_string = ""

# Create the dictionary.
reviews_dict = {'Reviewer Name': names, 'Reviews': reviews}
# Print the lengths of each list.
print(len(names), len(reviews))

# Create a new dataframe.
df = pd.DataFrame.from_dict(reviews_dict, orient='index')
df.head()

# Delete all the columns that have missing values.
df.dropna(axis=1, inplace=True)
df.head()

# Transpose the dataframe.
prod_reviews = df.T
print(prod_reviews.head(10))

# Remove special characters from review text.
prod_reviews['Reviews'] = prod_reviews['Reviews'].astype(str)

prod_reviews.head(5)

# Convert dataframe to CSV file.
prod_reviews.to_csv('Review.csv', index=False, header=True)`
</code>```

So, a list of URLs that will be scraped goes to hundreds...

I want to shorten it, i dont want to paste all URLs, how can i do it????

Title: web scraping of concurrent review pages

Body:
How can I scrape concurrent web pages  of customer reviews in Python for which follows A) a regular order B)irregular order, let me explain:
In this link there is a page number=2 means second page of the review

https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=2',

And when click next button link becomes '.....pageNumber=3..' and so on... I sometimes find the last page , sometimes not...

But in any case, I want to write a line of code that covers all the pages instead of  generating all pages and pasting them to Jupiter notebook

My code was like this, number of URL s are reduced:

`import requests
from bs4 import BeautifulSoup
import pandas as pd
from urllib.parse import urlencode
import csv

# Define a list of URL's that will be scraped.
list_of_urls = ['https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=1',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=2',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=3',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=4',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=5',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=6',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=7',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=8',
'https://www.amazon.com/NOUHAUS-Ergo-Flip-Computer-Chair/product-reviews/B07SG3FK4W/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=9'
]

# Retrieve each of the url's HTML data and convert the data into a beautiful soup object.
# Find, extract and store reviewer names and review text into a list.

names = []
reviews = []
data_string = ""

for url in list_of_urls:
    params = {'api_key': "f00ffd18cb3cb9e64c315b9aa54e29f3", 'url': url}
    response = requests.get('http://api.scraperapi.com/',   params=urlencode(params))
    soup = BeautifulSoup(response.text, 'html.parser')

    for item in soup.find_all("span", class_="a-profile-name"):
      data_string = data_string + item.get_text()
      names.append(data_string)
      data_string = ""

    for item in soup.find_all("span", {"data-hook": "review-body"}):
      data_string = data_string + item.get_text()
      reviews.append(data_string)
      data_string = ""

# Create the dictionary.
reviews_dict = {'Reviewer Name': names, 'Reviews': reviews}
# Print the lengths of each list.
print(len(names), len(reviews))

# Create a new dataframe.
df = pd.DataFrame.from_dict(reviews_dict, orient='index')
df.head()

# Delete all the columns that have missing values.
df.dropna(axis=1, inplace=True)
df.head()

# Transpose the dataframe.
prod_reviews = df.T
print(prod_reviews.head(10))

# Remove special characters from review text.
prod_reviews['Reviews'] = prod_reviews['Reviews'].astype(str)

prod_reviews.head(5)

# Convert dataframe to CSV file.
prod_reviews.to_csv('Review.csv', index=False, header=True)`

So, a list of URLs that will be scraped goes to hundreds...

I want to shorten it, i dont want to paste all URLs, how can i do it????


问:
Is there a way to highlight a specific line within a codeblock using GitHub's markdown?
I have a code block where I'd like to highlight a line for instructional purposes while preserving the other lines for context. I suspect there is no real way of doing this but wanted to see if perhaps somebody had a workaround.</p>
```<code><div>
  <p>Highlight this line</p>
</div>
</code>```

Body:
I have a code block where I'd like to highlight a line for instructional purposes while preserving the other lines for context. I suspect there is no real way of doing this but wanted to see if perhaps somebody had a workaround.

Highlight this line