问:
ViewPager2 height change animation stuttering on android tablets
I am trying to animate a ViewPager2. When the user changes the page to a page of a different height, I want the view to smoothly grow or shrink to the new height. This works fine on phones, but when I try this on a tablet, the animation stutters. How could I fix this?

Animation code:

```<code>private fun animateHeightChange(view: ConstraintLayout, viewPager: ViewPager2) {
        val viewPagerAnimator = ValueAnimator.ofInt(viewPager.height, view.measuredHeight).apply {
            interpolator = LinearInterpolator()
            addUpdateListener {
                val animatedValue = it.animatedValue as Int
                viewPager.layoutParams = viewPager.layoutParams.apply { height = animatedValue }
            }
        }

        AnimatorSet().run {
            doOnStart { viewPager.setLayerType(View.LAYER_TYPE_HARDWARE, null) }
            doOnEnd {
                baseActionSheetBinding.root.setLayerType(View.LAYER_TYPE_NONE, null)
                viewPager.setLayerType(View.LAYER_TYPE_NONE, null)
            }
            play(viewPagerAnimator)
            start()
        }
    }

</code>```

View:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/view_pager_indicator"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/view_pager_indicator"
        android:layout_width="match_parent"
        android:layout_height="8dp"
        android:layout_marginBottom="12dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view_pager"
        app:tabBackground="@drawable/view_pager_indicator"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

</code>```

Body:
I am trying to animate a ViewPager2. When the user changes the page to a page of a different height, I want the view to smoothly grow or shrink to the new height. This works fine on phones, but when I try this on a tablet, the animation stutters. How could I fix this?

Animation code:

private fun animateHeightChange(view: ConstraintLayout, viewPager: ViewPager2) {
        val viewPagerAnimator = ValueAnimator.ofInt(viewPager.height, view.measuredHeight).apply {
            interpolator = LinearInterpolator()
            addUpdateListener {
                val animatedValue = it.animatedValue as Int
                viewPager.layoutParams = viewPager.layoutParams.apply { height = animatedValue }
            }
        }

        AnimatorSet().run {
            doOnStart { viewPager.setLayerType(View.LAYER_TYPE_HARDWARE, null) }
            doOnEnd {
                baseActionSheetBinding.root.setLayerType(View.LAYER_TYPE_NONE, null)
                viewPager.setLayerType(View.LAYER_TYPE_NONE, null)
            }
            play(viewPagerAnimator)
            start()
        }
    }

View:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/view_pager_indicator"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/view_pager_indicator"
        android:layout_width="match_parent"
        android:layout_height="8dp"
        android:layout_marginBottom="12dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view_pager"
        app:tabBackground="@drawable/view_pager_indicator"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp" />

</androidx.constraintlayout.widget.ConstraintLayout>


来源: stackexchange

问:
how to design application architechture where only api gateway is public exposed doing authentication and authorization
we need to design an application where there is three entities which will be consuming my apis

web application

mobile application

third party tools

i am planning on following architecture API Gatway will be exposed to external world. request coming from entities will be authenticated with OPENID via API Gateway plugin. then OPENID will return JWT to access the internal microservices.

This works fine since users from web and app will be redirected to OIDC for authentication in return token but i do not know how it will work for third party tool. i cannot do browser redirection with them.

how can we implement this architecture?

ContentLicense: CC BY-SA 4.0


问:
Dropdown list dynamic data in jinja
First of all im using python and flask.
I have a signup form for my websits, it has two drop down lists

for example if users selects A from dropdown1 the dropdown2 should show A1,A2 and A3
and if user selects B the second drop down list should include B1,B2 and B3

I've searched the internet but could not find any suitable answer.
Thanks for this amazing website :))))

Title: Dropdown list dynamic data in jinja


问:
Sound is not updating according to slider expo av
I am trying to update the song, when i move the slider the song pauses which is good then after releasing the slider and hitting play the song restarts instead of starting from that position
here is the code: (I divided the code to get rid of the unrelated parts)
THE HTML PART:

```<code>                      <TouchableHighlight onPress={() => navigation.navigate("Player")}
                           style={styles.playerPopupBack} >
                        <View style={styles.player}>
                          <View style={styles.playerart}>
                            <Image  source={{uri: 'https://c.saavncdn.com/972/NO-LOVE-
                            Punjabi-2022-20220621214632-500x500.jpg'}} style=
                          {styles.image}/>
                          </View>
                          <TouchableHighlight onPress={updatePlayer} style=
                           {styles.playerbutton}>
                            <View>
                              <BackImage />
                              <View style={styles.innerButton}>
                                {displayPlayer()}
                              </View>
                            </View>
                          </TouchableHighlight>
                            <Text style={styles.playertitle}>No Love</Text>
                            <Text  style={styles.playerdesc}>Shubh</Text>

                            <Slider
                            style={styles.slider}
                            disabled
                            value={percent}
                            onValueChange={(value)=>setRange(value)}
                            onSlidingStart={
                              async() =>{
                                if(play == 1){
                                  return;
                                }
                                try {
                                  setPlay(1);
                                  setPlayB(false);
                                  await sound.pauseAsync();
                                } catch (error) {
                                  console.log("Error inside onSlidingStart",error);
                                }
                              }
                            }
                            onSlidingComplete={async (value)=>{
                              if(play!=1){
                                return;
                              }
                              try {
                                const status = await
                                sound.setPositionAsync(sound.durationMillis * value);
                                await sound.pauseAsync();
                                setSound(sound,
                               {soundObj:status,playbackPosition:status.positionMillis})

                              } catch (error) {
                                console.log("Error inside onSlidingComplete",error);
                              }

                            }}
                            minimumValue={0}
                            maximumValue={1}
                            thumbTintColor="white"
                            minimumTrackTintColor="#9D34D1"
                            maximumTrackTintColor="#315CE8"
                            />
                        </View>
                        </TouchableHighlight>

                    </SafeAreaView>
                  );
                }
</code>```

THE JS PART :

```<code>                      import { StatusBar } from 'expo-status-bar';
                  import React, { useEffect, useState } from 'react';
                  import { SafeAreaView, StyleSheet, Text, View, ScrollView,
                  TouchableHighlight, Dimensions} from 'react-native';
                  import { MainLogo } from '../../logos/mainLogo';
                  import { TextInput } from "react-native";
                  import reactDom from 'react-dom';
                  import { BackImage } from '../../logos/background';
                  import { PlayLogo } from '../../logos/play';
                  import { PauseLogo } from '../../logos/pause';
                  import { Image } from 'react-native';
                  import Slider from "@react-native-community/slider";
                  import { Audio } from 'expo-av';
                  import { createStackNavigator } from "@react-navigation/stack";
                  import { NavigationContainer } from "@react-navigation/native";
                  import {Player} from './homeScreens/playerPopUp';
                  import { Sound } from 'expo-av/build/Audio';
                       const [range,setRange] = useState(0);
                    const [play,setPlay] = useState(1);
                    const [playB,setPlayB] = useState(false);
                    const [songLoaded,setSongLoaded] = useState(false);
                    const [sound,setSound] = useState(new Audio.Sound());
                    const [percent,setPercent] = useState(0);

                    Audio.setAudioModeAsync({
                      staysActiveInBackground: true,
                      playsInSilentModeIOS: true
                  });

                    var LoadSong = async() => {
                      if(songLoaded == false) {
                        await sound.loadAsync({
                          uri: example
                        })
                        setSongLoaded(true);
                        await sound.playAsync();
                        setPlayB(true);
                      }
                      else {
                        console.log("SONG ALREADY PLAYING");
                      }
                    }

                    var updatePlayer = async() => {
                      if(play == -1) { //TO PAUSE THE SONG
                        if(songLoaded == true) {
                          if(playB == true) {
                            await sound.pauseAsync();
                            setPlayB(false);
                          }
                          setPlay(1);
                        }
                      }
                      else if(play == 1) { //TO PLAY THE SONG
                        if(songLoaded == false) {
                          LoadSong();
                        }
                        else {
                          if(playB == false) {
                            await sound.playAsync();
                            setPlayB(true);
                          }
                        }
                        setPlay(-1);
                      }
                    }

                    var displayPlayer = () => {
                      if(play == 1) {
                        return <PlayLogo />
                      }
                      else {
                        return <PauseLogo />
                      }
                    }
</code>```

The code for just a simple music player. please check the code if you need more details comment below thank you!

Body:
I am trying to update the song, when i move the slider the song pauses which is good then after releasing the slider and hitting play the song restarts instead of starting from that position
here is the code: (I divided the code to get rid of the unrelated parts)
THE HTML PART:

                      <TouchableHighlight onPress={() => navigation.navigate("Player")}
                           style={styles.playerPopupBack} >
                        <View style={styles.player}>
                          <View style={styles.playerart}>
                            <Image  source={{uri: 'https://c.saavncdn.com/972/NO-LOVE-
                            Punjabi-2022-20220621214632-500x500.jpg'}} style=
                          {styles.image}/>
                          </View>
                          <TouchableHighlight onPress={updatePlayer} style=
                           {styles.playerbutton}>
                            <View>
                              <BackImage />
                              <View style={styles.innerButton}>
                                {displayPlayer()}
                              </View>
                            </View>
                          </TouchableHighlight>
                            <Text style={styles.playertitle}>No Love</Text>
                            <Text  style={styles.playerdesc}>Shubh</Text>

                            <Slider
                            style={styles.slider}
                            disabled
                            value={percent}
                            onValueChange={(value)=>setRange(value)}
                            onSlidingStart={
                              async() =>{
                                if(play == 1){
                                  return;
                                }
                                try {
                                  setPlay(1);
                                  setPlayB(false);
                                  await sound.pauseAsync();
                                } catch (error) {
                                  console.log("Error inside onSlidingStart",error);
                                }
                              }
                            }
                            onSlidingComplete={async (value)=>{
                              if(play!=1){
                                return;
                              }
                              try {
                                const status = await
                                sound.setPositionAsync(sound.durationMillis * value);
                                await sound.pauseAsync();
                                setSound(sound,
                               {soundObj:status,playbackPosition:status.positionMillis})

                              } catch (error) {
                                console.log("Error inside onSlidingComplete",error);
                              }

                            }}
                            minimumValue={0}
                            maximumValue={1}
                            thumbTintColor="white"
                            minimumTrackTintColor="#9D34D1"
                            maximumTrackTintColor="#315CE8"
                            />
                        </View>
                        </TouchableHighlight>

                    </SafeAreaView>
                  );
                }

THE JS PART :

                      import { StatusBar } from 'expo-status-bar';
                  import React, { useEffect, useState } from 'react';
                  import { SafeAreaView, StyleSheet, Text, View, ScrollView,
                  TouchableHighlight, Dimensions} from 'react-native';
                  import { MainLogo } from '../../logos/mainLogo';
                  import { TextInput } from "react-native";
                  import reactDom from 'react-dom';
                  import { BackImage } from '../../logos/background';
                  import { PlayLogo } from '../../logos/play';
                  import { PauseLogo } from '../../logos/pause';
                  import { Image } from 'react-native';
                  import Slider from "@react-native-community/slider";
                  import { Audio } from 'expo-av';
                  import { createStackNavigator } from "@react-navigation/stack";
                  import { NavigationContainer } from "@react-navigation/native";
                  import {Player} from './homeScreens/playerPopUp';
                  import { Sound } from 'expo-av/build/Audio';
                       const [range,setRange] = useState(0);
                    const [play,setPlay] = useState(1);
                    const [playB,setPlayB] = useState(false);
                    const [songLoaded,setSongLoaded] = useState(false);
                    const [sound,setSound] = useState(new Audio.Sound());
                    const [percent,setPercent] = useState(0);

                    Audio.setAudioModeAsync({
                      staysActiveInBackground: true,
                      playsInSilentModeIOS: true
                  });

                    var LoadSong = async() => {
                      if(songLoaded == false) {
                        await sound.loadAsync({
                          uri: example
                        })
                        setSongLoaded(true);
                        await sound.playAsync();
                        setPlayB(true);
                      }
                      else {
                        console.log("SONG ALREADY PLAYING");
                      }
                    }

                    var updatePlayer = async() => {
                      if(play == -1) { //TO PAUSE THE SONG
                        if(songLoaded == true) {
                          if(playB == true) {
                            await sound.pauseAsync();
                            setPlayB(false);
                          }
                          setPlay(1);
                        }
                      }
                      else if(play == 1) { //TO PLAY THE SONG
                        if(songLoaded == false) {
                          LoadSong();
                        }
                        else {
                          if(playB == false) {
                            await sound.playAsync();
                            setPlayB(true);
                          }
                        }
                        setPlay(-1);
                      }
                    }

                    var displayPlayer = () => {
                      if(play == 1) {
                        return <PlayLogo />
                      }
                      else {
                        return <PauseLogo />
                      }
                    }

The code for just a simple music player. please check the code if you need more details comment below thank you!


问:
Change Video Background dynamically in react-native onPress
Today for a school project I need to create a shop in which when you click a button, the Video (used as background) in the Home page changes.

I found how to change color through style but here the Video is a component and the Video's link is it content so I'm not sure how to proceed...

I'm trying to use useEffect like this :

```<code>useEffect(() => {

        const backGround = document.getElementById("bg");
        setBg(backGround.Video = "source{require("./test2.mp4")}");

    }, [bg])
</code>```

`

If you guys could refer me, it would be awesome !

Body:
Today for a school project I need to create a shop in which when you click a button, the Video (used as background) in the Home page changes.

I found how to change color through style but here the Video is a component and the Video's link is it content so I'm not sure how to proceed...

I'm trying to use useEffect like this :

useEffect(() => {

        const backGround = document.getElementById("bg");
        setBg(backGround.Video = "source{require("./test2.mp4")}");

    }, [bg])

`

If you guys could refer me, it would be awesome !


问:
Proto Message - Get Field by String (name)
I want to get a specific Field from a proto Message with a String, i will try my best to explain what i need to know:

For example we have this .proto File:

```<code>message Employee {
  string id = 1;
  PersonData person_data = 2;
  ...
}

message PersonData {
  string first_name = 1;
  string surname = 2;
  ...
}
</code>```

Now iam getting a String with a field name like "person_data.first_name".

For example if you want to get the id you must just write:

```<code>FieldDescriptor fieldDescriptor = message.getDescriptorForType().findFieldByName("id");
</code>```

But i need the field "first_name". How can i manage this?
I tried a lot of methods but nothing worked.

Anyone any ideas?

Body:
I want to get a specific Field from a proto Message with a String, i will try my best to explain what i need to know:

For example we have this .proto File:

message Employee {
  string id = 1;
  PersonData person_data = 2;
  ...
}

message PersonData {
  string first_name = 1;
  string surname = 2;
  ...
}

Now iam getting a String with a field name like "person_data.first_name".

For example if you want to get the id you must just write:

FieldDescriptor fieldDescriptor = message.getDescriptorForType().findFieldByName("id");

But i need the field "first_name". How can i manage this?
I tried a lot of methods but nothing worked.

Anyone any ideas?


问:
PyCharm Notebook Table Mouseover Highlight Color
In PyCharm if in Jupyter notebook the result tables have a white background highlight color if mouse is moved over. I can't find any setting that is related to this behavior. Any hint?</p>


问:
Trying to retrieve GitHub "Code Scanning" is enabled or not (GitHub API)
I am working on a GitHub automation using github APIs. As a part of this automation, I want to get the status of "Code Scanning".

https://api.github.com/repos/{Org}/{repo}/code-scanning/analyses

I have tried with above API endpoint but it's not giving me whether the code scanning is enabled or not. Its only retrieving the executions of code scanning. Therefore, if a user enabled the code scanning and then disabled it, then the above endpoint will retrieve result set for previous executions.

I checked the Graphql documentation as well, but I couldn't find any resource to retrieve this. Following is the field I want to retrieve using an API call.

GitHub code scanning field


问:
Usage of writeInt() of DataStoreHelper.kt class results in UnresolvedReference when used in viewmodel
I am following this tutorial to write & read int:
https://betterprogramming.pub/using-jetpack-preferences-datastore-more-effectively-414e1126cff7

However, when using context.writeInt in viewmodel, I get unresolved reference error.

DataStoreHelper.kt

```<code>//Preference Name
const val PREFERENCE_NAME = "MyDataStore"

class DataStoreHelper {

    //Instance of DataStore
    val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = PREFERENCE_NAME)

    /**
     * Add Integer to the data store
     */
    suspend fun Context.writeInt(key: String, value: Int) {
        dataStore.edit { pref -> pref[intPreferencesKey(key)] = value }
    }

    /**
     * Reading the Int value from the data store
     */
    fun Context.readInt(key: String): Flow<Int> {
        return dataStore.data.map { pref ->
            pref[intPreferencesKey(key)] ?: 0
        }
    }
}
</code>```

WeeklyPlannerViewModel.kt

```<code>@HiltViewModel
class WeeklyPlannerViewModel @Inject constructor(
    @ApplicationContext val appContext: Application
): ViewModel()  {

    companion object{
        const val NAME_USER_KEY = "name"
    }

    val dataStoreHelper = DataStoreHelper()

    fun saveRecipeId(id: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            appContext.writeInt(NAME_USER_KEY, id)

        }
    }

</code>```

Usign DataStoreHelper() to access the function, but that did not work either.

Body:
I am following this tutorial to write & read int:
https://betterprogramming.pub/using-jetpack-preferences-datastore-more-effectively-414e1126cff7

However, when using context.writeInt in viewmodel, I get unresolved reference error.

DataStoreHelper.kt

//Preference Name
const val PREFERENCE_NAME = "MyDataStore"

class DataStoreHelper {

    //Instance of DataStore
    val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = PREFERENCE_NAME)

    /**
     * Add Integer to the data store
     */
    suspend fun Context.writeInt(key: String, value: Int) {
        dataStore.edit { pref -> pref[intPreferencesKey(key)] = value }
    }

    /**
     * Reading the Int value from the data store
     */
    fun Context.readInt(key: String): Flow<Int> {
        return dataStore.data.map { pref ->
            pref[intPreferencesKey(key)] ?: 0
        }
    }
}

WeeklyPlannerViewModel.kt

@HiltViewModel
class WeeklyPlannerViewModel @Inject constructor(
    @ApplicationContext val appContext: Application
): ViewModel()  {

    companion object{
        const val NAME_USER_KEY = "name"
    }

    val dataStoreHelper = DataStoreHelper()

    fun saveRecipeId(id: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            appContext.writeInt(NAME_USER_KEY, id)

        }
    }

Usign DataStoreHelper() to access the function, but that did not work either.


问:
Dynamic progressBar in Powershell
I've make a powershell script with running multiple powershell. I would like to do a GUI progressbar that will advandce according to the content of a log.txt file in real time. (All my script write in this file when they finish).

For now I've made this, it's works but my logs need to be finish and didn't work in real time.

```<code># Pour bloquer le resize du form et supprimer les icones Minimize and Maximize
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$form.MaximizeBox = $False
$form.MinimizeBox = $False
# Choix de la taille
$form.Size = New-Object System.Drawing.Size(400,370)

# Barre de progression
$progress = New-Object System.Windows.Forms.ProgressBar
$progress.Location = New-Object System.Drawing.Point(20,185)
$progress.Name = 'progressBar'
$progress.Step = 1
$progress.Size = New-Object System.Drawing.Size(350,23)
$form.Controls.Add($progress)

# Bouton OK
$button_ok = New-Object System.Windows.Forms.Button
$button_ok.Text = "OK"
$button_ok.Size = New-Object System.Drawing.Size(355,40)
$button_ok.Location = New-Object System.Drawing.Size(20,230)
$form.Controls.Add($button_ok)

$CheminLOGS = "c:\logs.txt"

$button_ok.Add_Click(
{

    Do {
    $Check1 = Select-String -Path $CheminLOGS -Pattern "FIN SCRIPT-PHASE1"
    Write-Host "La Phase1 n'est pas terminee"
    TIMEOUT 5 /nobreak
}Until($Check1 -Like "$CheminLOGS*")

Write-Host "PHASE 1 TERMINEE"
$progress.Value = 25

Do {
    $Check2 = Select-String -Path $CheminLOGS -Pattern "FIN SCRIPT-PHASE2"
    Write-Host "La Phase2 n'est pas terminee"
    TIMEOUT 5 /nobreak
}Until($Check2 -Like "$CheminLOGS*")

Write-host PHASE 2 Terminée

$progress.Value = 100

})

$form.Topmost = $true
$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()
</code>```

Can you help me ?

Title: Dynamic progressBar in Powershell

Body:
I've make a powershell script with running multiple powershell. I would like to do a GUI progressbar that will advandce according to the content of a log.txt file in real time. (All my script write in this file when they finish).

For now I've made this, it's works but my logs need to be finish and didn't work in real time.

# Pour bloquer le resize du form et supprimer les icones Minimize and Maximize
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$form.MaximizeBox = $False
$form.MinimizeBox = $False
# Choix de la taille
$form.Size = New-Object System.Drawing.Size(400,370)

# Barre de progression
$progress = New-Object System.Windows.Forms.ProgressBar
$progress.Location = New-Object System.Drawing.Point(20,185)
$progress.Name = 'progressBar'
$progress.Step = 1
$progress.Size = New-Object System.Drawing.Size(350,23)
$form.Controls.Add($progress)

# Bouton OK
$button_ok = New-Object System.Windows.Forms.Button
$button_ok.Text = "OK"
$button_ok.Size = New-Object System.Drawing.Size(355,40)
$button_ok.Location = New-Object System.Drawing.Size(20,230)
$form.Controls.Add($button_ok)

$CheminLOGS = "c:\logs.txt"

$button_ok.Add_Click(
{

    Do {
    $Check1 = Select-String -Path $CheminLOGS -Pattern "FIN SCRIPT-PHASE1"
    Write-Host "La Phase1 n'est pas terminee"
    TIMEOUT 5 /nobreak
}Until($Check1 -Like "$CheminLOGS*")

Write-Host "PHASE 1 TERMINEE"
$progress.Value = 25

Do {
    $Check2 = Select-String -Path $CheminLOGS -Pattern "FIN SCRIPT-PHASE2"
    Write-Host "La Phase2 n'est pas terminee"
    TIMEOUT 5 /nobreak
}Until($Check2 -Like "$CheminLOGS*")

Write-host PHASE 2 Terminée

$progress.Value = 100

})

$form.Topmost = $true
$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()

Can you help me ?


问:
Serve external static content as homepage
I'm facing a problem (sure, that's why I'm here) while trying to use an external static content (generated by Gatsby & Strapi) as my JSF application welcome page on a Wildfly-17 server (reacheable as myapp.com or myapp.com/).

Here's my configuration in standalone.xml:

```<code><server name="default-server">
            <http-listener name="default" socket-binding="http" max-post-size="308248576" redirect-socket="https" enable-http2="true"/>
            <https-listener name="https" socket-binding="https" max-post-size="308248576" security-realm="ApplicationRealm" enable-http2="true"/>
            <host name="default-host" alias="localhost">
                <location name="/" handler="welcome-content"/>
                <http-invoker security-realm="ApplicationRealm"/>
            </host>
        </server>
        <servlet-container name="default">
            <jsp-config/>
            <websockets/>
        </servlet-container>
        <handlers>
            <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
        </handlers>
</code>```

You may see that's the welcome content file is the actual wildfly default welcome file because the gatsby + strapi implementation is not finished yet by my co-worker so I'm doing my tests on this file.

My web.xml configuration:

```<code><filter>
    <filter-name>secure</filter-name>
    <filter-class>fr.assistance.filter.SessionFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>secure</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

This file previously contained the welcome-file-list block:

```<code><welcome-file-list>
        <welcome-file>/login.xhtml</welcome-file>
    </welcome-file-list>
</code>```

But how can I target a external file here ?

As you, there's a filter class which is the following:

```<code>@Override
    public void doFilter(
            ServletRequest request, ServletResponse response,
            FilterChain chain
    )
    {
        try
        {

            HttpServletRequest reqt = (HttpServletRequest) request;
            HttpServletResponse resp = (HttpServletResponse) response;
            HttpSession ses = reqt.getSession(false);
            String reqURI = reqt.getRequestURI();

            // Allow jsf.js ressources (auto-generated js script for mojara events) to be loaded instead of resulting in redirect
            if ((reqURI.contains(".xhtml") || reqURI.equals("/")) && !reqURI.contains(ResourceHandler.RESOURCE_IDENTIFIER))
            {
                String lRegex = "^.*\\/((login|reset-password|inscription|contact|register-adherent|register-password)\\.xhtml)?(\\?.*|\\;.*)?";
                if ((ses == null || ses.getAttribute("username") == null))
                {
                    if (reqt.getQueryString() != null)
                    {
                        reqt.getSession().setAttribute("sharedFile", reqt.getQueryString());
                    }
                    if (Pattern.compile(lRegex).matcher(reqURI).matches() || reqURI.equals("/"))
                        chain.doFilter(request, response);
                    else resp.sendRedirect(reqt.getContextPath() + "/login.xhtml");
                } else
                {
                    this.mUserManager.updateSession((Integer) ses.getAttribute(SessionBean.USER_SESSION_ATTRIBUTE_NAME));
                    if (Pattern.compile(lRegex).matcher(reqURI).matches())
                        resp.sendRedirect(reqt.getContextPath() + "/secure/home.xhtml");
                    else chain.doFilter(request, response);
                }
            } else
            {
                chain.doFilter(request, response);
            }
        } catch (Exception e)
        {
            LogManager.getLogger("HDS").error(e, e.getCause());
        }
    }
</code>```

In debug mode, I checked that my request on myapp.com was passing by my filter which does and correctly reach and passed this condition:

if (Pattern.compile(lRegex).matcher(reqURI).matches() ||
reqURI.equals("/"))

But then I'm not reaching the welcome file content but a blank error page instead which the only content is "Forbidden".

All access granted controls are done manully inside app workflow.

Does this mean wildfly does not have access to it's own welcome content file ? Or is It just not reaching the file ?

I hope you'll understand what I said as I'm not english native speaker but this is my question:

How to make Wildfly serve external html page generated by gatsby / strapi as my jsf application home page ?

Also, you'll considare that I already checked many documentations from Jboss, Wildfly and JSF such as many online ressources but they doesn't help me solve my problem.

I may haven't fully understand one of them or missed a good ressource, so please just redirect me to these so I can understand and try them.

Have a good day.

Body:
I'm facing a problem (sure, that's why I'm here) while trying to use an external static content (generated by Gatsby & Strapi) as my JSF application welcome page on a Wildfly-17 server (reacheable as myapp.com or myapp.com/).

Here's my configuration in standalone.xml:

<server name="default-server">
            <http-listener name="default" socket-binding="http" max-post-size="308248576" redirect-socket="https" enable-http2="true"/>
            <https-listener name="https" socket-binding="https" max-post-size="308248576" security-realm="ApplicationRealm" enable-http2="true"/>
            <host name="default-host" alias="localhost">
                <location name="/" handler="welcome-content"/>
                <http-invoker security-realm="ApplicationRealm"/>
            </host>
        </server>
        <servlet-container name="default">
            <jsp-config/>
            <websockets/>
        </servlet-container>
        <handlers>
            <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
        </handlers>

You may see that's the welcome content file is the actual wildfly default welcome file because the gatsby + strapi implementation is not finished yet by my co-worker so I'm doing my tests on this file.

My web.xml configuration:

<filter>
    <filter-name>secure</filter-name>
    <filter-class>fr.assistance.filter.SessionFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>secure</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

This file previously contained the welcome-file-list block:

<welcome-file-list>
        <welcome-file>/login.xhtml</welcome-file>
    </welcome-file-list>

But how can I target a external file here ?

As you, there's a filter class which is the following:

@Override
    public void doFilter(
            ServletRequest request, ServletResponse response,
            FilterChain chain
    )
    {
        try
        {

            HttpServletRequest reqt = (HttpServletRequest) request;
            HttpServletResponse resp = (HttpServletResponse) response;
            HttpSession ses = reqt.getSession(false);
            String reqURI = reqt.getRequestURI();

            // Allow jsf.js ressources (auto-generated js script for mojara events) to be loaded instead of resulting in redirect
            if ((reqURI.contains(".xhtml") || reqURI.equals("/")) && !reqURI.contains(ResourceHandler.RESOURCE_IDENTIFIER))
            {
                String lRegex = "^.*\\/((login|reset-password|inscription|contact|register-adherent|register-password)\\.xhtml)?(\\?.*|\\;.*)?";
                if ((ses == null || ses.getAttribute("username") == null))
                {
                    if (reqt.getQueryString() != null)
                    {
                        reqt.getSession().setAttribute("sharedFile", reqt.getQueryString());
                    }
                    if (Pattern.compile(lRegex).matcher(reqURI).matches() || reqURI.equals("/"))
                        chain.doFilter(request, response);
                    else resp.sendRedirect(reqt.getContextPath() + "/login.xhtml");
                } else
                {
                    this.mUserManager.updateSession((Integer) ses.getAttribute(SessionBean.USER_SESSION_ATTRIBUTE_NAME));
                    if (Pattern.compile(lRegex).matcher(reqURI).matches())
                        resp.sendRedirect(reqt.getContextPath() + "/secure/home.xhtml");
                    else chain.doFilter(request, response);
                }
            } else
            {
                chain.doFilter(request, response);
            }
        } catch (Exception e)
        {
            LogManager.getLogger("HDS").error(e, e.getCause());
        }
    }

In debug mode, I checked that my request on myapp.com was passing by my filter which does and correctly reach and passed this condition:

if (Pattern.compile(lRegex).matcher(reqURI).matches() ||
reqURI.equals("/"))

But then I'm not reaching the welcome file content but a blank error page instead which the only content is "Forbidden".

All access granted controls are done manully inside app workflow.

Does this mean wildfly does not have access to it's own welcome content file ? Or is It just not reaching the file ?

I hope you'll understand what I said as I'm not english native speaker but this is my question:

How to make Wildfly serve external html page generated by gatsby / strapi as my jsf application home page ?

Also, you'll considare that I already checked many documentations from Jboss, Wildfly and JSF such as many online ressources but they doesn't help me solve my problem.

I may haven't fully understand one of them or missed a good ressource, so please just redirect me to these so I can understand and try them.

Have a good day.


问:
Counting the number of hits in database using Django
Is it possible to count or return the number of hits, instead of the number of items in database table using Django queryset?
For example, if the database table has a text column with two rows:

1, "Hi I am the first one. I am not the last one"

2, "Hi again. I am the second one."

I want the result of Object.filter(text__regex=rf"one") to be three rows, not two because I have two "one" words in the first row.

"Hi I am the first one. I am not the last one"

"Hi I am the first one. I am not the last one"

"Hi again. I am the second one."


问:
Google sign on not working other than landing page
I implemented a Google sign-on button on landing page of the Angular application. I am able to login via Google and the API returns email and id of the logged in user. I am trying to move the sign-on button to inner page which redirects from landing page. But same code not working in the inner page.

Can anyone help me to figure out the issue? The HTML and TypeScript codes are given below.

```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>addScript()

  {

    (<any>window).onGoogleLibraryLoad = () => {

      console.log('Google\'s One-tap sign in script loaded!');

      // @ts-ignore

      google.accounts.id.initialize({

        client_id: '********',

        // callback: this.handleCredentialResponse.bind(this), // Whatever function you want to trigger...

        callback: data => this.handleCredentialResponse(data),

        auto_select: false,

        cancel_on_tap_outside: false,

        login_uri: "http://localhost",

        allowed_parent_origin: 'http://localhost'

      });

        (<any>window).google.accounts.id.prompt((notification: PromptMomentNotification) => {

          console.log('Google prompt event triggered...');

          // alert('bbb')

          if (notification.getDismissedReason() === 'credential_returned') {

            this.ngZone.run(() => {

              // this.router.navigate(['myapp/somewhere'], { replaceUrl: true });

              console.log('credential_returned!');

            });

            // console.log('credentials returned');

          }

        });

      // }

    };

  }</code>```

Body:
I implemented a Google sign-on button on landing page of the Angular application. I am able to login via Google and the API returns email and id of the logged in user. I am trying to move the sign-on button to inner page which redirects from landing page. But same code not working in the inner page.

Can anyone help me to figure out the issue? The HTML and TypeScript codes are given below.

addScript()

  {

    (<any>window).onGoogleLibraryLoad = () => {

      console.log('Google\'s One-tap sign in script loaded!');

      // @ts-ignore

      google.accounts.id.initialize({

        client_id: '********',

        // callback: this.handleCredentialResponse.bind(this), // Whatever function you want to trigger...

        callback: data => this.handleCredentialResponse(data),

        auto_select: false,

        cancel_on_tap_outside: false,

        login_uri: "http://localhost",

        allowed_parent_origin: 'http://localhost'

      });

        (<any>window).google.accounts.id.prompt((notification: PromptMomentNotification) => {

          console.log('Google prompt event triggered...');

          // alert('bbb')

          if (notification.getDismissedReason() === 'credential_returned') {

            this.ngZone.run(() => {

              // this.router.navigate(['myapp/somewhere'], { replaceUrl: true });

              console.log('credential_returned!');

            });

            // console.log('credentials returned');

          }

        });

      // }

    };

  }


问:
Multiple plots in on figure updating in real time
Problem description:
I want to plot incoming current-voltage data from multiple sweeps in one figure in real time. like shown in the picture:
example data

Since the amount of data can grow very quickly (thousands of curves with thousands single data points), my idea was to plot every single graph directly into an image with fixed x- and y-axis.

I've tried it with the PIL library by hand but I wonder if there is a better way or library to solve this.
Here's my very simple plotting class without any labels and ticks:

```<code>import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageDraw
import math

class Plotter:
    def __init__(self):
        self.img = Image.new("RGB", (800, 600))
        self.draw = ImageDraw.Draw(self.img)
        self.last_point = (0,0)
        self.first = True
        self.plot_area = (50, 50, 700, 500)
        self.xlim = (0, 100)
        self.ylim = (-1, 1)

    def plot(self, x, y, color):
        self.first = True
        for i in range(len(x)):
            if abs(x[i]) == 0.0:
                x[i] = 1e-16
            if abs(y[i]) == 0.0:
                y[i] = 1e-16
            self.plot_point(abs(x[i]),abs(y[i]), color)

        self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM)

    def plot_point(self, x, y, color):
        index_x = self.plot_area[0] + self.normalize(x, self.xlim) * self.plot_area[2]
        index_y = self.plot_area[1] + self.normalize(y, self.ylim, True) * self.plot_area[3]

        if self.is_in_plot_area(index_x, index_y):

            line = [self.last_point, (index_x, index_y)]

            if not self.first:
                self.draw.line(line, fill=color, width=0)
            else:
                self.first = False
            self.last_point = (index_x, index_y)

    def update(self):
        self.img.show()

    def show(self):
        self.img.show()

    def normalize(self, val, limits, log=False):
        if log:
            scale = math.log(limits[1], 10) - math.log(limits[0], 10)
            return (math.log(val,10) - math.log(limits[0],10)) / scale
        else:
            scale = limits[1] - limits[0]
            return (val - limits[0]) / scale

    def is_in_plot_area(self, index_x, index_y):
        if index_x < self.plot_area[0]:
            return False
        if index_x >= self.plot_area[0] + self.plot_area[2]:
            return False
        if index_y < self.plot_area[1]:
            return False
        if index_y >= self.plot_area[1] + self.plot_area[3]:
            return False
        return True
</code>```

Another idea was to save the plot as a png-file with matplotlib and set it as background image for the next  incoming sweep. It looks nice, but it's too slow.

```<code>import numpy as np
import matplotlib.pyplot as plt
import random
import time

class Plotter:

    def __init__(self):
        self.image_path = "plot.png"
        self.fig, self.ax = plt.subplots()
        # self.ax.set_ylim(-1, 1)
        self.x_limit = (0, 10)
        self.y_limit = (0, 10)
        self.ax1 = self.fig.add_axes([0, 0, 1, 1], zorder=1)
        plt.ion()
        self.x = []
        self.y = []
        self.first = True

    def set_limits(self, x_limit, y_limit):
        self.x_limit = x_limit
        self.y_limit = y_limit

    def plot(self, x, y, color='blue'):
        self.ax.set_yscale('log')
        self.ax.set_xlim(self.x_limit)
        self.ax.set_ylim(self.y_limit)
        self.ax.plot(x, np.abs(y), color=color)

    def show(self):
        #plt.show()
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()

    def save_plot(self):
        self.fig.savefig(self.image_path, transparent=True)

    def load_plot(self):
        img = plt.imread(self.image_path)
        self.ax1.imshow(img)
        self.ax1.axis('off')

    def refresh_figure(self):
        self.ax.cla()
        self.ax1.cla()

    def update(self, x, y, load=True, color='blue'):
        if load:
            self.refresh_figure()
            self.load_plot()
        self.plot(x, y, color)
        self.save_plot()

    def run(self):
        if len(self.x) and len(self.y):
            self.update(self.x[0], self.y[0], not self.first)
            self.x.pop(0)
            self.y.pop(0)
            self.first = False

    def push_data(self, x, y):
        self.x.append(x[:])
        self.y.append(y[:])

p = Plotter()
p.set_limits((0, 10), (1, 1000))

end = False
t0 = time.time()
t = t0
p.save_plot()
p.fig.show()
p.fig.canvas.draw()

while not end:
    if time.time() - t > 1.0:
        x = np.linspace(0, 10, 100)
        # y = np.abs(np.exp(-0.5 * (x + 0.5 * random.random())) * np.sin(x + 0.5 * random.random()))
        y = np.exp(0.5*x) + 100 * random.random()
        p.push_data(x, y)
        t = time.time()
        print("in")
    p.run()
    p.show()
    if time.time()-t0 > 10:
        end = True
input()

</code>```

Any ideas?

Body:
Problem description:
I want to plot incoming current-voltage data from multiple sweeps in one figure in real time. like shown in the picture:
example data

Since the amount of data can grow very quickly (thousands of curves with thousands single data points), my idea was to plot every single graph directly into an image with fixed x- and y-axis.

I've tried it with the PIL library by hand but I wonder if there is a better way or library to solve this.
Here's my very simple plotting class without any labels and ticks:

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageDraw
import math

class Plotter:
    def __init__(self):
        self.img = Image.new("RGB", (800, 600))
        self.draw = ImageDraw.Draw(self.img)
        self.last_point = (0,0)
        self.first = True
        self.plot_area = (50, 50, 700, 500)
        self.xlim = (0, 100)
        self.ylim = (-1, 1)

    def plot(self, x, y, color):
        self.first = True
        for i in range(len(x)):
            if abs(x[i]) == 0.0:
                x[i] = 1e-16
            if abs(y[i]) == 0.0:
                y[i] = 1e-16
            self.plot_point(abs(x[i]),abs(y[i]), color)

        self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM)

    def plot_point(self, x, y, color):
        index_x = self.plot_area[0] + self.normalize(x, self.xlim) * self.plot_area[2]
        index_y = self.plot_area[1] + self.normalize(y, self.ylim, True) * self.plot_area[3]

        if self.is_in_plot_area(index_x, index_y):

            line = [self.last_point, (index_x, index_y)]

            if not self.first:
                self.draw.line(line, fill=color, width=0)
            else:
                self.first = False
            self.last_point = (index_x, index_y)

    def update(self):
        self.img.show()

    def show(self):
        self.img.show()

    def normalize(self, val, limits, log=False):
        if log:
            scale = math.log(limits[1], 10) - math.log(limits[0], 10)
            return (math.log(val,10) - math.log(limits[0],10)) / scale
        else:
            scale = limits[1] - limits[0]
            return (val - limits[0]) / scale

    def is_in_plot_area(self, index_x, index_y):
        if index_x < self.plot_area[0]:
            return False
        if index_x >= self.plot_area[0] + self.plot_area[2]:
            return False
        if index_y < self.plot_area[1]:
            return False
        if index_y >= self.plot_area[1] + self.plot_area[3]:
            return False
        return True

Another idea was to save the plot as a png-file with matplotlib and set it as background image for the next  incoming sweep. It looks nice, but it's too slow.

import numpy as np
import matplotlib.pyplot as plt
import random
import time

class Plotter:

    def __init__(self):
        self.image_path = "plot.png"
        self.fig, self.ax = plt.subplots()
        # self.ax.set_ylim(-1, 1)
        self.x_limit = (0, 10)
        self.y_limit = (0, 10)
        self.ax1 = self.fig.add_axes([0, 0, 1, 1], zorder=1)
        plt.ion()
        self.x = []
        self.y = []
        self.first = True

    def set_limits(self, x_limit, y_limit):
        self.x_limit = x_limit
        self.y_limit = y_limit

    def plot(self, x, y, color='blue'):
        self.ax.set_yscale('log')
        self.ax.set_xlim(self.x_limit)
        self.ax.set_ylim(self.y_limit)
        self.ax.plot(x, np.abs(y), color=color)

    def show(self):
        #plt.show()
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()

    def save_plot(self):
        self.fig.savefig(self.image_path, transparent=True)

    def load_plot(self):
        img = plt.imread(self.image_path)
        self.ax1.imshow(img)
        self.ax1.axis('off')

    def refresh_figure(self):
        self.ax.cla()
        self.ax1.cla()

    def update(self, x, y, load=True, color='blue'):
        if load:
            self.refresh_figure()
            self.load_plot()
        self.plot(x, y, color)
        self.save_plot()

    def run(self):
        if len(self.x) and len(self.y):
            self.update(self.x[0], self.y[0], not self.first)
            self.x.pop(0)
            self.y.pop(0)
            self.first = False

    def push_data(self, x, y):
        self.x.append(x[:])
        self.y.append(y[:])

p = Plotter()
p.set_limits((0, 10), (1, 1000))

end = False
t0 = time.time()
t = t0
p.save_plot()
p.fig.show()
p.fig.canvas.draw()

while not end:
    if time.time() - t > 1.0:
        x = np.linspace(0, 10, 100)
        # y = np.abs(np.exp(-0.5 * (x + 0.5 * random.random())) * np.sin(x + 0.5 * random.random()))
        y = np.exp(0.5*x) + 100 * random.random()
        p.push_data(x, y)
        t = time.time()
        print("in")
    p.run()
    p.show()
    if time.time()-t0 > 10:
        end = True
input()

Any ideas?


问:
how to do bitmap construction in js
On the backend, I have a function which expects uint256 argument. Though, it's not normal uint. uint256 means it's 32 bytes long(256 bits). The idea behind is I there're 256 people and for each person, I need to pass whether they attended the concert or not. Though, I can't pass the array. uint256 is the only way I need this solved. So, every bit in uint256 would say 1 or 0(1 meaning person attended).

On the backend, I do something like this:

for(let i = 0; i < 256; i++) {
   let attended = num & 1 << i;
}
```

num is uint256 that function expects.

What I can't figure out is how to construct this uint256 is javascript.

Doing the 1111000111000 If I type this 256 times, It would end up bigger than 256bits. So looking for ideas..

Title: how to do bitmap construction in js

Body:
On the backend, I have a function which expects uint256 argument. Though, it's not normal uint. uint256 means it's 32 bytes long(256 bits). The idea behind is I there're 256 people and for each person, I need to pass whether they attended the concert or not. Though, I can't pass the array. uint256 is the only way I need this solved. So, every bit in uint256 would say 1 or 0(1 meaning person attended).

On the backend, I do something like this:

for(let i = 0; i < 256; i++) {
   let attended = num & 1 << i;
}

num is uint256 that function expects.

What I can't figure out is how to construct this uint256 is javascript.

Doing the 1111000111000 If I type this 256 times, It would end up bigger than 256bits. So looking for ideas..


问:
Why doesn't Sign-in with Google require a Client Secret?
I'm following Google's new Sign In Button documentation. For the verification on server, they ask us to run the following code.(for NodeJS)

const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
  const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
      // Or, if multiple clients access the backend:
      //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
  });
  const payload = ticket.getPayload();
  const userid = payload['sub'];
  // If request specified a G Suite domain:
  // const domain = payload['hd'];
}
verify().catch(console.error);
```
<p>I find it weird that at no point, we specified the Client Secret, which was shown in our Google Developer console along with the Client ID.</p>
<p>Since the Client ID is also embedded in the frontend website code, anybody could essentially copy it, and start their own server on my credentials right?</p>
<p>When I looked at the <code>Oauth2Client2</code> constructor, it has the Client Secret as the second parameter, however it's optional.</p>
```(alias) new OAuth2Client(clientId?: string | undefined, clientSecret?: string | undefined, redirectUri?: string | undefined): OAuth2Client (+1 overload)
```

What is the logic behind this? Is not using the Client Secret on my server (as shown in the docs), creating a vulnerability on my site?

Body:
I'm following Google's new Sign In Button documentation. For the verification on server, they ask us to run the following code.(for NodeJS)

const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
  const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
      // Or, if multiple clients access the backend:
      //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
  });
  const payload = ticket.getPayload();
  const userid = payload['sub'];
  // If request specified a G Suite domain:
  // const domain = payload['hd'];
}
verify().catch(console.error);

I find it weird that at no point, we specified the Client Secret, which was shown in our Google Developer console along with the Client ID.

Since the Client ID is also embedded in the frontend website code, anybody could essentially copy it, and start their own server on my credentials right?

When I looked at the Oauth2Client2 constructor, it has the Client Secret as the second parameter, however it's optional.

(alias) new OAuth2Client(clientId?: string | undefined, clientSecret?: string | undefined, redirectUri?: string | undefined): OAuth2Client (+1 overload)

What is the logic behind this? Is not using the Client Secret on my server (as shown in the docs), creating a vulnerability on my site?


问:
How implement ReceiveCustomWebHooks in WebApi.Core
I am following this link to implement webhooks between two systems with WebApi

https://devblogs.microsoft.com/dotnet/sending-webhooks-with-asp-net-webhooks-preview/

The problem is that the receiving API is developed in .NET Core and I don't see the support for config.InitializeReceiveCustomWebHooks(); inside the startup.

The code in .Net Framework is like this:

```<code>public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // Load Web API controllers and Azure Storage store
    config.InitializeCustomWebHooks();
    config.InitializeCustomWebHooksAzureStorage();
    config.InitializeCustomWebHooksApis();
    config.InitializeReceiveCustomWebHooks();
}
</code>```

Does anyone know how to implement it in .NET Core?

Thank you

Body:
I am following this link to implement webhooks between two systems with WebApi

https://devblogs.microsoft.com/dotnet/sending-webhooks-with-asp-net-webhooks-preview/

The problem is that the receiving API is developed in .NET Core and I don't see the support for config.InitializeReceiveCustomWebHooks(); inside the startup.

The code in .Net Framework is like this:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // Load Web API controllers and Azure Storage store
    config.InitializeCustomWebHooks();
    config.InitializeCustomWebHooksAzureStorage();
    config.InitializeCustomWebHooksApis();
    config.InitializeReceiveCustomWebHooks();
}

Does anyone know how to implement it in .NET Core?

Thank you


问:
Symfony Doctrine entities disable Proxy (while Xdebugging)
Whenever I use Xdebug to debug variables I see alot of Proxies\__CG__\ classes instead of my real classes. Is there any way to disable these? I want to eager load everything instead of lazy loading.

These Proxy (entity) classes have every property null, only the id is filled. This is not nice when using Xdebug to debug values from variables.

When I'm using the 'Evaluate Expression' tool, I can do $entity->getSomeEntity()->getName(); and it's not empty (lazy loading?). But without evaluating the expression, the value is null.

Tried to change Doctrine configuration auto_generate_proxy_classes to 0 but weirdly this doesn't seem to change a thing.


问:
Edit the description box of Ant Design Basic Sunburst Plot
I am trying to edit the description box of an Ant Design basic sunburst plot to include more information from my data. Being new to coding, I am struggling to use the website information, and have tried the following answer given to me by chat GPT but this hasn't worked:

```<code>const data = [
  {
    name: 'Parent',
    children: [
      {
        name: 'Child 1',
        value: 100,
        additionalValue: 20
      },
      {
        name: 'Child 2',
        value: 60,
        additionalValue: 10
      },
      {
        name: 'Child 3',
        value: 30,
        additionalValue: 5
      }
    ]
  }
];

const tooltip = {
  formatter: (name, value, additionalValue) => {
    return `Name: ${name} <br/> Value: ${value} <br/> Additional Value: ${additionalValue}`;
  }
};

const config3 = {
  data: data,
  innerRadius: 0.3,
  tooltip: tooltip,
  interactions: [
    {
      type: 'element-active',
    },
  ],
}

const SunburstPlot = () => {
  return <Sunburst {...config3} />;
};
</code>```

Ie nothing seems to turn up at all.

Is anyone able to suggest how I can get additional value to show up in my description box as well as my value?

Thanks!

Body:
I am trying to edit the description box of an Ant Design basic sunburst plot to include more information from my data. Being new to coding, I am struggling to use the website information, and have tried the following answer given to me by chat GPT but this hasn't worked:

const data = [
  {
    name: 'Parent',
    children: [
      {
        name: 'Child 1',
        value: 100,
        additionalValue: 20
      },
      {
        name: 'Child 2',
        value: 60,
        additionalValue: 10
      },
      {
        name: 'Child 3',
        value: 30,
        additionalValue: 5
      }
    ]
  }
];

const tooltip = {
  formatter: (name, value, additionalValue) => {
    return `Name: ${name} <br/> Value: ${value} <br/> Additional Value: ${additionalValue}`;
  }
};

const config3 = {
  data: data,
  innerRadius: 0.3,
  tooltip: tooltip,
  interactions: [
    {
      type: 'element-active',
    },
  ],
}

const SunburstPlot = () => {
  return <Sunburst {...config3} />;
};

Ie nothing seems to turn up at all.

Is anyone able to suggest how I can get additional value to show up in my description box as well as my value?

Thanks!


问:
3Scale custom policy matching path param in the URI
I am using 3Scale's edge limiting policy to impose rate limiting for my API and having the following endpoints

```<code>GET /v1/user
GET /v1/user/{name}
GET /v1/user/{name}/{organization}
</code>```

For the first endpoint configuring rate limit is pretty straight forward

```<code>Algorithm Used: Fixed Window Limiters
Window Size: 60 seconds
Operations:
  op: ==
  right: /v1/user
  right_type: plain text
  left: {{ uri }}
  left_type: liquid
</code>```

But for the next two endpoints, I am unable to set the right value of the Operations since these contains path parameters.

How to define the path parameter in the URL in Operations?

Body:
I am using 3Scale's edge limiting policy to impose rate limiting for my API and having the following endpoints

GET /v1/user
GET /v1/user/{name}
GET /v1/user/{name}/{organization}

For the first endpoint configuring rate limit is pretty straight forward

Algorithm Used: Fixed Window Limiters
Window Size: 60 seconds
Operations:
  op: ==
  right: /v1/user
  right_type: plain text
  left: {{ uri }}
  left_type: liquid

But for the next two endpoints, I am unable to set the right value of the Operations since these contains path parameters.

How to define the path parameter in the URL in Operations?


问:
ConcurrentModificationException when removing more than 2 sublists from a collection in Kotlin
I am making a quiz app and would like the user to have some control over what questions are asked. I have done this by adding checkboxes that, if unchecked, remove the questions in the sublist correlating to that category.

I used this code:

```<code>if (!cb1) questions.removeAll(cb1questions.toSet())
if (!cb2) questions.removeAll(cb2questions.toSet())
</code>```

which works when there are only two checkboxes but comes up with the error ConcurrentModificationException if I add a third checkbox like this:

```<code>if (!cb1) questions.removeAll(cb1questions.toSet())
if (!cb2) questions.removeAll(cb2questions.toSet())
if (!cb3) questions.removeAll(cb3questions.toSet())
</code>```

I have only seen this error in relation to loops before so aren't sure how to solve it within this context.
Any help in solving this problem would be greatly appreciated.

Body:
I am making a quiz app and would like the user to have some control over what questions are asked. I have done this by adding checkboxes that, if unchecked, remove the questions in the sublist correlating to that category.

I used this code:

if (!cb1) questions.removeAll(cb1questions.toSet())
if (!cb2) questions.removeAll(cb2questions.toSet())

which works when there are only two checkboxes but comes up with the error ConcurrentModificationException if I add a third checkbox like this:

if (!cb1) questions.removeAll(cb1questions.toSet())
if (!cb2) questions.removeAll(cb2questions.toSet())
if (!cb3) questions.removeAll(cb3questions.toSet())

I have only seen this error in relation to loops before so aren't sure how to solve it within this context.
Any help in solving this problem would be greatly appreciated.


问:
Script to "click" on a drawn button on a Google Sheet for Analytics v4 Report?
I have a Google Sheets Apps Script question related to an extension I use. We use Google Analytics v4 for data on our app's activity, and I pull daily numbers on that into a Google Sheet to create reports. Google made a free extension to do that for GA v3, but not for v4, and so I have to use an extension called Google Analytics Connector by SyncWith in order to get the data. It gives you 35 free report refreshes per month before it locks down and makes you pay to get any more, so I have to be very specific about only refreshing once a day (my company is not going to pay for a monthly plan from them). SyncWith has an automatic daily refresh setting, but the problem is it doesn't let you pick the specific time that it refreshes.

SyncWith makes spreadsheets for its reports, and originally had a TRUE/FALSE checkbox at the top. When you checked it, it would execute their code to pull in the new day's numbers from GA v4. I made this simple Apps Script that would simply check the box and uncheck it to get the report to run, and had a trigger set to run the Apps Script between 6 and 7 a.m.

```<code>function AppDataRefresh() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('App Daily data');
  sheet.getRange('A1').setValue("TRUE");
  sheet.getRange('A1').setValue("FALSE");
}
</code>```

However, now SyncWith has replaced its checkboxes with a new panel at the top that uses drawn buttons. This is what it looks like: https://freeimage.host/i/H7FfrEF

So, unfortunately, there's no longer any checkbox, meaning I can't get this report generated automatically at a specific time with my original Apps Script fix. So, my question is, based on the above picture, is there any kind of an Apps Script that can simulate clicking on a drawn button in a Google Sheet, based on cell location? For example, is there an Apps Script that could click "Refresh" by just clicking on cell D1?

Body:
I have a Google Sheets Apps Script question related to an extension I use. We use Google Analytics v4 for data on our app's activity, and I pull daily numbers on that into a Google Sheet to create reports. Google made a free extension to do that for GA v3, but not for v4, and so I have to use an extension called Google Analytics Connector by SyncWith in order to get the data. It gives you 35 free report refreshes per month before it locks down and makes you pay to get any more, so I have to be very specific about only refreshing once a day (my company is not going to pay for a monthly plan from them). SyncWith has an automatic daily refresh setting, but the problem is it doesn't let you pick the specific time that it refreshes.

SyncWith makes spreadsheets for its reports, and originally had a TRUE/FALSE checkbox at the top. When you checked it, it would execute their code to pull in the new day's numbers from GA v4. I made this simple Apps Script that would simply check the box and uncheck it to get the report to run, and had a trigger set to run the Apps Script between 6 and 7 a.m.

function AppDataRefresh() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('App Daily data');
  sheet.getRange('A1').setValue("TRUE");
  sheet.getRange('A1').setValue("FALSE");
}

However, now SyncWith has replaced its checkboxes with a new panel at the top that uses drawn buttons. This is what it looks like: https://freeimage.host/i/H7FfrEF

So, unfortunately, there's no longer any checkbox, meaning I can't get this report generated automatically at a specific time with my original Apps Script fix. So, my question is, based on the above picture, is there any kind of an Apps Script that can simulate clicking on a drawn button in a Google Sheet, based on cell location? For example, is there an Apps Script that could click "Refresh" by just clicking on cell D1?


问:
Cannot get Android Emulator to Work on M1 Mac (RN Project)
It feels like I've tried every solution on the internet, and nothing seems to work. My emulators start, but they refuse to connect to my project no matter what I do. The build works and is currently in the Google Play Store, so it WORKS on Google, it's just my M1 is not letting me test on my machine in the most infuriating of ways.
my bash_profile looks like this...

```<code>export ANDROID_HOME="$PATH:/Users/**********/Library/Android/sdk
export PATH="$PATH:/Users/**********/Library/Android/sdk/platform-tools"
export PATH="$PATH:/ANDROID_HOME/emulator
export PATH="$PATH:/ANDROID_HOME/tools
export PATH="$PATH:/ANDROID_HOME/tools/bin
export PATH="$PATH:/ANDROID_HOME/platform-tools
</code>```

and my project's local.properties looks like this...

```<code>sdk.dir=/Users/**********/Library/Android/sdk

</code>```

and I have Android Studio installed and set up. Whenever I run npc react-native run-android I get this error...

```<code>error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
...
...
warn Failed to connect to development server using "adb reverse": spawnSync adb ENOENT
info Starting the app...
error Failed to start the app.
Error: spawnSync adb ENOENT
</code>```

Fine, so if I try to start it via Android Studio, I get this following error...

```<code>Could not connect to development server.

Ensure that Metro is running
</code>```

FINE, so let me spin up the hard downloaded Android Emulator and run it on that. I then get this error...

```<code>Unable to load script. Make sure you're either running Metro or that your bundle 'index.android.bundle` is packaged correctly for release
</code>```

This is where I hit a wall, because I've never touched that file but I've gotten both this and other Android RN projects to run on my machine before. I sincerely have no idea what's going on, does anyone have a direction to point me?

Body:
It feels like I've tried every solution on the internet, and nothing seems to work. My emulators start, but they refuse to connect to my project no matter what I do. The build works and is currently in the Google Play Store, so it WORKS on Google, it's just my M1 is not letting me test on my machine in the most infuriating of ways.
my bash_profile looks like this...

export ANDROID_HOME="$PATH:/Users/**********/Library/Android/sdk
export PATH="$PATH:/Users/**********/Library/Android/sdk/platform-tools"
export PATH="$PATH:/ANDROID_HOME/emulator
export PATH="$PATH:/ANDROID_HOME/tools
export PATH="$PATH:/ANDROID_HOME/tools/bin
export PATH="$PATH:/ANDROID_HOME/platform-tools

and my project's local.properties looks like this...

sdk.dir=/Users/**********/Library/Android/sdk

and I have Android Studio installed and set up. Whenever I run npc react-native run-android I get this error...

error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
...
...
warn Failed to connect to development server using "adb reverse": spawnSync adb ENOENT
info Starting the app...
error Failed to start the app.
Error: spawnSync adb ENOENT

Fine, so if I try to start it via Android Studio, I get this following error...

Could not connect to development server.

Ensure that Metro is running

FINE, so let me spin up the hard downloaded Android Emulator and run it on that. I then get this error...

Unable to load script. Make sure you're either running Metro or that your bundle 'index.android.bundle` is packaged correctly for release

This is where I hit a wall, because I've never touched that file but I've gotten both this and other Android RN projects to run on my machine before. I sincerely have no idea what's going on, does anyone have a direction to point me?


问:
I can't delete instant games in the background of FB developers
We have shut down the instant game service, but cannot delete it in the developer background.
No matter what method we use, we can't delete the background instant game.
This problem caused us to fail to pass the login policy review, and the game login service was closed.

We replaced 4 computers to delete the instant game, but all failed.
We confirm that CHROME has been updated to the latest version and deleted after temporary storage,
but it is still invalid.
For the first time, we used EDGE to log in to the FB developers to delete the instant game, but also encountered a failure.
We have attached a new film to you.
I hope you can help us delete the instant game


问:
Multiple API calls competing for one atomic db action
I have an API to send message and create contact as such: when it is called and detected no such contact in the database, it first creates a contact, then send out the message.

The problem is: when multiple API calls are issued concurrently (sending message to the same receiver), multiple contacts of the same receiver will be created. (race condition)

Say A, B and C are issued concurrently, when A is still createing a contact, B and C already detect there is no such contact in the contact list, hence B and C would also create the contact.

Any clue on how to solve such race condition? I used azure sql database, .net6, EF core framework, etc.

I tried using Semaphore, but Semaphore is intraprocess, multiple API calls are interprocess.

I also tried using named mutex

```<code>            _mutex = new Mutex(false, "Global\\MyUniqueMutexName", out bool hasInitialOwnership);
            try
            {
                if (!hasInitialOwnership)
                {
                    _mutex.WaitOne();
                }
                res = await CriticalAction(...params...);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                if (hasInitialOwnership)
                {
                    _mutex.ReleaseMutex();
                }
            }
</code>```

but doesn't work

Body:
I have an API to send message and create contact as such: when it is called and detected no such contact in the database, it first creates a contact, then send out the message.

The problem is: when multiple API calls are issued concurrently (sending message to the same receiver), multiple contacts of the same receiver will be created. (race condition)

Say A, B and C are issued concurrently, when A is still createing a contact, B and C already detect there is no such contact in the contact list, hence B and C would also create the contact.

Any clue on how to solve such race condition? I used azure sql database, .net6, EF core framework, etc.

I tried using Semaphore, but Semaphore is intraprocess, multiple API calls are interprocess.

I also tried using named mutex

            _mutex = new Mutex(false, "Global\\MyUniqueMutexName", out bool hasInitialOwnership);
            try
            {
                if (!hasInitialOwnership)
                {
                    _mutex.WaitOne();
                }
                res = await CriticalAction(...params...);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                if (hasInitialOwnership)
                {
                    _mutex.ReleaseMutex();
                }
            }

but doesn't work


问:
Important measures to assess the relationship between two variables
What other measures are important for assessing the relationship between two variables apart from correlation, determination and significance?</p>


问:
Vitest visualViewport is not defined
I am writing one of my first vitest and my code does a test of the visualViewport when the component is mounted. When I run the test, it fails because the visualViewport is not defined. How would I go about having this defined when the test runs?

```<code>onMounted(() => {
  if (visualViewport.width > 1024) {
    options.isDesktop = true;
  }

  visualViewport.addEventListener('resize', ({target}) => {
    if (target.width > 1024) {
      options.isDesktop = true;
    } else {
      options.isDesktop = false;
    }
  });
});
</code>```
```<code>ReferenceError: visualViewport is not defined
                                                                                │ ❯ src/scripts/search-and-filter/App.vue:22:3
                                                                                │     20|
                                                                                │     21| onMounted(() => {
                                                                                │     22|   if (visualViewport.width > 1024) {
                                                                                │       |   ^
                                                                                │     23|     options.isDesktop = true;
                                                                                │     24|   }
</code>```

Let me know if more information is needed and I will add it. Thank you for your help.

jsdom is being used so I don't think that is the problem.

Title: Vitest visualViewport is not defined

Body:
I am writing one of my first vitest and my code does a test of the visualViewport when the component is mounted. When I run the test, it fails because the visualViewport is not defined. How would I go about having this defined when the test runs?

onMounted(() => {
  if (visualViewport.width > 1024) {
    options.isDesktop = true;
  }

  visualViewport.addEventListener('resize', ({target}) => {
    if (target.width > 1024) {
      options.isDesktop = true;
    } else {
      options.isDesktop = false;
    }
  });
});

ReferenceError: visualViewport is not defined
                                                                                │ ❯ src/scripts/search-and-filter/App.vue:22:3
                                                                                │     20|
                                                                                │     21| onMounted(() => {
                                                                                │     22|   if (visualViewport.width > 1024) {
                                                                                │       |   ^
                                                                                │     23|     options.isDesktop = true;
                                                                                │     24|   }

Let me know if more information is needed and I will add it. Thank you for your help.

jsdom is being used so I don't think that is the problem.


问:
docker compose otel collector permission denied in retrieving configuration file
I have my file docker-compose.yml :

```<code>otel-collector:
    image: otel/opentelemetry-collector
    command: ["--config=/etc/otel-collector-config.yaml"]
    volumes:
      - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
    ports:
      - "1888:1888"   # pprof extension
      - "8888:8888"   # Prometheus metrics exposed by the collector
      - "8889:8889"   # Prometheus exporter metrics
      - "13133:13133" # health_check extension
      - "4317:4317"   # OTLP gRPC receiver
      - "4318:4318"   # OTLP http receiver
      - "55679:55679" # zpages extension
</code>```

I see this error after execution of docker compose up:

otel-collector  | Error: failed to get config: cannot resolve the
configuration: cannot retrieve the configuration: unable to read the
file file:/etc/otel-collector-config.yaml: open
/etc/otel-collector-config.yaml: permission denied otel-collector  |
2022/01/09 11:15:47 collector server run finished with error: failed
to get config: cannot resolve the configuration: cannot retrieve the
configuration: unable to read the file
file:/etc/otel-collector-config.yaml: open
/etc/otel-collector-config.yaml: permission denied

How can I solve it?

Body:
I have my file docker-compose.yml :

otel-collector:
    image: otel/opentelemetry-collector
    command: ["--config=/etc/otel-collector-config.yaml"]
    volumes:
      - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
    ports:
      - "1888:1888"   # pprof extension
      - "8888:8888"   # Prometheus metrics exposed by the collector
      - "8889:8889"   # Prometheus exporter metrics
      - "13133:13133" # health_check extension
      - "4317:4317"   # OTLP gRPC receiver
      - "4318:4318"   # OTLP http receiver
      - "55679:55679" # zpages extension

I see this error after execution of docker compose up:

otel-collector  | Error: failed to get config: cannot resolve the
configuration: cannot retrieve the configuration: unable to read the
file file:/etc/otel-collector-config.yaml: open
/etc/otel-collector-config.yaml: permission denied otel-collector  |
2022/01/09 11:15:47 collector server run finished with error: failed
to get config: cannot resolve the configuration: cannot retrieve the
configuration: unable to read the file
file:/etc/otel-collector-config.yaml: open
/etc/otel-collector-config.yaml: permission denied

How can I solve it?


问:
WPF How to visit each child of a UniformGrid
The UserControl is composed of two labels and one Textbox.Some relative codes are below

```<code>public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
        DataContext = this;
    }
    public string Title { get; set; }
    public string Company {get; set; }
    public TextBox TrueText;
    private void Input_Loaded(object sender, RoutedEventArgs e)
    {
        this.TrueText = sender as TextBox;
    }
}
</code>```

xaml

```<code><Viewbox >
    <Grid  HorizontalAlignment="Left" VerticalAlignment="Center">
        <Label Content="{Binding Title}" HorizontalAlignment="Left"  Height="20" VerticalAlignment="Center" Padding="0,0,0,0" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Width="180"/>
        <TextBox Margin="180,0,0,0" Name="Input"  Loaded="Input_Loaded" Controls:TextBoxHelper.Watermark="待输入" Controls:TextBoxHelper.ClearTextButton="True" Padding="0,0,0,0" VerticalContentAlignment="Center" MinHeight="0" HorizontalAlignment="Left" VerticalAlignment="Center" Width="120" Height="18"/>
        <Label Content="{Binding Company}" HorizontalAlignment="Left" Height="18" Margin="300,1,0,0" VerticalAlignment="Top" Width="50" Padding="0,0,0,0" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
    </Grid>
</Viewbox>
</code>```

Then I want to get the Input in TextBox of each UserControl.But I can't get the children of the UniformGrid.

I have tried to use GetChildObject, but in this way I can't access his related properties
This is my wrong codeyour text

```<code>IEnumerable<UserControl1> list = (IEnumerable<UserControl1>)Grid1.GetChildObjects();
int i = 1;
double[] num = { 0 };
foreach (var u in list)
{
    i++;
    num[i] = Convert.ToDouble(u.TrueText.Text);
}

</code>```

Any solution will be truly appreciated

Body:
The UserControl is composed of two labels and one Textbox.Some relative codes are below

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
        DataContext = this;
    }
    public string Title { get; set; }
    public string Company {get; set; }
    public TextBox TrueText;
    private void Input_Loaded(object sender, RoutedEventArgs e)
    {
        this.TrueText = sender as TextBox;
    }
}

xaml

<Viewbox >
    <Grid  HorizontalAlignment="Left" VerticalAlignment="Center">

        <TextBox Margin="180,0,0,0" Name="Input"  Loaded="Input_Loaded" Controls:TextBoxHelper.Watermark="待输入" Controls:TextBoxHelper.ClearTextButton="True" Padding="0,0,0,0" VerticalContentAlignment="Center" MinHeight="0" HorizontalAlignment="Left" VerticalAlignment="Center" Width="120" Height="18"/>

    </Grid>
</Viewbox>

Then I want to get the Input in TextBox of each UserControl.But I can't get the children of the UniformGrid.

I have tried to use GetChildObject, but in this way I can't access his related properties
This is my wrong codeyour text

IEnumerable<UserControl1> list = (IEnumerable<UserControl1>)Grid1.GetChildObjects();
int i = 1;
double[] num = { 0 };
foreach (var u in list)
{
    i++;
    num[i] = Convert.ToDouble(u.TrueText.Text);
}

Any solution will be truly appreciated


问:
How to make a hierarchical structure of folds/collapses in the text editor?
I want to format this:

```<code># 1 =====
tibble()
## 1.1 ====
tibble()
### 1.1.1 ====
tibble()
# 2 =====
tibble()
## 2.1 ====
tibble()
### 2.1.1 ====
tibble()
</code>```

If I collapse # 1 and # 2, I would like to get:

```<code># 1 =====
# 2 =====
</code>```

But instead I just get this:

```<code># 1 =====
## 1.1 ====
tibble()
### 1.1.1 ====
tibble()
# 2 =====
## 2.1 ====
tibble()
### 2.1.1 ====
tibble()
</code>```

Is it possible to have multiple "levels" of folding in rstudio?

My purpose is this: I have some long code with multiple folds inside and it has to be repeated 32 times. I would like to be able to fold all those 32 instances without losing the foldability of the inside contents of each of the 32 instances.

Body:
I want to format this:

# 1 =====
tibble()
## 1.1 ====
tibble()
### 1.1.1 ====
tibble()
# 2 =====
tibble()
## 2.1 ====
tibble()
### 2.1.1 ====
tibble()

If I collapse # 1 and # 2, I would like to get:

# 1 =====
# 2 =====

But instead I just get this:

# 1 =====
## 1.1 ====
tibble()
### 1.1.1 ====
tibble()
# 2 =====
## 2.1 ====
tibble()
### 2.1.1 ====
tibble()

Is it possible to have multiple "levels" of folding in rstudio?

My purpose is this: I have some long code with multiple folds inside and it has to be repeated 32 times. I would like to be able to fold all those 32 instances without losing the foldability of the inside contents of each of the 32 instances.


问:
How can I apply Data validation and conditional formatting on the drop down list?
I want to add data validation for a list of dates (Jan 1st 2023 to December 31st 2023) to a column. When the user click on the drop down. I want them to see the Current day date highlighted. How can i do this?

I have added the necessary data validation rule to the column. Clicking on the date column, I want it to do something like what I have in the picture below.

That blue color is not an highlight. It's my cursor


问:
Run next.js app with npm start, NOT next start (i.e. without next installed)?
Is it possible to run a next.js app without having next installed on the target system? I made a basic next app on my dev computer that has next installed, but the system I want to run it on only has node/npm, not next. When I try to start the app with "npm start" or "npm run dev" it just triggers the start script in package.json that calls next start, giving me 'next' is not recognized as an internal or external command, operable program or batch file.

I tried modifying package.json so instead of start => next start, it would call npm start, but it gave me an error about missing dependencies. Maybe I need to tweak this more, or maybe there is some way of building a next app with npm-pack-all that does not require next?


问:
Decimal values are not accepting in input type Number. Why?
I have below input type in asp.net core application

```<code><form asp-controller="~/Controllers/GroupLengthConverterTools/MToCmController">
    <p>Provide the meter value below</p>
    <span asp-validation-for="InputValue" class="text-danger"></span>
    <input type="number" asp-for="InputValue" id="numberCounter" step="any" onClick="this.setSelectionRange(0, this.value.length)" /><br />

    <br />
    <input asp-action="Index" type="submit" value="Convert to Centimeters" class="btn btn-primary" />
    <input asp-action="Clear" type="submit" value="Clear" class="btn btn-outline-primary" />
    <br />
</form>
</code>```

Here is the controller class

```<code>  [HttpPost]
        [Route("meter-to-cm")]
        public IActionResult Index(LengthConverterBassModel model)
        {
            model.SetToolModelData(model, toolUniqueIdentifier);
            ModelState["InputText"].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid;

            if (!ModelState.IsValid)
            {
                return View(FullPathsOfViews.MToCmLengthConverter, model);
            }

            model.OutPutText = string.Format("{0}cm - {1}", LengthConverters.ConvertMToCm(model.InputValue);

            return View(FullPathsOfViews.MToCmLengthConverter, model);
        }
</code>```

After I type 4.56 into the box it says an error

The value '4.56' is not valid for InputValue.

Below is the Model class

```<code>[Required(ErrorMessage = "Provide a value")]
public decimal? InputValue { get; set; }
</code>```

Note that this was not happening in localhost. Only when I deployed this. Both regions are set to the United states.

When this occures even the public IActionResult Index(LengthConverterBassModel model) method is not firing. It stops at the presentation layer.
Whats wrong here?

Body:
I have below input type in asp.net core application

<form asp-controller="~/Controllers/GroupLengthConverterTools/MToCmController">

Provide the meter value below

    <input type="number" asp-for="InputValue" id="numberCounter" step="any" onClick="this.setSelectionRange(0, this.value.length)" />

    <input asp-action="Index" type="submit" value="Convert to Centimeters" class="btn btn-primary" />
    <input asp-action="Clear" type="submit" value="Clear" class="btn btn-outline-primary" />

</form>

Here is the controller class

  [HttpPost]
        [Route("meter-to-cm")]
        public IActionResult Index(LengthConverterBassModel model)
        {
            model.SetToolModelData(model, toolUniqueIdentifier);
            ModelState["InputText"].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid;

            if (!ModelState.IsValid)
            {
                return View(FullPathsOfViews.MToCmLengthConverter, model);
            }

            model.OutPutText = string.Format("{0}cm - {1}", LengthConverters.ConvertMToCm(model.InputValue);

            return View(FullPathsOfViews.MToCmLengthConverter, model);
        }

After I type 4.56 into the box it says an error

The value '4.56' is not valid for InputValue.

Below is the Model class

[Required(ErrorMessage = "Provide a value")]
public decimal? InputValue { get; set; }

Note that this was not happening in localhost. Only when I deployed this. Both regions are set to the United states.

When this occures even the public IActionResult Index(LengthConverterBassModel model) method is not firing. It stops at the presentation layer.
Whats wrong here?