问:
I can't trasition between the STATES in my app . what is the wrong in my code?
```<code>/*
 * Copyright (C) 2021 The Android Open Source Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.lemonade

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {

    /**
     * DO NOT ALTER ANY VARIABLE OR VALUE NAMES OR THEIR INITIAL VALUES.
     *
     * Anything labeled var instead of val is expected to be changed in the functions but DO NOT
     * alter their initial values declared here, this could cause the app to not function properly.
     */
    private val LEMONADE_STATE = "LEMONADE_STATE"
    private val LEMON_SIZE = "LEMON_SIZE"
    private val SQUEEZE_COUNT = "SQUEEZE_COUNT"
    // SELECT represents the "pick lemon" state
    private val SELECT = "select"
    // SQUEEZE represents the "squeeze lemon" state
    private val SQUEEZE = "squeeze"
    // DRINK represents the "drink lemonade" state
    private val DRINK = "drink"
    // RESTART represents the state where the lemonade has been drunk and the glass is empty
    private val RESTART = "restart"
    // Default the state to select
    private var lemonadeState = "select"
    // Default lemonSize to -1
    private var lemonSize = -1
    // Default the squeezeCount to -1
    private var squeezeCount = -1

    private var lemonTree = LemonTree()
    private var lemonImage: ImageView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // === DO NOT ALTER THE CODE IN THE FOLLOWING IF STATEMENT ===
        if (savedInstanceState != null) {
            lemonadeState = savedInstanceState.getString(LEMONADE_STATE, "select")
            lemonSize = savedInstanceState.getInt(LEMON_SIZE, -1)
            squeezeCount = savedInstanceState.getInt(SQUEEZE_COUNT, -1)
        }
        // === END IF STATEMENT ===

        lemonImage = findViewById(R.id.image_lemon_state)
        setViewElements()
        lemonImage!!.setOnClickListener {
            // TODO: call the method that handles the state when the image is clicked
            clickLemonImage()
            Toast.makeText(this,"Lemon clicked",Toast.LENGTH_SHORT).show()
        }
        lemonImage!!.setOnLongClickListener {
            // TODO: replace 'false' with a call to the function that shows the squeeze count
            showSnackbar()
            //false
        }
    }

    /**
     * === DO NOT ALTER THIS METHOD ===
     *
     * This method saves the state of the app if it is put in the background.
     */
    override fun onSaveInstanceState(outState: Bundle) {
        outState.putString(LEMONADE_STATE, lemonadeState)
        outState.putInt(LEMON_SIZE, lemonSize)
        outState.putInt(SQUEEZE_COUNT, squeezeCount)
        super.onSaveInstanceState(outState)
    }

    /**
     * Clicking will elicit a different response depending on the state.
     * This method determines the state and proceeds with the correct action.
     */
    private fun clickLemonImage() {
        // TODO: use a conditional statement like 'if' or 'when' to track the lemonadeState
        //  when the image is clicked we may need to change state to the next step in the
     //  lemonade making progression (or at least make some changes to the current state in the
        //  case of squeezing the lemon). That should be done in this conditional statement
        when(lemonadeState){
        // TODO: When the image is clicked in the SELECT state, the state should become SQUEEZE
   //  - The lemonSize variable needs to be set using the 'pick()' method in the LemonTree class
            //  - The squeezeCount should be 0 since we haven't squeezed any lemons just yet.

            SELECT -> {
                SQUEEZE
                var pick = LemonTree()
                lemonSize = pick.pick()
                squeezeCount = 0

            }

            // TODO: When the image is clicked in the SQUEEZE state the squeezeCount needs to be
            //  INCREASED by 1 and lemonSize needs to be DECREASED by 1.
      //  - If the lemonSize has reached 0, it has been juiced and the state should become DRINK
            //  - Additionally, lemonSize is no longer relevant and should be set to -1

            SQUEEZE -> {
                lemonSize = 5
//                squeezeCount = 0
                squeezeCount++
                lemonSize--
                when(lemonSize){
                    0 -> DRINK
                }
            }

          // TODO: When the image is clicked in the DRINK state the state should become RESTART

            DRINK -> {
                RESTART
                lemonSize = -1
            }

         // TODO: When the image is clicked in the RESTART state the state should become SELECT

            RESTART -> SELECT
        }

    // TODO: lastly, before the function terminates we need to set the view elements so that the
        //  UI can reflect the correct state

        setViewElements()
    }

    /**
     * Set up the view elements according to the state.
     */
    private fun setViewElements() {
        val textAction: TextView = findViewById(R.id.text_action1)
        // TODO: set up a conditional that tracks the lemonadeState

        // TODO: for each state, the textAction TextView should be set to the corresponding string from
        //  the string resources file. The strings are named to match the state

        // TODO: Additionally, for each state, the lemonImage should be set to the corresponding
        //  drawable from the drawable resources. The drawables have the same names as the strings
        //  but remember that they are drawables, not strings.
        when(lemonadeState){
            SELECT -> {
                textAction.setText(R.string.lemon_select)
                lemonImage?.setImageResource(R.drawable.lemon_tree)
            }
            SQUEEZE -> {
                textAction.setText(R.string.lemon_squeeze)
                lemonImage?.setImageResource(R.drawable.lemon_squeeze)
            }
            DRINK -> {
                textAction.setText(R.string.lemon_drink)
                lemonImage?.setImageResource(R.drawable.lemon_drink)
            }
            RESTART -> {
                textAction.setText(R.string.lemon_empty_glass)
                lemonImage?.setImageResource(R.drawable.lemon_restart)
            }
        }
    }

    /**
     * === DO NOT ALTER THIS METHOD ===
     *
     * Long clicking the lemon image will show how many times the lemon has been squeezed.
     */
    private fun showSnackbar(): Boolean {
        if (lemonadeState != SQUEEZE) {
            return false
        }
        val squeezeText = getString(R.string.squeeze_count, squeezeCount)
        Snackbar.make(
            findViewById(R.id.constraint_Layout),
            squeezeText,
            Snackbar.LENGTH_SHORT
        ).show()
        return true
    }
}

/**
 * A Lemon tree class with a method to "pick" a lemon. The "size" of the lemon is randomized
 * and determines how many times a lemon needs to be squeezed before you get lemonade.
 */
class LemonTree {
    fun pick(): Int {
        return (2..4).random()
    }
}

</code>```

i have a test for my code. the test is default from the starter, when i run the test i get this:

Caused by: junit.framework.AssertionFailedError: 'an instance of android.widget.TextView and view.getText() equals string from resource id: <2131689520>' doesn't match the selected view.

Expected: an instance of android.widget.TextView and view.getText() equals string from resource id: <2131689520> [lemon_drink] value: Click to drink your lemonade!

Got: view.getText() was "Click to select a lemon!"

View Details: MaterialTextView{id=2131231150, res-name=text_action1, visibility=VISIBLE, width=485, height=63, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@8e0204b, tag=null, root-is-layout-requested=false, has-input-connection=false, x=298.0, y=384.0, text=Click to select a lemon!, input-type=0, ime-target=false, has-links=false}

and another erroe when i run the test :

androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: view.getId() is <2131231102/com.example.lemonade:id/snackbar_text>

View Hierarchy:
+>DecorView{id=-1, visibility=VISIBLE, width=1080, height=1920, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params={(0,0)(fillxfill) ty=BASE_APPLICATION wanim=0x10302f8
fl=LAYOUT_IN_SCREEN LAYOUT_INSET_DECOR SPLIT_TOUCH HARDWARE_ACCELERATED DRAWS_SYSTEM_BAR_BACKGROUNDS
pfl=FORCE_DRAW_STATUS_BAR_BACKGROUND}, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=3}
|
+->LinearLayout{id=-1, visibility=VISIBLE, width=1080, height=1794, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@b25468d, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+-->ViewStub{id=16908682, res-name=action_mode_bar_stub, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@86c3042, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0}
|
+-->FrameLayout{id=-1, visibility=VISIBLE, width=1080, height=1731, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@b079590, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=63.0, child-count=1}
|
+--->ActionBarOverlayLayout{id=2131230861, res-name=decor_content_parent, visibility=VISIBLE, width=1080, height=1731, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@c86a6af, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+---->ContentFrameLayout{id=16908290, res-name=content, visibility=VISIBLE, width=1080, height=1584, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.ActionBarOverlayLayout$LayoutParams@19ba45, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=147.0, child-count=1}
|
+----->ConstraintLayout{id=2131230844, res-name=constraint_Layout, visibility=VISIBLE, width=1080, height=1584, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@1b086a8, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+------>MaterialTextView{id=2131231150, res-name=text_action1, visibility=VISIBLE, width=485, height=63, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@f20b5c1, tag=null, root-is-layout-requested=false, has-input-connection=false, x=298.0, y=384.0, text=Click to select a lemon!, input-type=0, ime-target=false, has-links=false}
|
+------>AppCompatImageView{id=2131230939, res-name=image_lemon_state, visibility=VISIBLE, width=420, height=525, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@c946166, tag=null, root-is-layout-requested=false, has-input-connection=false, x=330.0, y=530.0}
|
+---->ActionBarContainer{id=2131230773, res-name=action_bar_container, visibility=VISIBLE, width=1080, height=147, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.ActionBarOverlayLayout$LayoutParams@241ecfd, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+----->Toolbar{id=2131230771, res-name=action_bar, visibility=VISIBLE, width=1080, height=147, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@13382c0, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+------>AppCompatTextView{id=-1, visibility=VISIBLE, width=257, height=71, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.Toolbar$LayoutParams@5455bf9, tag=null, root-is-layout-requested=false, has-input-connection=false, x=42.0, y=38.0, text=Lemonade, input-type=0, ime-target=false, has-links=false}
|
+------>ActionMenuView{id=-1, visibility=VISIBLE, width=0, height=147, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.Toolbar$LayoutParams@c24373e, tag=null, root-is-layout-requested=false, has-input-connection=false, x=1080.0, y=0.0, child-count=0}
|
+----->ActionBarContextView{id=2131230779, res-name=action_context_bar, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@c34999f, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=0}
|
+->View{id=16908336, res-name=navigationBarBackground, visibility=VISIBLE, width=1080, height=126, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@92e0aec, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=1794.0}
|
+->View{id=16908335, res-name=statusBarBackground, visibility=VISIBLE, width=1080, height=63, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@e76beb5, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0}
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1538)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:12)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:7)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:8)
at androidx.test.espresso.ViewInteraction.check(ViewInteraction.java:12)
at com.example.lemonade.LemonadeTests.test_squeeze_count_snackbar_is_displayed(LemonadeTests.kt:84)

Body:
/*
 * Copyright (C) 2021 The Android Open Source Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.lemonade

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {

    /**
     * DO NOT ALTER ANY VARIABLE OR VALUE NAMES OR THEIR INITIAL VALUES.
     *
     * Anything labeled var instead of val is expected to be changed in the functions but DO NOT
     * alter their initial values declared here, this could cause the app to not function properly.
     */
    private val LEMONADE_STATE = "LEMONADE_STATE"
    private val LEMON_SIZE = "LEMON_SIZE"
    private val SQUEEZE_COUNT = "SQUEEZE_COUNT"
    // SELECT represents the "pick lemon" state
    private val SELECT = "select"
    // SQUEEZE represents the "squeeze lemon" state
    private val SQUEEZE = "squeeze"
    // DRINK represents the "drink lemonade" state
    private val DRINK = "drink"
    // RESTART represents the state where the lemonade has been drunk and the glass is empty
    private val RESTART = "restart"
    // Default the state to select
    private var lemonadeState = "select"
    // Default lemonSize to -1
    private var lemonSize = -1
    // Default the squeezeCount to -1
    private var squeezeCount = -1

    private var lemonTree = LemonTree()
    private var lemonImage: ImageView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // === DO NOT ALTER THE CODE IN THE FOLLOWING IF STATEMENT ===
        if (savedInstanceState != null) {
            lemonadeState = savedInstanceState.getString(LEMONADE_STATE, "select")
            lemonSize = savedInstanceState.getInt(LEMON_SIZE, -1)
            squeezeCount = savedInstanceState.getInt(SQUEEZE_COUNT, -1)
        }
        // === END IF STATEMENT ===

        lemonImage = findViewById(R.id.image_lemon_state)
        setViewElements()
        lemonImage!!.setOnClickListener {
            // TODO: call the method that handles the state when the image is clicked
            clickLemonImage()
            Toast.makeText(this,"Lemon clicked",Toast.LENGTH_SHORT).show()
        }
        lemonImage!!.setOnLongClickListener {
            // TODO: replace 'false' with a call to the function that shows the squeeze count
            showSnackbar()
            //false
        }
    }

    /**
     * === DO NOT ALTER THIS METHOD ===
     *
     * This method saves the state of the app if it is put in the background.
     */
    override fun onSaveInstanceState(outState: Bundle) {
        outState.putString(LEMONADE_STATE, lemonadeState)
        outState.putInt(LEMON_SIZE, lemonSize)
        outState.putInt(SQUEEZE_COUNT, squeezeCount)
        super.onSaveInstanceState(outState)
    }

    /**
     * Clicking will elicit a different response depending on the state.
     * This method determines the state and proceeds with the correct action.
     */
    private fun clickLemonImage() {
        // TODO: use a conditional statement like 'if' or 'when' to track the lemonadeState
        //  when the image is clicked we may need to change state to the next step in the
     //  lemonade making progression (or at least make some changes to the current state in the
        //  case of squeezing the lemon). That should be done in this conditional statement
        when(lemonadeState){
        // TODO: When the image is clicked in the SELECT state, the state should become SQUEEZE
   //  - The lemonSize variable needs to be set using the 'pick()' method in the LemonTree class
            //  - The squeezeCount should be 0 since we haven't squeezed any lemons just yet.

            SELECT -> {
                SQUEEZE
                var pick = LemonTree()
                lemonSize = pick.pick()
                squeezeCount = 0

            }

            // TODO: When the image is clicked in the SQUEEZE state the squeezeCount needs to be
            //  INCREASED by 1 and lemonSize needs to be DECREASED by 1.
      //  - If the lemonSize has reached 0, it has been juiced and the state should become DRINK
            //  - Additionally, lemonSize is no longer relevant and should be set to -1

            SQUEEZE -> {
                lemonSize = 5
//                squeezeCount = 0
                squeezeCount++
                lemonSize--
                when(lemonSize){
                    0 -> DRINK
                }
            }

          // TODO: When the image is clicked in the DRINK state the state should become RESTART

            DRINK -> {
                RESTART
                lemonSize = -1
            }

         // TODO: When the image is clicked in the RESTART state the state should become SELECT

            RESTART -> SELECT
        }

    // TODO: lastly, before the function terminates we need to set the view elements so that the
        //  UI can reflect the correct state

        setViewElements()
    }

    /**
     * Set up the view elements according to the state.
     */
    private fun setViewElements() {
        val textAction: TextView = findViewById(R.id.text_action1)
        // TODO: set up a conditional that tracks the lemonadeState

        // TODO: for each state, the textAction TextView should be set to the corresponding string from
        //  the string resources file. The strings are named to match the state

        // TODO: Additionally, for each state, the lemonImage should be set to the corresponding
        //  drawable from the drawable resources. The drawables have the same names as the strings
        //  but remember that they are drawables, not strings.
        when(lemonadeState){
            SELECT -> {
                textAction.setText(R.string.lemon_select)
                lemonImage?.setImageResource(R.drawable.lemon_tree)
            }
            SQUEEZE -> {
                textAction.setText(R.string.lemon_squeeze)
                lemonImage?.setImageResource(R.drawable.lemon_squeeze)
            }
            DRINK -> {
                textAction.setText(R.string.lemon_drink)
                lemonImage?.setImageResource(R.drawable.lemon_drink)
            }
            RESTART -> {
                textAction.setText(R.string.lemon_empty_glass)
                lemonImage?.setImageResource(R.drawable.lemon_restart)
            }
        }
    }

    /**
     * === DO NOT ALTER THIS METHOD ===
     *
     * Long clicking the lemon image will show how many times the lemon has been squeezed.
     */
    private fun showSnackbar(): Boolean {
        if (lemonadeState != SQUEEZE) {
            return false
        }
        val squeezeText = getString(R.string.squeeze_count, squeezeCount)
        Snackbar.make(
            findViewById(R.id.constraint_Layout),
            squeezeText,
            Snackbar.LENGTH_SHORT
        ).show()
        return true
    }
}

/**
 * A Lemon tree class with a method to "pick" a lemon. The "size" of the lemon is randomized
 * and determines how many times a lemon needs to be squeezed before you get lemonade.
 */
class LemonTree {
    fun pick(): Int {
        return (2..4).random()
    }
}

i have a test for my code. the test is default from the starter, when i run the test i get this:

Caused by: junit.framework.AssertionFailedError: 'an instance of android.widget.TextView and view.getText() equals string from resource id: <2131689520>' doesn't match the selected view.

Expected: an instance of android.widget.TextView and view.getText() equals string from resource id: <2131689520> [lemon_drink] value: Click to drink your lemonade!

Got: view.getText() was "Click to select a lemon!"

View Details: MaterialTextView{id=2131231150, res-name=text_action1, visibility=VISIBLE, width=485, height=63, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@8e0204b, tag=null, root-is-layout-requested=false, has-input-connection=false, x=298.0, y=384.0, text=Click to select a lemon!, input-type=0, ime-target=false, has-links=false}

and another erroe when i run the test :

androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: view.getId() is <2131231102/com.example.lemonade:id/snackbar_text>

View Hierarchy:
+>DecorView{id=-1, visibility=VISIBLE, width=1080, height=1920, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params={(0,0)(fillxfill) ty=BASE_APPLICATION wanim=0x10302f8
fl=LAYOUT_IN_SCREEN LAYOUT_INSET_DECOR SPLIT_TOUCH HARDWARE_ACCELERATED DRAWS_SYSTEM_BAR_BACKGROUNDS
pfl=FORCE_DRAW_STATUS_BAR_BACKGROUND}, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=3}
|
+->LinearLayout{id=-1, visibility=VISIBLE, width=1080, height=1794, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@b25468d, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+-->ViewStub{id=16908682, res-name=action_mode_bar_stub, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@86c3042, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0}
|
+-->FrameLayout{id=-1, visibility=VISIBLE, width=1080, height=1731, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@b079590, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=63.0, child-count=1}
|
+--->ActionBarOverlayLayout{id=2131230861, res-name=decor_content_parent, visibility=VISIBLE, width=1080, height=1731, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@c86a6af, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+---->ContentFrameLayout{id=16908290, res-name=content, visibility=VISIBLE, width=1080, height=1584, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.ActionBarOverlayLayout$LayoutParams@19ba45, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=147.0, child-count=1}
|
+----->ConstraintLayout{id=2131230844, res-name=constraint_Layout, visibility=VISIBLE, width=1080, height=1584, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@1b086a8, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+------>MaterialTextView{id=2131231150, res-name=text_action1, visibility=VISIBLE, width=485, height=63, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@f20b5c1, tag=null, root-is-layout-requested=false, has-input-connection=false, x=298.0, y=384.0, text=Click to select a lemon!, input-type=0, ime-target=false, has-links=false}
|
+------>AppCompatImageView{id=2131230939, res-name=image_lemon_state, visibility=VISIBLE, width=420, height=525, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@c946166, tag=null, root-is-layout-requested=false, has-input-connection=false, x=330.0, y=530.0}
|
+---->ActionBarContainer{id=2131230773, res-name=action_bar_container, visibility=VISIBLE, width=1080, height=147, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.ActionBarOverlayLayout$LayoutParams@241ecfd, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+----->Toolbar{id=2131230771, res-name=action_bar, visibility=VISIBLE, width=1080, height=147, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@13382c0, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+------>AppCompatTextView{id=-1, visibility=VISIBLE, width=257, height=71, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.Toolbar$LayoutParams@5455bf9, tag=null, root-is-layout-requested=false, has-input-connection=false, x=42.0, y=38.0, text=Lemonade, input-type=0, ime-target=false, has-links=false}
|
+------>ActionMenuView{id=-1, visibility=VISIBLE, width=0, height=147, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.Toolbar$LayoutParams@c24373e, tag=null, root-is-layout-requested=false, has-input-connection=false, x=1080.0, y=0.0, child-count=0}
|
+----->ActionBarContextView{id=2131230779, res-name=action_context_bar, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@c34999f, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=0}
|
+->View{id=16908336, res-name=navigationBarBackground, visibility=VISIBLE, width=1080, height=126, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@92e0aec, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=1794.0}
|
+->View{id=16908335, res-name=statusBarBackground, visibility=VISIBLE, width=1080, height=63, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@e76beb5, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0}
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1538)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:12)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:7)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:8)
at androidx.test.espresso.ViewInteraction.check(ViewInteraction.java:12)
at com.example.lemonade.LemonadeTests.test_squeeze_count_snackbar_is_displayed(LemonadeTests.kt:84)


来源: stackexchange

问:
Change the location of the product comparison button and add to favorites
have a good time
I want to move the WooCommerce product comparison button and the Add to Favorites button and the variable product selection feature to a sidebar that I made myself, but I don't know how to do it.
please guide me.
I could not find a solution for several days!!</p>

ContentLicense: CC BY-SA 4.0


问:
Android + webRtc. Opponent's VideoStream is not displayed in surfaceViewRendered on secondary call
I'm using this library:

```<code>implementation 'com.mesibo.api:webrtc:1.0.5'
</code>```

The problem is when I end the first videoconference and then call again - the opponent's video is not displayed in the surfaceViewRenderer (and his voice is absent as well). Whereas the onAddStream callback inside my PeerConnection.Observer is fired sucessfully when the abonent accepts my new call.

Could you please help me:

Why my peer's MediaStream is not rendered in the surfaceViewRenderer?

What are required steps to take on both peers' sides on ending call (besides peerConnection.close()) - e.g. what else to clear/close/dispose - in order to make everything ready for a new videocall?

Thank you in advance!

Body:
I'm using this library:

implementation 'com.mesibo.api:webrtc:1.0.5'

The problem is when I end the first videoconference and then call again - the opponent's video is not displayed in the surfaceViewRenderer (and his voice is absent as well). Whereas the onAddStream callback inside my PeerConnection.Observer is fired sucessfully when the abonent accepts my new call.

Could you please help me:

Why my peer's MediaStream is not rendered in the surfaceViewRenderer?

What are required steps to take on both peers' sides on ending call (besides peerConnection.close()) - e.g. what else to clear/close/dispose - in order to make everything ready for a new videocall?

Thank you in advance!


问:
Difference beetwen Promise<iTips[]> and Promise<[iTips]> in Typescript
What is the difference between Promise<iTips[]>  and Promise<[iTips]>? Do you get the same result?


问:
Axios not returning network response, resolving despite 422 error
So this is driving me nuts because it was working at one point, and I cannot find anything I changed that would make it not work.

Here is my simple axios post request. Based on my debugging, this is successfully making the network request and the server is returning a 422 error, which I expect (testing invalid login credentials). However, when attempting to log the axios reponse to the console, I get "undefined". It is also returning a resolved promise.

const login = (loginParams) => {
  return axiosLoggedOut.post("/login", loginParams);
};
```
<p>Here is the code for the axios instance I am using. I am only intercepting the request in this, and I know the request it making it to the server, so I don't think the issue would be in here:</p>
<pre class="lang-js prettyprint-override"><code>import Cookies from "js-cookie";
import axios from 'axios';

const axiosLoggedOut = axios.create({
  baseURL: "http://localhost",
  withCredentials: true,
});

const requestTypes = ['post', 'put', 'delete'];

const onRequest = (config) => {
  if (requestTypes.includes(config.method) && !Cookies.get('XSRF-TOKEN')) {
    return setCSRFToken().then(() => config);
  }

  return config;
}

const setCSRFToken = () => {
  return axiosLoggedOut.get('/sanctum/csrf-cookie');
}

axiosLoggedOut.interceptors.request.use(onRequest, null);

export default axiosLoggedOut;
</code>```

Am I missing something obvious here?

Body:
So this is driving me nuts because it was working at one point, and I cannot find anything I changed that would make it not work.

Here is my simple axios post request. Based on my debugging, this is successfully making the network request and the server is returning a 422 error, which I expect (testing invalid login credentials). However, when attempting to log the axios reponse to the console, I get "undefined". It is also returning a resolved promise.

const login = (loginParams) => {
  return axiosLoggedOut.post("/login", loginParams);
};

Here is the code for the axios instance I am using. I am only intercepting the request in this, and I know the request it making it to the server, so I don't think the issue would be in here:

import Cookies from "js-cookie";
import axios from 'axios';

const axiosLoggedOut = axios.create({
  baseURL: "http://localhost",
  withCredentials: true,
});

const requestTypes = ['post', 'put', 'delete'];

const onRequest = (config) => {
  if (requestTypes.includes(config.method) && !Cookies.get('XSRF-TOKEN')) {
    return setCSRFToken().then(() => config);
  }

  return config;
}

const setCSRFToken = () => {
  return axiosLoggedOut.get('/sanctum/csrf-cookie');
}

axiosLoggedOut.interceptors.request.use(onRequest, null);

export default axiosLoggedOut;

Am I missing something obvious here?


问:
Using NavigationLink in ForEach loop in SwiftUI
I have a view that has a grid of buttons.  These buttons lead to another view, but depending on which button is pressed, passes in different information that will populate the view.  This is all already in a NavigationView.

```<code>ForEach(userData) { user in
    NavigationLink(destination: DestinationView(userData: user.data)) {
        Button(action: {}) {
            //button styling
        }
    }
}
</code>```

The buttons display as intended and are clickable but nothing happens.  The subview is a giant black rectangle for testing and it does not appear.  I tried adding to each NavigationLink the isDetailLink(false) modifier, but that did not do anything.

Body:
I have a view that has a grid of buttons.  These buttons lead to another view, but depending on which button is pressed, passes in different information that will populate the view.  This is all already in a NavigationView.

ForEach(userData) { user in
    NavigationLink(destination: DestinationView(userData: user.data)) {
        Button(action: {}) {
            //button styling
        }
    }
}

The buttons display as intended and are clickable but nothing happens.  The subview is a giant black rectangle for testing and it does not appear.  I tried adding to each NavigationLink the isDetailLink(false) modifier, but that did not do anything.


问:
How to find the least shopped month in a csv file with Python?
I have a csv file called purchases.csv and I am trying to find the least and most shopped months. I added the csv file to the end of the question. Here what i got so far;

```<code>import pandas as pd
from collections import Counter

df = pd.read_csv('purchases.csv')

df['date']=pd.to_datetime(df['date']) #Filtering the date to 2020 only
dataset=df[df['date'].dt.year == 2020]

#Exploratory Data Analysis

totalShop = len(dataset) # Total shopping
print(totalShop)

product = len(dataset['item_id'].value_counts()) #How many products there are
print(product) # Ürün Sayısı

count = Counter(dataset['item_id']) #most selled 10 products
maxSold = count.most_common(10)
print(maxSold)
</code>```

I believe I can find it with counter and most_common() but it does not work well. This is what I tried;

```<code>count = Counter(dataset['date'])
maxShopping = count.most_common()
print(maxShopping)
</code>```

I would appriciate if anyone can help me. Thank you so much!

Body:
I have a csv file called purchases.csv and I am trying to find the least and most shopped months. I added the csv file to the end of the question. Here what i got so far;

import pandas as pd
from collections import Counter

df = pd.read_csv('purchases.csv')

df['date']=pd.to_datetime(df['date']) #Filtering the date to 2020 only
dataset=df[df['date'].dt.year == 2020]

#Exploratory Data Analysis

totalShop = len(dataset) # Total shopping
print(totalShop)

product = len(dataset['item_id'].value_counts()) #How many products there are
print(product) # Ürün Sayısı

count = Counter(dataset['item_id']) #most selled 10 products
maxSold = count.most_common(10)
print(maxSold)

I believe I can find it with counter and most_common() but it does not work well. This is what I tried;

count = Counter(dataset['date'])
maxShopping = count.most_common()
print(maxShopping)

I would appriciate if anyone can help me. Thank you so much!


问:
What is the reason of request body not matching the schema?
I'm using swagger to describe a simple endpoint to upload file with date(int64). There is request body:

```<code>put:
  tags:
    - files
  description: Add an associated file to a project
  operationId: addFile
  parameters:
    - name: projectId
      in: path
      required: true
      schema:
        type: string
        format: uuid
  requestBody:
    content:
      multipart/form-data:
        schema:
          $ref: "#/components/schemas/AddFileToProjectRequestBody"
    required: true
  responses:
    200:
      description: Successful
      content: {}
</code>```

and schema:

```<code>  AddFileToProjectRequestBody:
      required:
        - file
      type: object
      properties:
        file:
          type: string
          format: binary
          description: The file to upload
        fileDate:
          type: integer
          format: int64
          minimum: 0
          description: File modified date (Unix timestamp in milliseconds)
</code>```

If I upload a simple file it works fine. But if I am trying to add a fileDate I get an error.
"request body has an error: doesn't match the schema: Error at "/fileDate": Field must be set to integer or not be present"
Looks like it fails to read number as int. Can someone explain to me why? I have tried to change it to string and it worked, but doesn't look logical to me to set date as string.

UPD:

```<code>    ------WebKitFormBoundaryGs2
Content-Disposition: form-data; name="fileDate"

1670485649000
------WebKitFormBoundaryGs2
Content-Disposition: form-data; name="projectFile"; filename="1.txt"
Content-Type: text/plain

------WebKitFormBoundaryGs2--
</code>```

Body:
I'm using swagger to describe a simple endpoint to upload file with date(int64). There is request body:

put:
  tags:
    - files
  description: Add an associated file to a project
  operationId: addFile
  parameters:
    - name: projectId
      in: path
      required: true
      schema:
        type: string
        format: uuid
  requestBody:
    content:
      multipart/form-data:
        schema:
          $ref: "#/components/schemas/AddFileToProjectRequestBody"
    required: true
  responses:
    200:
      description: Successful
      content: {}

and schema:

  AddFileToProjectRequestBody:
      required:
        - file
      type: object
      properties:
        file:
          type: string
          format: binary
          description: The file to upload
        fileDate:
          type: integer
          format: int64
          minimum: 0
          description: File modified date (Unix timestamp in milliseconds)

If I upload a simple file it works fine. But if I am trying to add a fileDate I get an error.
"request body has an error: doesn't match the schema: Error at "/fileDate": Field must be set to integer or not be present"
Looks like it fails to read number as int. Can someone explain to me why? I have tried to change it to string and it worked, but doesn't look logical to me to set date as string.

UPD:

    ------WebKitFormBoundaryGs2
Content-Disposition: form-data; name="fileDate"

1670485649000
------WebKitFormBoundaryGs2
Content-Disposition: form-data; name="projectFile"; filename="1.txt"
Content-Type: text/plain

------WebKitFormBoundaryGs2--


问:
React native material ripple typescript error when using children
I have joined the project where react native material ripple is in use,

```<code> "react-native-material-ripple": "^0.9.1",
 "@types/react-native-material-ripple": "^0.9.2",

</code>```

And there are typescript errors all over the place saying that

```<code> Overload 1 of 2, '(props: RippleProps | Readonly<RippleProps>): Ripple', gave the following error.
    Type '{ children: Element; onPress: () => void; style: { height: number; width: number; margin: number; borderRadius: number; overflow: "hidden"; alignItems: "center"; justifyContent: "center"; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Ripple> & Readonly<RippleProps>'.
      Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Ripple> & Readonly<RippleProps>'.
  Overload 2 of 2, '(props: RippleProps, context: any): Ripple', gave the following error.
    Type '{ children: Element; onPress: () => void; style: { height: number; width: number; margin: number; borderRadius: number; overflow: "hidden"; alignItems: "center"; justifyContent: "center"; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Ripple> & Readonly<RippleProps>'.
      Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Ripple> & Readonly<RippleProps>'.ts(2769)
</code>```

I have checked the documentation and in the example, on GitHub it clearly says that is should contain children https://github.com/n4kz/react-native-material-ripple#usage

would you be able to tell me what can I do to get rid of these errors? It gives a very negative impression that there are errors in every file and a feeling of code being untidy.
Thanks

Body:
I have joined the project where react native material ripple is in use,

 "react-native-material-ripple": "^0.9.1",
 "@types/react-native-material-ripple": "^0.9.2",

And there are typescript errors all over the place saying that

 Overload 1 of 2, '(props: RippleProps | Readonly<RippleProps>): Ripple', gave the following error.
    Type '{ children: Element; onPress: () => void; style: { height: number; width: number; margin: number; borderRadius: number; overflow: "hidden"; alignItems: "center"; justifyContent: "center"; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Ripple> & Readonly<RippleProps>'.
      Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Ripple> & Readonly<RippleProps>'.
  Overload 2 of 2, '(props: RippleProps, context: any): Ripple', gave the following error.
    Type '{ children: Element; onPress: () => void; style: { height: number; width: number; margin: number; borderRadius: number; overflow: "hidden"; alignItems: "center"; justifyContent: "center"; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Ripple> & Readonly<RippleProps>'.
      Property 'children' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Ripple> & Readonly<RippleProps>'.ts(2769)

I have checked the documentation and in the example, on GitHub it clearly says that is should contain children https://github.com/n4kz/react-native-material-ripple#usage

would you be able to tell me what can I do to get rid of these errors? It gives a very negative impression that there are errors in every file and a feeling of code being untidy.
Thanks


问:
dart: how can I pass in a list of documents which contain a Document Ref and return a field for each Referenced doc?
I have as an input a list of Documents (a Sub Collection on Firestore).  Each Document contains a field that is a Document Reference to the Context collection.

I want to return as a String List the field for each Context record referenced by this list of Document References.

```<code>List<String> returnContextNameListfromContextDocs(
    List<UserContextsRecord>? listOfUserContexts) {

       final List<String> contextNames = [];

       listOfUserContexts.forEach((element) {

          contextNames.add(element...?) //element just has Document Reference, I don't know how to look up in Firebase the corresponding document

       }

    }
</code>```

Body:
I have as an input a list of Documents (a Sub Collection on Firestore).  Each Document contains a field that is a Document Reference to the Context collection.

I want to return as a String List the field for each Context record referenced by this list of Document References.

List<String> returnContextNameListfromContextDocs(
    List<UserContextsRecord>? listOfUserContexts) {

       final List<String> contextNames = [];

       listOfUserContexts.forEach((element) {

          contextNames.add(element...?) //element just has Document Reference, I don't know how to look up in Firebase the corresponding document

       }

    }


问:
(Finbuckle) How to add/remove tenants without stopping the NET Service?
I have NET Service, it works with multiple tenants using Finbuckle.Multitenant framework like this

Tenants(N)->NET Service->N tenants dataases

How to add (N+1)th tenant or remove one tenant without stopping the NET Service?


问:
how to use on_conflict within sqlalchemy orm setup?
In fact, I understand where the problem is. I am trying to replace an immune key.

Because I use an email address as a unique ID in the Database and this is my first time setting up sqlalchemy is ORM I need help.

The strategy that I try to achieve is trying to write multiple columns but if that key (email) exists update other columns of this key.

I know how to do this directly via psycopg2 but can't figure out how to setup ORM to behave this way.

```<code>sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation)
duplicate key value violates unique constraint "db_pkey" DETAIL:  Key
(email)=(smb_email) already exists.
</code>```

my current ORM db_setup is:

```<code>from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from dotenv import load_dotenv
from pathlib import Path
import os

env_path = Path('.')/'.env'
load_dotenv(dotenv_path=env_path)

SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL")

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={}, future=True)
SessionLocal = sessionmaker(
    autocommit=False, autoflush=False, bind=engine, future=True)

Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
</code>```

func that calls the database and returns that error:

```<code>def create_user(db: Session, user: UserCreate):
    db_user = User(email=user.email, password=user.password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
</code>```

if important, this is the pydantic base:

```<code>from datetime import datetime

from pydantic import BaseModel

class UserBase(BaseModel):
    email: str

class UserCreate(UserBase):
    password: str

class User(UserBase):
    loyalty_account_id: str
    member_id: str
    account_pin: str
    first_name: str
    last_name: str
    cell_phone_number: str
    birth_date: str
    address_line_1: str
    address_line_2: str
    city: str
    state: str
    zip_code: str
    preferred_card_id: str
    card_pin: str
    prompt_card_id: str
    telegram_chat_id: str

    class Config:
        orm_mode = True
</code>```

Body:
In fact, I understand where the problem is. I am trying to replace an immune key.

Because I use an email address as a unique ID in the Database and this is my first time setting up sqlalchemy is ORM I need help.

The strategy that I try to achieve is trying to write multiple columns but if that key (email) exists update other columns of this key.

I know how to do this directly via psycopg2 but can't figure out how to setup ORM to behave this way.

sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation)
duplicate key value violates unique constraint "db_pkey" DETAIL:  Key
(email)=(smb_email) already exists.

my current ORM db_setup is:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from dotenv import load_dotenv
from pathlib import Path
import os

env_path = Path('.')/'.env'
load_dotenv(dotenv_path=env_path)

SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL")

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={}, future=True)
SessionLocal = sessionmaker(
    autocommit=False, autoflush=False, bind=engine, future=True)

Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

func that calls the database and returns that error:

def create_user(db: Session, user: UserCreate):
    db_user = User(email=user.email, password=user.password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

if important, this is the pydantic base:

from datetime import datetime

from pydantic import BaseModel

class UserBase(BaseModel):
    email: str

class UserCreate(UserBase):
    password: str

class User(UserBase):
    loyalty_account_id: str
    member_id: str
    account_pin: str
    first_name: str
    last_name: str
    cell_phone_number: str
    birth_date: str
    address_line_1: str
    address_line_2: str
    city: str
    state: str
    zip_code: str
    preferred_card_id: str
    card_pin: str
    prompt_card_id: str
    telegram_chat_id: str

    class Config:
        orm_mode = True


问:
lighthouse auditing : Avoid an excessive DOM size , what is the best practice to have 2000 options in select tag with out affecting the performance?
i'm trying to fix the performance issues reported by lighthouse.
one of these issues is select tag has about 2000 options
so light house telling me " avoid an excessive DOM size : A large DOM will increase memory usage, cause longer style calculations, and produce costly layout reflows "

Example :

```<code><select>
<option>2000</option>
<option>1999</option>
<option>1998</option>
.
.
.
<option>1</option>
</select>
</code>```

I used pugjs to generate the 2000 options

what do you think the best practice would be to avoid this performance issue ?

Body:
i'm trying to fix the performance issues reported by lighthouse.
one of these issues is select tag has about 2000 options
so light house telling me " avoid an excessive DOM size : A large DOM will increase memory usage, cause longer style calculations, and produce costly layout reflows "

Example :

<select>
<option>2000</option>
<option>1999</option>
<option>1998</option>
.
.
.
<option>1</option>
</select>

I used pugjs to generate the 2000 options

what do you think the best practice would be to avoid this performance issue ?


问:
How to include a ? in Java 11 HTTP Client URL?
I have a URL from a third party so no option of removing the nasty characters.  For security purposes I have put a dummy company in mybadurl.com and also replaced the account number with AccountNo.

```<code>https://mybadurl.com/(Portfolios=['AccountNo'],FromDate=2022-09-20,ToDate=2022-09-20,ClassificationID=-8)?$expand=Portfolio($select=PortfolioCode,ReconciliationStatus),security($select=*)
</code>```

The ? is causing the bad response below.  I need a way of turning this off so that Java HTTP Client will accept my URL.  Note I have already encoded with URLEncoder

```<code>A potentially dangerous Request.Path value was detected from the client (?).
at System.Web.HttpRequest.ValidateInputIfRequiredByConfig()
at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)
</code>```

Below is my complete code

```<code>import java.net.*;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public String getAdventPerformanceData(@RequestBody AdventDataRequest requestMessage) throws IOException, ParseException, InterruptedException {
HttpClient httpClient = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .proxy(ProxySelector.of(new InetSocketAddress(adventAuthenticator.getProxyURL(),
                adventAuthenticator.getProxyPort())))
        .build();

String query2 = "(Portfolios=['AccountNo'],FromDate=2022-09-20,ToDate=2022-09-20,ClassificationID=-8)?" +
        "$expand=Portfolio($select=PortfolioCode,ReconciliationStatus),security($select=*)";

HttpRequest request = HttpRequest.newBuilder()
        .GET()
        .uri(URI.create("mybadurl.com/Performance" + URLEncoder.encode(query2, StandardCharsets.UTF_8)
                ))
        .header("authorization", "BEARER " + adventAuthenticator.getToken())
        .build();

HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

return response.body();
}
</code>```

I have tried using URLEncoder.encode this works for some special characters such as [ but seemingly you still have a problem with ?.

I have researched around and found a few examples of how to fix in ASP but not Java.

I have tried a modified version of the URL without the ? and I am able to get some sort of response without an error so i know the issue is with the ?.  Unfortunately though I need to include the ? in the syntax to get the response I need from the third party.

Body:
I have a URL from a third party so no option of removing the nasty characters.  For security purposes I have put a dummy company in mybadurl.com and also replaced the account number with AccountNo.

https://mybadurl.com/(Portfolios=['AccountNo'],FromDate=2022-09-20,ToDate=2022-09-20,ClassificationID=-8)?$expand=Portfolio($select=PortfolioCode,ReconciliationStatus),security($select=*)

The ? is causing the bad response below.  I need a way of turning this off so that Java HTTP Client will accept my URL.  Note I have already encoded with URLEncoder

A potentially dangerous Request.Path value was detected from the client (?).
at System.Web.HttpRequest.ValidateInputIfRequiredByConfig()
at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)

Below is my complete code

import java.net.*;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public String getAdventPerformanceData(@RequestBody AdventDataRequest requestMessage) throws IOException, ParseException, InterruptedException {
HttpClient httpClient = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .proxy(ProxySelector.of(new InetSocketAddress(adventAuthenticator.getProxyURL(),
                adventAuthenticator.getProxyPort())))
        .build();

String query2 = "(Portfolios=['AccountNo'],FromDate=2022-09-20,ToDate=2022-09-20,ClassificationID=-8)?" +
        "$expand=Portfolio($select=PortfolioCode,ReconciliationStatus),security($select=*)";

HttpRequest request = HttpRequest.newBuilder()
        .GET()
        .uri(URI.create("mybadurl.com/Performance" + URLEncoder.encode(query2, StandardCharsets.UTF_8)
                ))
        .header("authorization", "BEARER " + adventAuthenticator.getToken())
        .build();

HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

return response.body();
}

I have tried using URLEncoder.encode this works for some special characters such as [ but seemingly you still have a problem with ?.

I have researched around and found a few examples of how to fix in ASP but not Java.

I have tried a modified version of the URL without the ? and I am able to get some sort of response without an error so i know the issue is with the ?.  Unfortunately though I need to include the ? in the syntax to get the response I need from the third party.


问:
SharePoint 2016 color code items that are grouped
I am using a script editor web part (with code inserted) to color code items in rows that are grouped for a sharepoint list. I'm extremely confused as to why the the color applies only when I'm in edit mode. The code I'm using in the script editor is below..

SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() {

   SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
     OnPostRender: function(ctx) {

       var statusColors =  {
          'Wacht' : '#FF0000',
          'In analyse' : '#FCF600'

       };

       var rows = ctx.ListData.Row;
       for (var i=0;i


问:
Why is my receipt not printing on my shop?
I have created a shop and it should print a receipt for the customer but when I go to print it says no pages found.

It should be working after I click the print button to print the page and show preview but its saying nothing to show.

Why is it not printing?

int shopitemid, shopquantity, shopprice, shoptotal, pos = 60;
        string shopname;
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawString("The Androids Dungeon", new Font("Century Gothic", 12, FontStyle.Bold), Brushes.Red, new Point(80));
            e.Graphics.DrawString("ID Product Price Quantity Total", new Font("Century Gothic", 10, FontStyle.Bold), Brushes.Red, new Point(26,40));
            foreach(DataGridViewRow row in datafrmcheckout.Rows)
            {
                shopitemid = Convert.ToInt32(row.Cells["Column1"].Value);
                shopname = "" + row.Cells["Column2"].Value;
                shopprice = Convert.ToInt32(row.Cells["Column3"].Value);
                shopquantity = Convert.ToInt32(row.Cells["Column4"].Value);
                shoptotal = Convert.ToInt32(row.Cells["Column5"].Value);
                e.Graphics.DrawString("" + shopitemid, new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(26, pos));
                e.Graphics.DrawString("" + shopname, new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(45, pos));
                e.Graphics.DrawString("" + shopprice, new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(120, pos));
                e.Graphics.DrawString("" + shopquantity, new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(170, pos));
                e.Graphics.DrawString("" + shoptotal, new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(235, pos));
                pos = pos + 20;

            }
            e.Graphics.DrawString("Grand Total: £ " +grdtotal , new Font("Century Gothic", 12, FontStyle.Bold), Brushes.Crimson, new Point(60, pos + 50));
            e.Graphics.DrawString("***The Android Dungeon***", new Font("Century Gothic", 12, FontStyle.Bold), Brushes.Crimson, new Point(40, pos + 85));
            datafrmcheckout.Rows.Clear();
            datafrmcheckout.Refresh();
            pos = 100;
            grdtotal = 0;

        }

        private void Printbt_Click(object sender, EventArgs e)
        {
            printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("pprnm", 285, 600);
           if(printPreviewDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocument1.Print();
            }
        }

```


问:
retrofit MalformedJsonException
I am receiving a response from the server in JSON format.

```<code>val gson = Gson().newBuilder()
    .setLenient()
    .create()

    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()
</code>```

the response contains characters \r, \n, "  and I get an error "com.google.gson.stream.MalformedJsonException: Unterminated object at line"

please tell me how to process this JSON correctly

tried using Moshi but doesn't work either

```<code>.addConverterFactory(MoshiConverterFactory.create(moshi).asLenient())
</code>```

Title: retrofit MalformedJsonException

Body:
I am receiving a response from the server in JSON format.

val gson = Gson().newBuilder()
    .setLenient()
    .create()

    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()

the response contains characters \r, \n, "  and I get an error "com.google.gson.stream.MalformedJsonException: Unterminated object at line"

please tell me how to process this JSON correctly

tried using Moshi but doesn't work either

.addConverterFactory(MoshiConverterFactory.create(moshi).asLenient())


问:
PyTorch Pre-Allocation to avoid OOM does not work
So, I am trying to finetune FCoref using the trainer in https://github.com/shon-otmazgin/fastcoref

This uses a Dynamic Batching with variable length and this creates an issue on CUDA because once PyTorch allocates memory for the first batch, it does not increase it.

So, following this guide here: https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html#pre-allocate-memory-in-case-of-variable-input-length

I added this to my code and I call it before running the actual training (right after creating the model and moving it to CUDA):

```<code>batch = {
            "input_ids": torch.rand(9, 5, 512),
            "attention_mask": torch.rand(9, 5, 512),
            "gold_clusters": torch.rand(9, 58, 39, 2),
            "leftovers": {
                "input_ids": torch.rand(4),
                "attention_mask": torch.rand(4),
            }
        }
        batch['input_ids'] = torch.tensor(batch['input_ids'], device=self.device)
        batch['attention_mask'] = torch.tensor(batch['attention_mask'],
                                               device=self.device)
        batch['gold_clusters'] = torch.tensor(batch['gold_clusters'],
                                              device=self.device)
        if 'leftovers' in batch:
            batch['leftovers']['input_ids'] = torch.tensor(
                batch['leftovers']['input_ids'], device=self.device)
            batch['leftovers']['attention_mask'] = torch.tensor(
                batch['leftovers']['attention_mask'],
                device=self.device)
        self.model.zero_grad()
        self.model.train()
        with torch.cuda.amp.autocast():
            outputs = self.model(batch, gold_clusters=batch['gold_clusters'],
                                 return_all_outputs=False)

        loss = outputs[0]  # model outputs are always tuple in transformers (see doc)
        loss.backward()
</code>```

At first, I was getting OOM issues with this because it was too big (I basically created the biggest tensors in each key according to my dataset).

So, instead, I created a batch that looks like my biggest batch in the actual data (according to the sum of tensor sizes):

```<code>batch = {
            "input_ids": torch.rand(4, 1, 512),
            "attention_mask": torch.rand(4, 1, 512),
            "gold_clusters": torch.rand(4, 11, 24, 2),
            "leftovers": {
                "input_ids": torch.rand(4, 459),
                "attention_mask": torch.rand(4, 459),
            }
        }
</code>```

Now, this works but when the actual training starts, I run into the same issue even though the first batch is smaller than the pre-allocation batch:

OutOfMemoryError: CUDA out of memory. Tried to allocate 74.00 MiB (GPU 0; 14.56 GiB total capacity; 13.31 GiB already allocated; 36.44 MiB free; 13.76 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

Other things I tried:

export 'PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:21'

Decreasing batch size, but due to the variability I keep running into the same issue.

My machine:

runs Debian 4.19.260-1 (2022-09-29) x86_64 GNU/Linux

T4 GPU with 16 GB VRAM

Any idea?

Body:
So, I am trying to finetune FCoref using the trainer in https://github.com/shon-otmazgin/fastcoref

This uses a Dynamic Batching with variable length and this creates an issue on CUDA because once PyTorch allocates memory for the first batch, it does not increase it.

So, following this guide here: https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html#pre-allocate-memory-in-case-of-variable-input-length

I added this to my code and I call it before running the actual training (right after creating the model and moving it to CUDA):

batch = {
            "input_ids": torch.rand(9, 5, 512),
            "attention_mask": torch.rand(9, 5, 512),
            "gold_clusters": torch.rand(9, 58, 39, 2),
            "leftovers": {
                "input_ids": torch.rand(4),
                "attention_mask": torch.rand(4),
            }
        }
        batch['input_ids'] = torch.tensor(batch['input_ids'], device=self.device)
        batch['attention_mask'] = torch.tensor(batch['attention_mask'],
                                               device=self.device)
        batch['gold_clusters'] = torch.tensor(batch['gold_clusters'],
                                              device=self.device)
        if 'leftovers' in batch:
            batch['leftovers']['input_ids'] = torch.tensor(
                batch['leftovers']['input_ids'], device=self.device)
            batch['leftovers']['attention_mask'] = torch.tensor(
                batch['leftovers']['attention_mask'],
                device=self.device)
        self.model.zero_grad()
        self.model.train()
        with torch.cuda.amp.autocast():
            outputs = self.model(batch, gold_clusters=batch['gold_clusters'],
                                 return_all_outputs=False)

        loss = outputs[0]  # model outputs are always tuple in transformers (see doc)
        loss.backward()

At first, I was getting OOM issues with this because it was too big (I basically created the biggest tensors in each key according to my dataset).

So, instead, I created a batch that looks like my biggest batch in the actual data (according to the sum of tensor sizes):

batch = {
            "input_ids": torch.rand(4, 1, 512),
            "attention_mask": torch.rand(4, 1, 512),
            "gold_clusters": torch.rand(4, 11, 24, 2),
            "leftovers": {
                "input_ids": torch.rand(4, 459),
                "attention_mask": torch.rand(4, 459),
            }
        }

Now, this works but when the actual training starts, I run into the same issue even though the first batch is smaller than the pre-allocation batch:

OutOfMemoryError: CUDA out of memory. Tried to allocate 74.00 MiB (GPU 0; 14.56 GiB total capacity; 13.31 GiB already allocated; 36.44 MiB free; 13.76 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

Other things I tried:

export 'PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:21'

Decreasing batch size, but due to the variability I keep running into the same issue.

My machine:

runs Debian 4.19.260-1 (2022-09-29) x86_64 GNU/Linux

T4 GPU with 16 GB VRAM

Any idea?


问:
I get post error: net::ERR_UNSAFE_PORT when doing a POST using Ionic in WebStorm
I'm trying to make a POST request to an already existing API which doesn't have any problems returning what I want when I do a post using Postman. I'm debugging on Chrome and I'm programming in WebStorm IDE developing an Ionic application.

I have access to a VPN which then connects to the server and all works well.
Ionic serve command also returns the same error:

error: net::ERR_UNSAFE_PORT

On my login.page.ts I have:

```<code>this.loginService.postCredentials(data).subscribe((dataReturned)=>{
  this.dataReturned = JSON.stringify(dataReturned);
});
</code>```
```<code>const data = {Username: 'encripted ', Password:'encripted '}; (Encription is not the problem)
</code>```

Then on my login service, I have:

```<code>const httpOptions = {
  headers: new HttpHeaders({
// eslint-disable-next-line @typescript-eslint/naming-convention
'Content-Type': 'application/json',
// eslint-disable-next-line @typescript-eslint/naming-convention
'Access-Control-Allow-Headers': 'Content-Type',
// eslint-disable-next-line @typescript-eslint/naming-convention
'Access-Control-Allow-Methods': 'POST',
// eslint-disable-next-line @typescript-eslint/naming-convention
'Access-Control-Allow-Origin':'*'
  })
};
</code>```
```<code>return this.http.post(this.url, JSON.stringify(data),httpOptions);
</code>```
```<code>url = 'http://x.x.x.x:PORT1/api/post/login';
</code>```

I have already tried to do the following on the Chrome's direct short-cut:

"C:\Program Files\Google\Chrome\Application\chrome.exe" --explicitly-allowed-ports=PORT1.PORT2
```

PORT 2: the one that WebStorm launches the Chrome tab on.

I would sincerely appreciate any help.

Body:
I'm trying to make a POST request to an already existing API which doesn't have any problems returning what I want when I do a post using Postman. I'm debugging on Chrome and I'm programming in WebStorm IDE developing an Ionic application.

I have access to a VPN which then connects to the server and all works well.
Ionic serve command also returns the same error:

error: net::ERR_UNSAFE_PORT

On my login.page.ts I have:

this.loginService.postCredentials(data).subscribe((dataReturned)=>{
  this.dataReturned = JSON.stringify(dataReturned);
});

const data = {Username: 'encripted ', Password:'encripted '}; (Encription is not the problem)

Then on my login service, I have:

const httpOptions = {
  headers: new HttpHeaders({
// eslint-disable-next-line @typescript-eslint/naming-convention
'Content-Type': 'application/json',
// eslint-disable-next-line @typescript-eslint/naming-convention
'Access-Control-Allow-Headers': 'Content-Type',
// eslint-disable-next-line @typescript-eslint/naming-convention
'Access-Control-Allow-Methods': 'POST',
// eslint-disable-next-line @typescript-eslint/naming-convention
'Access-Control-Allow-Origin':'*'
  })
};

return this.http.post(this.url, JSON.stringify(data),httpOptions);

url = 'http://x.x.x.x:PORT1/api/post/login';

I have already tried to do the following on the Chrome's direct short-cut:

"C:\Program Files\Google\Chrome\Application\chrome.exe" --explicitly-allowed-ports=PORT1.PORT2

PORT 2: the one that WebStorm launches the Chrome tab on.

I would sincerely appreciate any help.