问:
Running multithreading get request in parallel with timeout using Python
I am new to Python and I have a task which I want to simulate stress on the server by multiplying different requests to the server.

The tool should have these options (getting from CLI\terminal input):

Number of concurrent requests (how many threads to run in parallel)

Number of domain to run on

Timeout - time in seconds to finish the stress process.

At the end of the stress process I want to print results that contains the following fields:

Number of total requests: how many requests was in total

Error rate: how many requests failed in total

Total time - how long did the whole operation take.

The tool should handle “KeyboardInterrupt” and print the information output until that moment.

This is what I coded so far:

```<code>    import sys
import time
import keyboard
from pynput.keyboard import Listener
import requests
import threading
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

timeout=0
URLS = ['bankofamerica.com', 'google.com', 'cnn.com', 'google.com', 'cnn.com', 'youtube.com']
header = {
    "Host": "candidate-eval.securingsam.com",
    "Authorization": "Token I_am_under_stress_when_I_test",
    "User-Agent": "Tester"
}

def on_press(key):
    if keyboard.is_pressed("q"):
        sys.exit()

def scanner():
    site = URLS.pop()
    while True:
        print(f"Running: {site}")
        res = requests.get(f"https://candidate-eval.securingsam.com/domain/ranking/{site}", verify=False, headers=header)
        print(res.json())
        time.sleep(1)

def input_generator():
    concurrent_requests = input("Enter number of concurrent requests --> How many threads to run in parallel?>>")
    number_of_domains = input("Enter number of domains --> How many domains to run in parallel (max: 5000 domains>>")
    timeout = input("Enter Timeout: time in seconds to finish the stress process>>")

    print(concurrent_requests)
    print(number_of_domains)
    print(timeout)

def runner(timeout=None):
    threads = []
    for _ in range(len(URLS)):
        threads.append(threading.Thread(target=scanner))
    list(map(lambda t: t.start(), threads))
    list(map(lambda t: t.join(), threads))
    if timeout:
        time.sleep(timeout)
        sys.exit()

def killer():
    with Listener(on_press=on_press) as listener:
        listener.join()

if __name__ == '__main__':
    input_generator()
    threading.Thread(target=killer).start()
    runner()
</code>```

I want to be able to set a timeout so the run would stop if it reach timeout,
I want to be able to collect all the results (in correlation to the task requirements)
I want to add another option where I can finish the run using “KeyboardInterrupt” and calculate how much time the program ran.

Body:
I am new to Python and I have a task which I want to simulate stress on the server by multiplying different requests to the server.

The tool should have these options (getting from CLI\terminal input):

Number of concurrent requests (how many threads to run in parallel)

Number of domain to run on

Timeout - time in seconds to finish the stress process.

At the end of the stress process I want to print results that contains the following fields:

Number of total requests: how many requests was in total

Error rate: how many requests failed in total

Total time - how long did the whole operation take.

The tool should handle “KeyboardInterrupt” and print the information output until that moment.

This is what I coded so far:

    import sys
import time
import keyboard
from pynput.keyboard import Listener
import requests
import threading
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

timeout=0
URLS = ['bankofamerica.com', 'google.com', 'cnn.com', 'google.com', 'cnn.com', 'youtube.com']
header = {
    "Host": "candidate-eval.securingsam.com",
    "Authorization": "Token I_am_under_stress_when_I_test",
    "User-Agent": "Tester"
}

def on_press(key):
    if keyboard.is_pressed("q"):
        sys.exit()

def scanner():
    site = URLS.pop()
    while True:
        print(f"Running: {site}")
        res = requests.get(f"https://candidate-eval.securingsam.com/domain/ranking/{site}", verify=False, headers=header)
        print(res.json())
        time.sleep(1)

def input_generator():
    concurrent_requests = input("Enter number of concurrent requests --> How many threads to run in parallel?>>")
    number_of_domains = input("Enter number of domains --> How many domains to run in parallel (max: 5000 domains>>")
    timeout = input("Enter Timeout: time in seconds to finish the stress process>>")

    print(concurrent_requests)
    print(number_of_domains)
    print(timeout)

def runner(timeout=None):
    threads = []
    for _ in range(len(URLS)):
        threads.append(threading.Thread(target=scanner))
    list(map(lambda t: t.start(), threads))
    list(map(lambda t: t.join(), threads))
    if timeout:
        time.sleep(timeout)
        sys.exit()

def killer():
    with Listener(on_press=on_press) as listener:
        listener.join()

if __name__ == '__main__':
    input_generator()
    threading.Thread(target=killer).start()
    runner()

I want to be able to set a timeout so the run would stop if it reach timeout,
I want to be able to collect all the results (in correlation to the task requirements)
I want to add another option where I can finish the run using “KeyboardInterrupt” and calculate how much time the program ran.


来源: stackexchange

问:
How to make a meshfree density plot
I solved an equation obtaining a probability density (over the two dimensional Euclidean space), with a meshfree method. I now want to plot the results. Hence, I have a point cloud in dimension 2, that is an array X of N elements each of dimension 2. I have a probability density f over X.

I want a 3d plot, where the z variable is the height of the probability density function, and where the height is higher, I want the color of the density to be brighter.

So far I can only make a scatter plot. I am not sure how to 'connect the dots'.

The above current plot is generated from

```<code>fig2, ax = plt.subplots(subplot_kw=dict(projection="3d"))
    #Labeling etc:
    ax.set_title("graph title")
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_zlabel("density")
    ax.set_xlim(left=-0.3, right=0.3)
    ax.set_ylim(bottom=-0.3, top=0.3)
    #do the plot:
    ax.scatter(x,y,z,c=z,cmap="hot")
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to make a meshfree density plot

Body:
I solved an equation obtaining a probability density (over the two dimensional Euclidean space), with a meshfree method. I now want to plot the results. Hence, I have a point cloud in dimension 2, that is an array X of N elements each of dimension 2. I have a probability density f over X.

I want a 3d plot, where the z variable is the height of the probability density function, and where the height is higher, I want the color of the density to be brighter.

So far I can only make a scatter plot. I am not sure how to 'connect the dots'.

The above current plot is generated from

fig2, ax = plt.subplots(subplot_kw=dict(projection="3d"))
    #Labeling etc:
    ax.set_title("graph title")
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_zlabel("density")
    ax.set_xlim(left=-0.3, right=0.3)
    ax.set_ylim(bottom=-0.3, top=0.3)
    #do the plot:
    ax.scatter(x,y,z,c=z,cmap="hot")


问:
React hooks - Redux - When I change an object, all other objects with the same name in the state change
Example me i on changed the NotificationGroup array in the reducer, what happend is that the same array in the selectedgroup object change either.

I tryed to use slice to create an other object in the state like group but didn't work.


问:
How to select paste option when we use open context menu keywork (Robotframework(python-3.8)- selenium)
How to select paste option when we use open context menu  keywork (Robotframework(python-3.8)- selenium)  Please guide ....screenshot where i trigger open context menu  keyword

i have no clue how to click on paste option after run open context menu keywork in robotframework.. Paste from clipboard keyword also not working even after library mentioned in setting (RPA.Desktop)
press keys/press key not working for this site
Site reference (https://www.w3schools.com/html/tryit.asp?filename=tryhtml_default_default)
Expected: -  data should be entered/pasted in html body[here i want to paste data or enter data - curser(|)
(https://i.stack.imgur.com/JnAb6.png)


问:
React Native Modalize Styling problem (webview/modal)
enter image description here

Hello friends, I would like to know how I solve this problem of stylization of Modal / Modalize.. well, it does not fully occupy the width of the screen, these side spacings are appearing. Does anyone have any notion of how to do this? I'm new to React Native, I'm learning from the expo

```<code>import * as React from 'react';
import { useState, useRef, useCallback } from 'react';
import {
    Text, StyleSheet,
    KeyboardAvoidingView, ScrollView, Image,
    TextInput, TouchableOpacity, View, SafeAreaView,
    Linking, Modal
} from 'react-native';
import { CheckBox } from 'react-native-elements';
import { Ionicons } from 'react-native-vector-icons'
import { useNavigation } from '@react-navigation/native';
import { Modalize } from 'react-native-modalize';
import WebViewModalProvider, { WebViewModal } from
    'react-native-webview-modal';

const Login = () => {
    const [input, setInput] = useState('');
    const [hidePass, setHidePass] = useState(true);
    const [ischecked1, setIschecked1] = useState(true);
    const [visible, setVisible] = useState(false);

    const modalizeRef = useRef(null);

    function onOpen() {
        if (modalizeRef.current) modalizeRef.current.open();
   }

    return (

        <KeyboardAvoidingView
            style={styles.container}
        >
            <SafeAreaView>
                <Modalize
                    ref={modalizeRef}
                    snapPoint={500}
                //handlePosition="inside"
                >
                    <View style={{
                        height: "100%",
                        justifyContent: 'center'
                    }}>
                        <WebViewModalProvider>
                            <View style={{height: 500 }}>
                                <SafeAreaView />
                                <WebViewModal
                                    visible={true}
                                    source={{ uri: "https://account.activedirectory.windowsazure.com/ChangePassword.aspx" }}
                                    style={{ margin: 10 }}
                                />
                            </View>
                        </WebViewModalProvider>
                    </View>
                </Modalize>

                <ScrollView>

                    <Image

                        style={styles.logo}
                    />
                    <Text style={styles.helloText}>
                        Olá de novo !
                    </Text>
                    <Text style={styles.welcomeText}>
                        Bem-vindo(a) de volta,
                        sentimos sua falta!
                    </Text>

                    <TextInput
                        style={styles.inputArea}
                        placeholder="Digite o e-mail"
                    />
                    <TextInput
                        style={styles.inputArea}
                        placeholder="Senha"
                        value={input}
                        onChangeText={(texto) => setInput(texto)}
                        secureTextEntry={hidePass}
                    />
                    <TouchableOpacity style={styles.eye} onPress={() => setHidePass(!hidePass)}>
                        <Ionicons name={hidePass ? 'eye' : 'eye-off'}
                            color="#A0D800" size={25}
                        />
                    </TouchableOpacity>
                    <View style={styles.checkBoxStyle}>
                        <CheckBox
                            left
                            size={18}
                            checkedColor='#A0D800'
                            value={ischecked1}
                            checked={ischecked1}
                            onPress={() => setIschecked1(!ischecked1)}

                            containerStyle={{
                                backgroundColor: "transparent",
                                borderColor: "transparent", marginRight: 0
                            }}
                        />
                        <TouchableOpacity onPress={() => setIschecked1(true)}>
                            <Text style={styles.Connected}>
                                Manter-se conectado
                            </Text>
                        </TouchableOpacity>

                        <TouchableOpacity //onPress={() =>
                            // Linking.openURL('https://account.activedirectory.windowsazure.com/ChangePassword.aspx')}
                            onPress={onOpen}>
                            <Text style={styles.forgotPassword}>
                                Esqueci minha senha
                            </Text>
                        </TouchableOpacity>
                    </View>

                    <TouchableOpacity
                        style={styles.botao}

                    >
                        <Text style={styles.botaoText}>Entrar</Text>
                    </TouchableOpacity>

                </ScrollView>
            </SafeAreaView>
        </KeyboardAvoidingView>
    );

}
const styles = StyleSheet.create({
    container: {

        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff'
    },
    logo: {
        marginTop: 50,
        marginBottom: 80,
        width: 150,
        height: 40,

    },
    inputArea: {
        marginTop: 30,
        padding: 15,
        height: 60,
        width: 370,
        borderColor: '#808080',
        borderWidth: 1,
        backgroundColor: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
        borderRadius: 15
    },
    botao: {
        width: 350,
        height: 60,
        backgroundColor: '#000000',
        marginTop: 35,
        marginLeft: 8,
        borderRadius: 15,
        alignItems: 'center',
        justifyContent: 'center',

    },
    botaoText: {
        fontSize: 15,
        fontWeight: 'bold',
        color: '#fff'
    },
    helloText: {
        fontSize: 40,
        fontWeight: 'bold',
        marginTop: 15,
        color: '#000000',
        marginEnd: 120,

    },
    welcomeText: {
        fontSize: 16,
        marginTop: 10,
        marginEnd: 35,
        marginVertical: 10,
        color: '#808080',
    },
    forgotPassword: {
        textDecorationLine: 'underline',
        fontWeight: 'bold',
        marginTop: 15,
        marginBottom: 15,
        marginLeft: 30,
        fontSize: 12
    },
    Connected: {
        textDecorationLine: 'underline',
        fontWeight: 'bold',
        marginTop: 15,
        fontSize: 12,
        marginRight: 55,
        marginLeft: -5
    },
    checkBoxStyle: {
        marginTop: 15,
        flexDirection: 'row',
        marginStart: -10
    },
    eye: {
        alignSelf: 'flex-end',
        bottom: 42,
        right: 40
    }
})

export default Login;
</code>```

Body:
enter image description here

Hello friends, I would like to know how I solve this problem of stylization of Modal / Modalize.. well, it does not fully occupy the width of the screen, these side spacings are appearing. Does anyone have any notion of how to do this? I'm new to React Native, I'm learning from the expo

import * as React from 'react';
import { useState, useRef, useCallback } from 'react';
import {
    Text, StyleSheet,
    KeyboardAvoidingView, ScrollView, Image,
    TextInput, TouchableOpacity, View, SafeAreaView,
    Linking, Modal
} from 'react-native';
import { CheckBox } from 'react-native-elements';
import { Ionicons } from 'react-native-vector-icons'
import { useNavigation } from '@react-navigation/native';
import { Modalize } from 'react-native-modalize';
import WebViewModalProvider, { WebViewModal } from
    'react-native-webview-modal';

const Login = () => {
    const [input, setInput] = useState('');
    const [hidePass, setHidePass] = useState(true);
    const [ischecked1, setIschecked1] = useState(true);
    const [visible, setVisible] = useState(false);

    const modalizeRef = useRef(null);

    function onOpen() {
        if (modalizeRef.current) modalizeRef.current.open();
   }

    return (

        <KeyboardAvoidingView
            style={styles.container}
        >
            <SafeAreaView>
                <Modalize
                    ref={modalizeRef}
                    snapPoint={500}
                //handlePosition="inside"
                >
                    <View style={{
                        height: "100%",
                        justifyContent: 'center'
                    }}>
                        <WebViewModalProvider>
                            <View style={{height: 500 }}>
                                <SafeAreaView />
                                <WebViewModal
                                    visible={true}
                                    source={{ uri: "https://account.activedirectory.windowsazure.com/ChangePassword.aspx" }}
                                    style={{ margin: 10 }}
                                />
                            </View>
                        </WebViewModalProvider>
                    </View>
                </Modalize>

                <ScrollView>

                    <Image

                        style={styles.logo}
                    />
                    <Text style={styles.helloText}>
                        Olá de novo !
                    </Text>
                    <Text style={styles.welcomeText}>
                        Bem-vindo(a) de volta,
                        sentimos sua falta!
                    </Text>

                    <TextInput
                        style={styles.inputArea}
                        placeholder="Digite o e-mail"
                    />
                    <TextInput
                        style={styles.inputArea}
                        placeholder="Senha"
                        value={input}
                        onChangeText={(texto) => setInput(texto)}
                        secureTextEntry={hidePass}
                    />
                    <TouchableOpacity style={styles.eye} onPress={() => setHidePass(!hidePass)}>
                        <Ionicons name={hidePass ? 'eye' : 'eye-off'}
                            color="#A0D800" size={25}
                        />
                    </TouchableOpacity>
                    <View style={styles.checkBoxStyle}>
                        <CheckBox
                            left
                            size={18}
                            checkedColor='#A0D800'
                            value={ischecked1}
                            checked={ischecked1}
                            onPress={() => setIschecked1(!ischecked1)}

                            containerStyle={{
                                backgroundColor: "transparent",
                                borderColor: "transparent", marginRight: 0
                            }}
                        />
                        <TouchableOpacity onPress={() => setIschecked1(true)}>
                            <Text style={styles.Connected}>
                                Manter-se conectado
                            </Text>
                        </TouchableOpacity>

                        <TouchableOpacity //onPress={() =>
                            // Linking.openURL('https://account.activedirectory.windowsazure.com/ChangePassword.aspx')}
                            onPress={onOpen}>
                            <Text style={styles.forgotPassword}>
                                Esqueci minha senha
                            </Text>
                        </TouchableOpacity>
                    </View>

                    <TouchableOpacity
                        style={styles.botao}

                    >
                        <Text style={styles.botaoText}>Entrar</Text>
                    </TouchableOpacity>

                </ScrollView>
            </SafeAreaView>
        </KeyboardAvoidingView>
    );

}
const styles = StyleSheet.create({
    container: {

        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff'
    },
    logo: {
        marginTop: 50,
        marginBottom: 80,
        width: 150,
        height: 40,

    },
    inputArea: {
        marginTop: 30,
        padding: 15,
        height: 60,
        width: 370,
        borderColor: '#808080',
        borderWidth: 1,
        backgroundColor: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
        borderRadius: 15
    },
    botao: {
        width: 350,
        height: 60,
        backgroundColor: '#000000',
        marginTop: 35,
        marginLeft: 8,
        borderRadius: 15,
        alignItems: 'center',
        justifyContent: 'center',

    },
    botaoText: {
        fontSize: 15,
        fontWeight: 'bold',
        color: '#fff'
    },
    helloText: {
        fontSize: 40,
        fontWeight: 'bold',
        marginTop: 15,
        color: '#000000',
        marginEnd: 120,

    },
    welcomeText: {
        fontSize: 16,
        marginTop: 10,
        marginEnd: 35,
        marginVertical: 10,
        color: '#808080',
    },
    forgotPassword: {
        textDecorationLine: 'underline',
        fontWeight: 'bold',
        marginTop: 15,
        marginBottom: 15,
        marginLeft: 30,
        fontSize: 12
    },
    Connected: {
        textDecorationLine: 'underline',
        fontWeight: 'bold',
        marginTop: 15,
        fontSize: 12,
        marginRight: 55,
        marginLeft: -5
    },
    checkBoxStyle: {
        marginTop: 15,
        flexDirection: 'row',
        marginStart: -10
    },
    eye: {
        alignSelf: 'flex-end',
        bottom: 42,
        right: 40
    }
})

export default Login;


问:
Storybook: Global styles applied to whole iframe
I am importing global styles in preview.js.

import '!style-loader!css-loader!sass-loader!../global.sass'

Unfortunately they get applied to the whole iframe's content.

Is there any way to import global styles which will not style storybooks elements but only my components?

I added the styles import to the angular.json. But this will result into the same problem.


问:
Can't complete a PUT request from a different Modal using fetch with React
I am trying to create a CRUD app using springboot and React.
I have a problem with the PUT request to update a record from MySQL database.
With postman, when I send A PUT request like this:

```<code>{
        "id": 456,
        "name": "CHANGED_NAME",
        "surname": "SURNAME",
        "gender": "M",
        "birthdate": "1995-12-07",
        "work_address": "address1",
        "home_address": "address2"
    },
to http://localhost:8080/users/456
</code>```

it works fine.

I have the info in a ListUsers.jsx file and I am trying to make the update from another jsx, e.x. UpdateUser.jsx sending as default values the current values when calling the UpdateUser Component.

Inside the UpdateUser.jsx I have a Form and onSubmit I call the handleSumbit method to make the PUT request, but nothing happens.

```<code>handleSubmit(event){
        event.preventDefault();
        fetch('http://localhost:8080/users/'+event.target.userId.value,{
          method:'PUT',
          headers:{
            'Accept':'application/json',
            'Content-Type':'application/json'
          },
          body:JSON.stringify({
            id: event.target.userId.value,
            name: event.target.name.value,
            surname: event.target.surname.value,
            gender: event.target.gender.value,
            birthdate: event.target.birthdate.value,
            work_address: event.target.work_address.value,
            home_address: event.target.home_address.value,

          })
        })
        .then(res=> res.json())
        .then((result)=>
        {
            //alert(result);
            this.setState({user_added:true});
        },
        (error)=>{
          //alert('Failed')
          this.setState({user_added:true});
        }
        );
        event.target.reset();
    }
</code>```

Body:
I am trying to create a CRUD app using springboot and React.
I have a problem with the PUT request to update a record from MySQL database.
With postman, when I send A PUT request like this:

{
        "id": 456,
        "name": "CHANGED_NAME",
        "surname": "SURNAME",
        "gender": "M",
        "birthdate": "1995-12-07",
        "work_address": "address1",
        "home_address": "address2"
    },
to http://localhost:8080/users/456

it works fine.

I have the info in a ListUsers.jsx file and I am trying to make the update from another jsx, e.x. UpdateUser.jsx sending as default values the current values when calling the UpdateUser Component.

Inside the UpdateUser.jsx I have a Form and onSubmit I call the handleSumbit method to make the PUT request, but nothing happens.

handleSubmit(event){
        event.preventDefault();
        fetch('http://localhost:8080/users/'+event.target.userId.value,{
          method:'PUT',
          headers:{
            'Accept':'application/json',
            'Content-Type':'application/json'
          },
          body:JSON.stringify({
            id: event.target.userId.value,
            name: event.target.name.value,
            surname: event.target.surname.value,
            gender: event.target.gender.value,
            birthdate: event.target.birthdate.value,
            work_address: event.target.work_address.value,
            home_address: event.target.home_address.value,

          })
        })
        .then(res=> res.json())
        .then((result)=>
        {
            //alert(result);
            this.setState({user_added:true});
        },
        (error)=>{
          //alert('Failed')
          this.setState({user_added:true});
        }
        );
        event.target.reset();
    }


问:
WebpackChunkName-Placeholder not working in laravel-mix?
I have this dynamically import (mix 6.0.6):

```<code>import(/* webpackChunkName: "request_user_profile_settings_[index]" */ '../modals/userprofilesettings.js')
</code>```

which gives me a file named:

```<code>js/request_user_profile_settings_[index].js

</code>```

I expected the placeholder [index] to be replaced with some number. What's going on?

Body:
I have this dynamically import (mix 6.0.6):

import(/* webpackChunkName: "request_user_profile_settings_[index]" */ '../modals/userprofilesettings.js')

which gives me a file named:

js/request_user_profile_settings_[index].js

I expected the placeholder [index] to be replaced with some number. What's going on?


问:
How to use public RapidApis with Spring boot Rest APIs?
i'm trying to integrate google translation public API with my spring application . I'm expecting a List of languages . I just don't know what type of return type i should choose ?

Google Translation Api

I tried This but it's not the wanted result

Spring Rest Api


问:
React-Hook-Form is showing required type error, even though the field is populated
[![enter image description here][1]][1]

I have a problem on validating three input fields. Two of them are working properly! But the phone number one is showing the required type error even though I populate it.

The code snippet is below:

```<code><Controller
  control={control}
  name='phoneNumber'
  render={({ field }) => (
    <Input {...register("phoneNumber", {
      minLength: { value: 7, message: "mínimo de 7 caracteres" },
      required: { value: true, message: "campo obrigatório" }
      })}
      name="phoneNumber"
      onChange={handlePhoneNumberChange}
      value={inputPhone}
      invalid={errors.phoneNumber && true}
    />
  )}
/>
</code>```

The other two that are working follow this example:

```<code><Controller
  defaultValue=''
  control={control}
  name='confirmPassword'
  render={({ field }) => (
    <Input
      {...register("confirmPassword", { required: true,  minLength: 8 })}
      type='password'
      placeholder='Digitar senha novamente'
      invalid={errors.confirmPassword && true}
      {...field}
    />
  )}
</code>```

Down below is the detailed info about the handlePhoneNumberChange function and the format function. They are there so that I can format the phone number that is populated in the Input field

```<code>export default function FormatPhone() {

  const { register, handleSubmit, control, formState: {errors}} = useForm()

  const [inputPhone, setInputPhone] = React.useState("")
  const [phoneNumberLength, setPhoneNumberLength] = React.useState(0)

    const formatPhoneNumber = (value) => {
        if (!value) return value
        const phoneNumber = value.replace(/[^\d]/g, "")
        const phoneNumberLength = phoneNumber.length
        if (phoneNumberLength < 4) {
          setPhoneNumberLength(phoneNumberLength)
          return phoneNumber
    }
        if (phoneNumberLength > 7) {
          setPhoneNumberLength(phoneNumber)
          return `(${phoneNumber.slice(0, 2)}) ${phoneNumber.slice(
            2,
            7
          )}-${phoneNumber.slice(7, 11)}`
        }
      }
      const handlePhoneNumberChange = (e) => {
        const formattedPhoneNumber = formatPhoneNumber(e.target.value)
        setInputPhone(formattedPhoneNumber)
</code>```

Body:
[![enter image description here][1]][1]

I have a problem on validating three input fields. Two of them are working properly! But the phone number one is showing the required type error even though I populate it.

The code snippet is below:

<Controller
  control={control}
  name='phoneNumber'
  render={({ field }) => (
    <Input {...register("phoneNumber", {
      minLength: { value: 7, message: "mínimo de 7 caracteres" },
      required: { value: true, message: "campo obrigatório" }
      })}
      name="phoneNumber"
      onChange={handlePhoneNumberChange}
      value={inputPhone}
      invalid={errors.phoneNumber && true}
    />
  )}
/>

The other two that are working follow this example:

<Controller
  defaultValue=''
  control={control}
  name='confirmPassword'
  render={({ field }) => (
    <Input
      {...register("confirmPassword", { required: true,  minLength: 8 })}
      type='password'
      placeholder='Digitar senha novamente'
      invalid={errors.confirmPassword && true}
      {...field}
    />
  )}

Down below is the detailed info about the handlePhoneNumberChange function and the format function. They are there so that I can format the phone number that is populated in the Input field

export default function FormatPhone() {

  const { register, handleSubmit, control, formState: {errors}} = useForm()

  const [inputPhone, setInputPhone] = React.useState("")
  const [phoneNumberLength, setPhoneNumberLength] = React.useState(0)

    const formatPhoneNumber = (value) => {
        if (!value) return value
        const phoneNumber = value.replace(/[^\d]/g, "")
        const phoneNumberLength = phoneNumber.length
        if (phoneNumberLength < 4) {
          setPhoneNumberLength(phoneNumberLength)
          return phoneNumber
    }
        if (phoneNumberLength > 7) {
          setPhoneNumberLength(phoneNumber)
          return `(${phoneNumber.slice(0, 2)}) ${phoneNumber.slice(
            2,
            7
          )}-${phoneNumber.slice(7, 11)}`
        }
      }
      const handlePhoneNumberChange = (e) => {
        const formattedPhoneNumber = formatPhoneNumber(e.target.value)
        setInputPhone(formattedPhoneNumber)


问:
Python os.walk returns weirdly formatted root directory
I've written a program which uses tkinter's askdirectory to get a folder and then convert all images into another format. But I've noticed something weird.

The first step the program does is ask for a directory and then use os.walk to create a filelist, which the converter (in this case PILLOW for most images and psd-tools for photoshop images) then takes. This code looks something like this:

```<code>from tkinter import Tk
from tkinter.filedialog import askdirectory
import os

path = askdirectory(title='Select Folder')

all_files=[]
for root, _, files in os.walk(path):
    for f in files:
        all_files.append(os.path.join(root, f))

convert(all_files) #not important here

</code>```

I've written a couple of little scripts that deal with files and paths, so I know how annoying this can be and how allergic some modules react to specific formats for paths. So, when I copy/paste a path into a script, i usually write path = r"path i copied from file explorer" and everything beyond that only happens with os.path.join(), which has worked perfectly until now.

I noticed strange filepaths in my error messages that claimed it couldn't find a file. So I printed my file lists out:

```<code>for line in all_files:
    print(line)
</code>```

And i got this:

```<code>G:/Downloads/New folder (2)\file1.png
G:/Downloads/New folder (2)\file2.png
G:/Downloads/New folder (2)\file3.png
G:/Downloads/New folder (2)\file4.png
...

</code>```

It seems like tkinter formats the string weirdly (one forward slash instead of two backward slashes, which is the case when i copy/paste a dir into a rawString). And os.path.join() cannot understand tkinter paths properly as a result.

But what I don't understand is why it's happening here. Because as far as I see it, os.path.join joins not the input path by tkinter with a filename, but it joins the root provided by os.walk, which should be in a format os.path.join understands, because I never had any problems with it before this.

So my question would either be "How can I reformat the tkinter string, so that it gets properly understood as a directory path by os.path.join and os.walk?" or "Why does os.walk behave like this here and put the wrongly formatted directoy into the root variable?"

(I know i could probably just type path = path.replace("/", "\"), but A) i am not sure if there would be other subtle differences and B) i really am curious why this imo weird thing it happening, so I don't make a similar mistake again)

EDIT (SOLUTION): Thanks to chepners comment, I was able to fix it (they didn't make a proper 'answer', hence why I'm adding this here, so someone with a similar problem doesn't miss the solution). Replacing the line all_files.append(os.path.join(root, f)) by all_files.append(os.path.normpath(os.path.join(root, f))) solved it, since normpath can handle a mixture of / and \. The reason for this can he read in chepners comments, I'm not adding them here.

Body:
I've written a program which uses tkinter's askdirectory to get a folder and then convert all images into another format. But I've noticed something weird.

The first step the program does is ask for a directory and then use os.walk to create a filelist, which the converter (in this case PILLOW for most images and psd-tools for photoshop images) then takes. This code looks something like this:

from tkinter import Tk
from tkinter.filedialog import askdirectory
import os

path = askdirectory(title='Select Folder')

all_files=[]
for root, _, files in os.walk(path):
    for f in files:
        all_files.append(os.path.join(root, f))

convert(all_files) #not important here

I've written a couple of little scripts that deal with files and paths, so I know how annoying this can be and how allergic some modules react to specific formats for paths. So, when I copy/paste a path into a script, i usually write path = r"path i copied from file explorer" and everything beyond that only happens with os.path.join(), which has worked perfectly until now.

I noticed strange filepaths in my error messages that claimed it couldn't find a file. So I printed my file lists out:

for line in all_files:
    print(line)

And i got this:

G:/Downloads/New folder (2)\file1.png
G:/Downloads/New folder (2)\file2.png
G:/Downloads/New folder (2)\file3.png
G:/Downloads/New folder (2)\file4.png
...

It seems like tkinter formats the string weirdly (one forward slash instead of two backward slashes, which is the case when i copy/paste a dir into a rawString). And os.path.join() cannot understand tkinter paths properly as a result.

But what I don't understand is why it's happening here. Because as far as I see it, os.path.join joins not the input path by tkinter with a filename, but it joins the root provided by os.walk, which should be in a format os.path.join understands, because I never had any problems with it before this.

So my question would either be "How can I reformat the tkinter string, so that it gets properly understood as a directory path by os.path.join and os.walk?" or "Why does os.walk behave like this here and put the wrongly formatted directoy into the root variable?"

(I know i could probably just type path = path.replace("/", "\"), but A) i am not sure if there would be other subtle differences and B) i really am curious why this imo weird thing it happening, so I don't make a similar mistake again)

EDIT (SOLUTION): Thanks to chepners comment, I was able to fix it (they didn't make a proper 'answer', hence why I'm adding this here, so someone with a similar problem doesn't miss the solution). Replacing the line all_files.append(os.path.join(root, f)) by all_files.append(os.path.normpath(os.path.join(root, f))) solved it, since normpath can handle a mixture of / and \. The reason for this can he read in chepners comments, I'm not adding them here.


问:
How to pass flag option in CopyHere
I see in this doc (https://learn.microsoft.com/en-us/windows/win32/shell/folder-copyhere
) that we can pass flag to remove this type of modal :

But actually nothing works, the modals don't go away

My code to install font, that I want without alert modal:

```<code>
Set objFSO = CreateObject("Scripting.FileSystemObject")

objStartFolder = CStr(WScript.Arguments.Item(0))
Const FONTS = &H14&

Set objShell = CreateObject("Shell.Application")

Set objFontFolder = objShell.Namespace(FONTS)
Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
For Each objFile in colFiles
    objFontFolder.CopyHere objFile.Path, 16
Next

</code>```

Title: How to pass flag option in CopyHere

Body:
I see in this doc (https://learn.microsoft.com/en-us/windows/win32/shell/folder-copyhere
) that we can pass flag to remove this type of modal :

But actually nothing works, the modals don't go away

My code to install font, that I want without alert modal:

Set objFSO = CreateObject("Scripting.FileSystemObject")

objStartFolder = CStr(WScript.Arguments.Item(0))
Const FONTS = &H14&

Set objShell = CreateObject("Shell.Application")

Set objFontFolder = objShell.Namespace(FONTS)
Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
For Each objFile in colFiles
    objFontFolder.CopyHere objFile.Path, 16
Next


问:
Upgrading spring from 3.0.5.RELEASE to 5.1.8.RELEASE and hibernate from 3.3.1.GA to 5.6.12.Final, getting error "no transaction is in progress""
I am using two dataSource x and y in my project.
and using 2 transactionManager tmx and tmy respectively for that.
Enable synchronization for tmy with SYNCHRONIZATION_ALWAYS and not enable for tmx with
SYNCHRONIZATION_NEVER.

while starting up the server, I am getting below error:

Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress    at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:398)    at org.hibernate.internal.SessionImpl.checkTransactionNeededForUpdateOperation(SessionImpl.java:3558)   at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1444)    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1440)  at org.springframework.orm.hibernate5.SessionFactoryUtils.flush(SessionFactoryUtils.java:147)   at org.springframework.orm.hibernate5.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:95)   at org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:96)     at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:922)  at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:730)    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)

```<code><bean id="baseTm" class="org.springframework.orm.hibernate5.HibernateTransactionManager" abstract="true">
            <property name="defaultTimeout" value="${db.transactiontimeout}" />
            <property name="failEarlyOnGlobalRollbackOnly" value="true"/>
    </bean>

    <bean id="Tmx" parent="baseTm">
        <property name="transactionSynchronizationName" value="SYNCHRONIZATION_NEVER"/>
        <property name="sessionFactory" ref="hibernateTx"/>
    </bean>

    <bean id="Tmy" parent="baseTm">
        <property name="transactionSynchronizationName" value="SYNCHRONIZATION_ALWAYS"/>
        <property name="sessionFactory" ref="hibernateTy"/>
    </bean>

<bean id="abstractHibernate" depends-on="cacheProvider" abstract="true" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
         <property name="hibernateProperties">
            <props>
               <prop key="hibernate.dialect">myProjectCustomizedDialect</prop>
               <prop key="hibernate.cache.provider_class">myProjectCustomizedEhCacheProvider</prop>
               <prop key="hibernate.cache.use_second_level_cache">true</prop>
               <prop key="hibernate.cache.use_query_cache">true</prop>
               <prop key="hibernate.show_sql">false</prop>
               <prop key="hibernate.format_sql">true</prop>
               <prop key="hibernate.generate_statistics">true</prop>
               <prop key="hibernate.connection.isolation">2</prop>
               <prop key="hibernate.cache.use_structured_entries">false</prop>
               <prop key="hibernate.default_batch_fetch_size">16</prop>
               <prop key="hibernate.max_fetch_depth">0</prop>
               <prop key="hibernate.jdbc.batch_size">20</prop>
               <prop key="hibernate.transaction.coordinator_class">jdbc</prop>
               <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
               <prop key="hibernate.cache.ehcache.missing_cache_strategy">create</prop>
            </props>
         </property>
         </bean>
</code>```

I debug the issue:
in SpringSessionSynchronization class -> beforeCommit method ->

Session session = this.getCurrentSession();

after getting above session when we inspect "this.isTransactionInProgress()", it returns false
because of that

if (this.disallowOutOfTransactionUpdateOperations && !this.isTransactionInProgress()) {
throw new TransactionRequiredException(exceptionMessage);
}

above if condition throws "no transaction is in progress"
why this "this.isTransactionInProgress()" status is set-up wrong, it should true instead of false
in SpringSessionSynchronization ?

what configuration I am missing here because before upgradation I was working fine.

Body:
I am using two dataSource x and y in my project.
and using 2 transactionManager tmx and tmy respectively for that.
Enable synchronization for tmy with SYNCHRONIZATION_ALWAYS and not enable for tmx with
SYNCHRONIZATION_NEVER.

while starting up the server, I am getting below error:

Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress    at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:398)    at org.hibernate.internal.SessionImpl.checkTransactionNeededForUpdateOperation(SessionImpl.java:3558)   at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1444)    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1440)  at org.springframework.orm.hibernate5.SessionFactoryUtils.flush(SessionFactoryUtils.java:147)   at org.springframework.orm.hibernate5.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:95)   at org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:96)     at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:922)  at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:730)    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)

<bean id="baseTm" class="org.springframework.orm.hibernate5.HibernateTransactionManager" abstract="true">
            <property name="defaultTimeout" value="${db.transactiontimeout}" />
            <property name="failEarlyOnGlobalRollbackOnly" value="true"/>
    </bean>

    <bean id="Tmx" parent="baseTm">
        <property name="transactionSynchronizationName" value="SYNCHRONIZATION_NEVER"/>
        <property name="sessionFactory" ref="hibernateTx"/>
    </bean>

    <bean id="Tmy" parent="baseTm">
        <property name="transactionSynchronizationName" value="SYNCHRONIZATION_ALWAYS"/>
        <property name="sessionFactory" ref="hibernateTy"/>
    </bean>

<bean id="abstractHibernate" depends-on="cacheProvider" abstract="true" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
         <property name="hibernateProperties">
            <props>
               <prop key="hibernate.dialect">myProjectCustomizedDialect</prop>
               <prop key="hibernate.cache.provider_class">myProjectCustomizedEhCacheProvider</prop>
               <prop key="hibernate.cache.use_second_level_cache">true</prop>
               <prop key="hibernate.cache.use_query_cache">true</prop>
               <prop key="hibernate.show_sql">false</prop>
               <prop key="hibernate.format_sql">true</prop>
               <prop key="hibernate.generate_statistics">true</prop>
               <prop key="hibernate.connection.isolation">2</prop>
               <prop key="hibernate.cache.use_structured_entries">false</prop>
               <prop key="hibernate.default_batch_fetch_size">16</prop>
               <prop key="hibernate.max_fetch_depth">0</prop>
               <prop key="hibernate.jdbc.batch_size">20</prop>
               <prop key="hibernate.transaction.coordinator_class">jdbc</prop>
               <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
               <prop key="hibernate.cache.ehcache.missing_cache_strategy">create</prop>
            </props>
         </property>
         </bean>

I debug the issue:
in SpringSessionSynchronization class -> beforeCommit method ->

Session session = this.getCurrentSession();

after getting above session when we inspect "this.isTransactionInProgress()", it returns false
because of that

if (this.disallowOutOfTransactionUpdateOperations && !this.isTransactionInProgress()) {
throw new TransactionRequiredException(exceptionMessage);
}

above if condition throws "no transaction is in progress"
why this "this.isTransactionInProgress()" status is set-up wrong, it should true instead of false
in SpringSessionSynchronization ?

what configuration I am missing here because before upgradation I was working fine.


问:
Stop pyyaml from putting key values into list, instead put into a dictionary
Here is a yaml file I have:

```<code>animal:
    - dog:
        - noise:
            - "woof"
        - food:
            - "dog food"
        - house:
            - "dog house"
    - cat:
        - noise:
            - "meow"
        - food:
            - "cat food"
        - home:
            - "cat tree"
</code>```

Here is the code I use to convert yaml to dictionary:

```<code>import yaml, pprint
from pathlib import Path

def gen_vars(conf_file)
    conf = yaml.safe_load(Path(config_file).read_text())
    pprint.pprint(conf)
    return

gen_vars('./conf.yaml')
</code>```

But here is the output:

```<code>{'animal': [{'dog': [{'noise': ['woof']},
                     {'food': ['dog food']},
                     {'house': ['dog house']}]},
            {'cat': [{'noise': ['meow']},
                     {'food': ['cat food']},
                     {'home': ['cat tree']}]}]
}
</code>```

Problems I have with this output:

Every value is in a list. I dont want that.

Every key/value pair is in a dictionary. I dont want that.

Every key and value are in single quotes. I dont want that.
I want this instead:

```<code>{"animal": {"dog": {"noise": "woof",
                     "food": "dog food",
                     "house": "dog house"}},
            {"cat": {"noise": "meow",
                     "food": "cat food",
                     "home": "cat tree"}}
}
</code>```

Am I formatting my yaml incorrectly? How can I get this type of output?

EDIT:

I figured out how to remove nested lists with dictionaries for each key value pair. This post answered my question:
Load yaml list as dictionary

Need to format without the -

```<code>animal:
    dog:
        noise:
            "woof"
        food:
            "dog food"
        house:
            "dog house"
    cat:
        noise:
            "meow"
        food:
            "cat food"
        home:
            "cat tree"
</code>```

Output:

```<code>{'animal': {'cat': {'food': 'cat food', 'home': 'cat tree', 'noise': 'meow'},
            'dog': {'food': 'dog food', 'house': 'dog house', 'noise': 'woof'}}

</code>```

Still, is there a way to make all single quotes double without converting to a string and using replace("\'","\"")?

Body:
Here is a yaml file I have:

animal:
    - dog:
        - noise:
            - "woof"
        - food:
            - "dog food"
        - house:
            - "dog house"
    - cat:
        - noise:
            - "meow"
        - food:
            - "cat food"
        - home:
            - "cat tree"

Here is the code I use to convert yaml to dictionary:

import yaml, pprint
from pathlib import Path

def gen_vars(conf_file)
    conf = yaml.safe_load(Path(config_file).read_text())
    pprint.pprint(conf)
    return

gen_vars('./conf.yaml')

But here is the output:

{'animal': [{'dog': [{'noise': ['woof']},
                     {'food': ['dog food']},
                     {'house': ['dog house']}]},
            {'cat': [{'noise': ['meow']},
                     {'food': ['cat food']},
                     {'home': ['cat tree']}]}]
}

Problems I have with this output:

Every value is in a list. I dont want that.

Every key/value pair is in a dictionary. I dont want that.

Every key and value are in single quotes. I dont want that.
I want this instead:

{"animal": {"dog": {"noise": "woof",
                     "food": "dog food",
                     "house": "dog house"}},
            {"cat": {"noise": "meow",
                     "food": "cat food",
                     "home": "cat tree"}}
}

Am I formatting my yaml incorrectly? How can I get this type of output?

EDIT:

I figured out how to remove nested lists with dictionaries for each key value pair. This post answered my question:
Load yaml list as dictionary

Need to format without the -

animal:
    dog:
        noise:
            "woof"
        food:
            "dog food"
        house:
            "dog house"
    cat:
        noise:
            "meow"
        food:
            "cat food"
        home:
            "cat tree"

Output:

{'animal': {'cat': {'food': 'cat food', 'home': 'cat tree', 'noise': 'meow'},
            'dog': {'food': 'dog food', 'house': 'dog house', 'noise': 'woof'}}

Still, is there a way to make all single quotes double without converting to a string and using replace("\'","\"")?


问:
use navigate not wroking
```<code> <button
                            className="btn btn-info"
                            onClick={() => {
                              dispatch(detailsEdit(data));
                              **navigate('/adminClientEdit');**
                            }}
                          >
                            More Details
                          </button>
</code>```

I need to navigate and view more pages.in this till dispatch working properly.

Title: use navigate not wroking

Body:
 <button
                            className="btn btn-info"
                            onClick={() => {
                              dispatch(detailsEdit(data));
                              **navigate('/adminClientEdit');**
                            }}
                          >
                            More Details
                          </button>

I need to navigate and view more pages.in this till dispatch working properly.


问:
How can i get current date with difference of current time and login hour in magneto 2
```<code>I am using the following code on controller for getting and saving the current date and time, login hr. and starting current date and difference of time
but the problem is i am using below code and facing issue.
the issue is when we hit the timer controller we are getting the current time as end time and start time but not getting current date on start time we have mention on below screenshot of database. please suggest me how to get current date in start time column of database.
here is file path. Tribugs\Rider\Controller\DutyStatus\Timer;

using below code when we hit controller  we are not getting total hr.('null') and start time but getting the correct current date.
and we 'ON' and 'OFF' the timer we are getting the total hr, start time and end time but not getting current date in start time column of database.

public function execute(){

        $html = '';
        $customerData = array();
        $result = $this->_resultJsonFactory->create();
        $resultPage = $this->_resultPageFactory->create();

        $params = $this->getRequest()->getPostValue("timer");

        $timerParams = $this->getRequest()->getPostValue("timerout");
        $resultRedirect = $this->resultRedirect->create(ResultFactory::TYPE_REDIRECT);
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        $model = $this->_dutystatus->create();
        $customerId = $this->userContext->getUserId();
        if(empty($customerId)) {
         $customerId = 31;
        }
        $today = $this->timezoneInterface->date()->format('H:i:s');
        $output = strtotime($today) - strtotime($timerParams);
        $model->addData([
            "user_id" => $customerId,
            "login_hours" => $params,
            "start_time" =>  $output,
            "end_time" => $today
            ]);
        $saveData = $model->save();
        if($saveData){
            $this->messageManager->addSuccess( __('Insert Record Successfully !') );
        }
        return $resultRedirect;
    }
</code>```

using above code when we hit controller  we are not getting total hr.('null') and start time but getting the correct current date.
and we 'ON' and 'OFF' the timer we are getting the total hr, start time and end time but not getting current date in start time column of database.
Database changed
MariaDB [a5677e1b_gags_frontend]> select * from duty_status;
+----+---------+-------------+---------------------+---------------------+
| id | user_id | login_hours | start_time          | end_time            |
+----+---------+-------------+---------------------+---------------------+
|  1 |     104 |    0.135833 | 1970-01-01 17:28:22 | 2022-12-02 17:36:31 |
|  2 |     104 |      0.1375 | 1970-01-01 17:29:49 | 2022-12-02 17:38:04 |
|  3 |     104 |    0.139722 | 1970-01-01 17:30:30 | 2022-12-02 17:38:53 |
|  4 |     104 |    0.143611 | 1970-01-01 17:30:45 | 2022-12-02 17:39:22 |
|  5 |     104 |    0.144722 | 1970-01-01 17:31:11 | 2022-12-02 17:39:52 |
|  6 |     104 |        NULL | 2022-12-02 19:27:59 | 2022-12-02 19:27:59 |
|  7 |     104 |        NULL | 2022-12-02 19:28:02 | 2022-12-02 19:28:02 |

Body:
I am using the following code on controller for getting and saving the current date and time, login hr. and starting current date and difference of time
but the problem is i am using below code and facing issue.
the issue is when we hit the timer controller we are getting the current time as end time and start time but not getting current date on start time we have mention on below screenshot of database. please suggest me how to get current date in start time column of database.
here is file path. Tribugs\Rider\Controller\DutyStatus\Timer;

using below code when we hit controller  we are not getting total hr.('null') and start time but getting the correct current date.
and we 'ON' and 'OFF' the timer we are getting the total hr, start time and end time but not getting current date in start time column of database.

public function execute(){

        $html = '';
        $customerData = array();
        $result = $this->_resultJsonFactory->create();
        $resultPage = $this->_resultPageFactory->create();

        $params = $this->getRequest()->getPostValue("timer");

        $timerParams = $this->getRequest()->getPostValue("timerout");
        $resultRedirect = $this->resultRedirect->create(ResultFactory::TYPE_REDIRECT);
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        $model = $this->_dutystatus->create();
        $customerId = $this->userContext->getUserId();
        if(empty($customerId)) {
         $customerId = 31;
        }
        $today = $this->timezoneInterface->date()->format('H:i:s');
        $output = strtotime($today) - strtotime($timerParams);
        $model->addData([
            "user_id" => $customerId,
            "login_hours" => $params,
            "start_time" =>  $output,
            "end_time" => $today
            ]);
        $saveData = $model->save();
        if($saveData){
            $this->messageManager->addSuccess( __('Insert Record Successfully !') );
        }
        return $resultRedirect;
    }

using above code when we hit controller  we are not getting total hr.('null') and start time but getting the correct current date.
and we 'ON' and 'OFF' the timer we are getting the total hr, start time and end time but not getting current date in start time column of database.
Database changed
MariaDB [a5677e1b_gags_frontend]> select * from duty_status;
+----+---------+-------------+---------------------+---------------------+
| id | user_id | login_hours | start_time          | end_time            |
+----+---------+-------------+---------------------+---------------------+
|  1 |     104 |    0.135833 | 1970-01-01 17:28:22 | 2022-12-02 17:36:31 |
|  2 |     104 |      0.1375 | 1970-01-01 17:29:49 | 2022-12-02 17:38:04 |
|  3 |     104 |    0.139722 | 1970-01-01 17:30:30 | 2022-12-02 17:38:53 |
|  4 |     104 |    0.143611 | 1970-01-01 17:30:45 | 2022-12-02 17:39:22 |
|  5 |     104 |    0.144722 | 1970-01-01 17:31:11 | 2022-12-02 17:39:52 |
|  6 |     104 |        NULL | 2022-12-02 19:27:59 | 2022-12-02 19:27:59 |
|  7 |     104 |        NULL | 2022-12-02 19:28:02 | 2022-12-02 19:28:02 |


问:
Error: - could not initialize class org.apache.maven.plugin.war.util.webappstructureserializer
I am working on spring maven and I am facing this error in pom.xml

could not initialize class org.apache.maven.plugin.war.util.webappstructureserializer in line 1

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ibank</groupId>
    <artifactId>ibank</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ibank</name>
    <description>With REST</description>

    <build>
        <finalName>ibank</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
</code>```

I have tried few solutions available which said to change version but still it showed the same errors.

Body:
I am working on spring maven and I am facing this error in pom.xml

could not initialize class org.apache.maven.plugin.war.util.webappstructureserializer in line 1

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ibank</groupId>
    <artifactId>ibank</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ibank</name>
    <description>With REST</description>

    <build>
        <finalName>ibank</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

I have tried few solutions available which said to change version but still it showed the same errors.


问:
How to shoot raycaster rays in spherical directions
I have created a raycaster to shoot out rays of 360 degrees with intervals of 3 to detect if a glb is in the camera view. At the moment this works on a flat surface with no change in the y coordinate. I would like this to have a spherical direction.

```<code>var search = []; //array of raycaster rays

for (let i = 0; i < 360; i += 3){
  search[i] = new THREE.Vector3(Math.cos(i), 0, Math.sin(i));
}
</code>```

This is the code for a 360 circle of rays, how would i move the y coordinate to cover a sphere.

```<code>function checkForTargets() {
  search.forEach((direction) => {
    raycaster.set(splineCamera.position, direction, 0, 100)
    const intersects = raycaster.intersectObjects(scene.children, true)
      if (intersects.length > 0) {
        if (intersects[0].object.name) {
          intersects[0].object.material.color.set(0x000000)
        }
      }
  });
}
</code>```

This function is called in my render loop, to test intersects.
Thanks in advance.

Body:
I have created a raycaster to shoot out rays of 360 degrees with intervals of 3 to detect if a glb is in the camera view. At the moment this works on a flat surface with no change in the y coordinate. I would like this to have a spherical direction.

var search = []; //array of raycaster rays

for (let i = 0; i < 360; i += 3){
  search[i] = new THREE.Vector3(Math.cos(i), 0, Math.sin(i));
}

This is the code for a 360 circle of rays, how would i move the y coordinate to cover a sphere.

function checkForTargets() {
  search.forEach((direction) => {
    raycaster.set(splineCamera.position, direction, 0, 100)
    const intersects = raycaster.intersectObjects(scene.children, true)
      if (intersects.length > 0) {
        if (intersects[0].object.name) {
          intersects[0].object.material.color.set(0x000000)
        }
      }
  });
}

This function is called in my render loop, to test intersects.
Thanks in advance.


问:
React Context loses state on Navigation
I created a React App which uses a login form to authenticate the user with the backend. After successful authentication, the backend sends an Object including user data as well as an access token. I then save the object in a custom Context using useState.
As soon as I navigate to a new Page the useState loses its state. At first, I thought the Context component rerenders resulting in the reset. But the ContextProvider is located in the index.tsx and should not rerender.

CurrentUserContext

```<code>type CurrentUserContextProviderProps = {
    children: React.ReactNode;
}

type CurerntUserContextType = {
    user: loginUserResponse | null
    setUser: React.Dispatch<React.SetStateAction<loginUserResponse | null>>
}

export const CurrentUserContext = createContext({} as CurerntUserContextType)

export const CurrentUserContextProvider = ({children}:CurrentUserContextProviderProps) => {
    const [user, setUser] = useState<loginUserResponse | null>(null);
    return <CurrentUserContext.Provider value={{user, setUser}}> {children} </CurrentUserContext.Provider>
};
</code>```

index.tsx

```<code>root.render(
    <BrowserRouter>
    <CurrentUserContextProvider>
      <Routes>
        <Route path="/*" element={<App />}/>
      </Routes>
    </CurrentUserContextProvider>
    </BrowserRouter>
);
</code>```

Backend response Object after successful login

```<code>export interface loginUserResponse  {
    currentUser: {
        userName?: string;
        userLocation?: string;
        telephoneNumber?: string;
        department?: string;
        email?: string;
        homeBase?: string;
        employeeNumber?: string;
    }
    accessToken?: string;
};
</code>```

Title: React Context loses state on Navigation

Body:
I created a React App which uses a login form to authenticate the user with the backend. After successful authentication, the backend sends an Object including user data as well as an access token. I then save the object in a custom Context using useState.
As soon as I navigate to a new Page the useState loses its state. At first, I thought the Context component rerenders resulting in the reset. But the ContextProvider is located in the index.tsx and should not rerender.

CurrentUserContext

type CurrentUserContextProviderProps = {
    children: React.ReactNode;
}

type CurerntUserContextType = {
    user: loginUserResponse | null
    setUser: React.Dispatch<React.SetStateAction<loginUserResponse | null>>
}

export const CurrentUserContext = createContext({} as CurerntUserContextType)

export const CurrentUserContextProvider = ({children}:CurrentUserContextProviderProps) => {
    const [user, setUser] = useState<loginUserResponse | null>(null);
    return <CurrentUserContext.Provider value={{user, setUser}}> {children} </CurrentUserContext.Provider>
};

index.tsx

root.render(
    <BrowserRouter>
    <CurrentUserContextProvider>
      <Routes>
        <Route path="/*" element={<App />}/>
      </Routes>
    </CurrentUserContextProvider>
    </BrowserRouter>
);

Backend response Object after successful login

export interface loginUserResponse  {
    currentUser: {
        userName?: string;
        userLocation?: string;
        telephoneNumber?: string;
        department?: string;
        email?: string;
        homeBase?: string;
        employeeNumber?: string;
    }
    accessToken?: string;
};


问:
.war file missing folder and files for angular project
xml file:
I have added under resources
src/main/frontend/src/app
When the build is done is not creating the folder and placing its files contents.
src/main/frontend/src/app/cheditor
src/main/frontend/src/app/rsp-business-admin
src/main/frontend/src/app/rsp-deletegate
src/main/frontend/src/app/app.tooltip mpeg file
and so on...

```<code><parent>
    <groupId>gov.uspto.cicm</groupId>
    <artifactId>uspto-corporate-pom</artifactId>
    <version>1.5.12.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>gov.uspto.AdminITCap.rsp</groupId>
<artifactId>frontend</artifactId>
<version>${version}</version>
<name>AdminITCap-RSP-Frontend</name>
<packaging>pom</packaging>
<description>The rsp frontend project</description>
<build>
    <plugins>
        <plugin>
        <!-- assamble static content -->
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <descriptors>
                <descriptor>src/main/assembly/static.xml</descriptor>
            </descriptors>
            <finalName>ROOT</finalName>
            <appendAssemblyId>false</appendAssemblyId>
        </configuration>
        <executions>
            <execution>
                <id>make-assembly</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
        </plugin>
        <plugin>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.4</version>

            <configuration>
                <nodeVersion>v6.10.2</nodeVersion>
                <npmVersion>4.5.0</npmVersion>
                <workingDirectory>src/main/frontend</workingDirectory>
            </configuration>

            <executions>

                <execution>
                    <id>install node and npm</id>
                    <goals>
                        <goal>install-node-and-npm</goal>
                    </goals>
                </execution>

                <execution>
                    <id>npm install</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>
                </execution>

                <execution>
                    <id>npm run build</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>

                    <configuration>
                        <arguments>run build</arguments>
                    </configuration>
                </execution>

            </executions>
        </plugin>
    </plugins>

    <resources>
        <resource>
            <directory>src/main/frontend/src/app</directory>
            <targetPath></targetPath>
        </resource>
    </resources>

</build>
<profiles>
    <profile>
        <id>sonar</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <sonar.jdbc.url>jdbc:mysql://host/sonar</sonar.jdbc.url>
            <sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
            <sonar.jdbc.username>sonar</sonar.jdbc.username>
            <sonar.jdbc.password>sonar</sonar.jdbc.password>
            <sonar.host.url>http://host/sonar</sonar.host.url>
        </properties>
    </profile>
</profiles>
<repositories>
   <repository>
      <id>jboss-eap-repository-group</id>
      <name>JBoss EAP Maven Repository</name>
      <url>https://host/nexus/content/groups/public/</url>
      <layout>default</layout>
      <releases>
         <enabled>true</enabled>
         <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
         <enabled>true</enabled>
         <updatePolicy>never</updatePolicy>
      </snapshots>
   </repository>

    <repository>
        <id>nexus</id>
        <name>nexus</name>
        <url>https://host/nexus/content/groups/public/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>PTO plugin repo</id>
        <name>PTO Plugin Repository</name>
        <url>https://host/nexus/content/groups/public/</url>
        <layout>default</layout>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <releases>
            <updatePolicy>never</updatePolicy>
        </releases>
    </pluginRepository>
        <pluginRepository>
      <id>jboss-eap-repository-group</id>
      <name>JBoss EAP Maven Repository</name>
      <url>https://host/nexus/content/groups/public/</url>
      <releases>
         <enabled>true</enabled>
      </releases>
      <snapshots>
         <enabled>true</enabled>
      </snapshots>
   </pluginRepository>
</pluginRepositories>
</code>```

Body:
xml file:
I have added under resources
src/main/frontend/src/app
When the build is done is not creating the folder and placing its files contents.
src/main/frontend/src/app/cheditor
src/main/frontend/src/app/rsp-business-admin
src/main/frontend/src/app/rsp-deletegate
src/main/frontend/src/app/app.tooltip mpeg file
and so on...

<parent>
    <groupId>gov.uspto.cicm</groupId>
    <artifactId>uspto-corporate-pom</artifactId>
    <version>1.5.12.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>gov.uspto.AdminITCap.rsp</groupId>
<artifactId>frontend</artifactId>
<version>${version}</version>
<name>AdminITCap-RSP-Frontend</name>
<packaging>pom</packaging>
<description>The rsp frontend project</description>
<build>
    <plugins>
        <plugin>

        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <descriptors>
                <descriptor>src/main/assembly/static.xml</descriptor>
            </descriptors>
            <finalName>ROOT</finalName>
            <appendAssemblyId>false</appendAssemblyId>
        </configuration>
        <executions>
            <execution>
                <id>make-assembly</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
        </plugin>
        <plugin>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.4</version>

            <configuration>
                <nodeVersion>v6.10.2</nodeVersion>
                <npmVersion>4.5.0</npmVersion>
                <workingDirectory>src/main/frontend</workingDirectory>
            </configuration>

            <executions>

                <execution>
                    <id>install node and npm</id>
                    <goals>
                        <goal>install-node-and-npm</goal>
                    </goals>
                </execution>

                <execution>
                    <id>npm install</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>
                </execution>

                <execution>
                    <id>npm run build</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>

                    <configuration>
                        <arguments>run build</arguments>
                    </configuration>
                </execution>

            </executions>
        </plugin>
    </plugins>

    <resources>
        <resource>
            <directory>src/main/frontend/src/app</directory>
            <targetPath></targetPath>
        </resource>
    </resources>

</build>
<profiles>
    <profile>
        <id>sonar</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <sonar.jdbc.url>jdbc:mysql://host/sonar</sonar.jdbc.url>
            <sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
            <sonar.jdbc.username>sonar</sonar.jdbc.username>
            <sonar.jdbc.password>sonar</sonar.jdbc.password>
            <sonar.host.url>http://host/sonar</sonar.host.url>
        </properties>
    </profile>
</profiles>
<repositories>
   <repository>
      <id>jboss-eap-repository-group</id>
      <name>JBoss EAP Maven Repository</name>
      <url>https://host/nexus/content/groups/public/</url>
      <layout>default</layout>
      <releases>
         <enabled>true</enabled>
         <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
         <enabled>true</enabled>
         <updatePolicy>never</updatePolicy>
      </snapshots>
   </repository>

    <repository>
        <id>nexus</id>
        <name>nexus</name>
        <url>https://host/nexus/content/groups/public/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>PTO plugin repo</id>
        <name>PTO Plugin Repository</name>
        <url>https://host/nexus/content/groups/public/</url>
        <layout>default</layout>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <releases>
            <updatePolicy>never</updatePolicy>
        </releases>
    </pluginRepository>
        <pluginRepository>
      <id>jboss-eap-repository-group</id>
      <name>JBoss EAP Maven Repository</name>
      <url>https://host/nexus/content/groups/public/</url>
      <releases>
         <enabled>true</enabled>
      </releases>
      <snapshots>
         <enabled>true</enabled>
      </snapshots>
   </pluginRepository>
</pluginRepositories>


问:
How to use lcms2 to check for out-of-gamut colors?
I'm converting images with embedded ICC profiles to the sRGB color space using LittleCMS. I want to efficiently detect when this conversion is lossy due to the image containing pixels that are out-of-gamut for the sRGB (e.g. the image is using Display P3 and contains saturated colors).

Note that I don't want to merely check if the embedded profile has a wide gamut, because the image pixels may not be taking advantage of its full gamut, and still fit in sRGB.

I know there's cmsSetAlarmCodes, but this seems like it could cause false positives, because there's nothing stopping the image from actually containing the same color that I set for my alarm color. Does LCMS have some out of band signal for this?

Another approach that comes to my mind is applying conversion twice: to sRGB and then back to the original color space, and checking how lossy it was. But that more than doubles processing time. Is there a more efficient way?


问:
How should I make two integers out of an int64 with bitwise operations in Delphi?
My solution would be:

```<code>IntLo := Integer(Value and $FFFFFFFF);
IntHi := Integer((Value shr 32) and $FFFFFFFF);
</code>```

But I'm not sure this is the fastest solution.

*Edit:
I realised that there is no need for and-ing:

```<code>IntLo := Integer(Value);
IntHi := Integer(Value shr 32);
</code>```

Body:
My solution would be:

IntLo := Integer(Value and $FFFFFFFF);
IntHi := Integer((Value shr 32) and $FFFFFFFF);

But I'm not sure this is the fastest solution.

*Edit:
I realised that there is no need for and-ing:

IntLo := Integer(Value);
IntHi := Integer(Value shr 32);


问:
how to mock a this.state react
I'm not a frontend developer, but I had to give a little maintenance to a page written in react, and I'm stuck adjusting the tests, here's the code that I have:

There's this test:

```<code>describe("display", () => {
  it("should display", () => {
    const c = testutils.quickmount((<table>
      <tbody>
        <Ingestion currentSession={testutils.sessions.default} ingestion={consts.ingestions.completed} />
      </tbody>
</table>))

let columns = c.find("td")
expect(columns.find("td.display").text()).toEqual("1")
})
</code>```

on the render() method I had this structure:

```<code>render(){
const {
...
display
}  = this.ingestion

... boring stuff
{this.renderStatusSummary(display, "display")}
-- I had this line changed to this
{this.renderStatusSummary(this.state.total_display, "display")}
-- and It solved what I needed
</code>```

however, now the above test is failing, and I can't see how to solve this
I suppose that I need to add a instance of my state at the ingestion, here how it is currently set up

```<code>const.test.ts

const defaults = {
 ingestion: api.ingestion({
 ... boring field
 display: 1,
 ... more boring fields
 error: ""
 }),...
</code>```

how can I Mock a this.state here to work? I don't know if my question was clear enough since I barely know what I'm talking about

Title: how to mock a this.state react

Body:
I'm not a frontend developer, but I had to give a little maintenance to a page written in react, and I'm stuck adjusting the tests, here's the code that I have:

There's this test:

describe("display", () => {
  it("should display", () => {
    const c = testutils.quickmount((

        <Ingestion currentSession={testutils.sessions.default} ingestion={consts.ingestions.completed} />

))

let columns = c.find("td")
expect(columns.find("td.display").text()).toEqual("1")
})

on the render() method I had this structure:

render(){
const {
...
display
}  = this.ingestion

... boring stuff
{this.renderStatusSummary(display, "display")}
-- I had this line changed to this
{this.renderStatusSummary(this.state.total_display, "display")}
-- and It solved what I needed

however, now the above test is failing, and I can't see how to solve this
I suppose that I need to add a instance of my state at the ingestion, here how it is currently set up

const.test.ts

const defaults = {
 ingestion: api.ingestion({
 ... boring field
 display: 1,
 ... more boring fields
 error: ""
 }),...

how can I Mock a this.state here to work? I don't know if my question was clear enough since I barely know what I'm talking about


问:
Enable QLayoutItem to take as much space as possible while maintaining its aspect ratio
I have a QGridLayout inside a QWidget which is structured as follows:

Default structure of the layout

In code:

auto widget = new QWidget();
auto layout = new QGridLayout(widget);
layout->setSpacing(30);

// Create button
auto button = new QPushButton();
button->setMinimumSize(160, 90);

auto policy = button->sizePolicy();
policy.setHeightForWidth(true);
policy.setHorizontalPolicy(QSizePolicy::Expanding);
policy.setVerticalPolicy(QSizePolicy::Expanding);
button->setSizePolicy(policy);

layout->addWidget(button, 0, 0, 2, 1);

// Create labels
auto label = new QLabel();

label->setText("QLabel");

policy = label->sizePolicy();
policy.setHorizontalPolicy(QSizePolicy::Fixed);
policy.setVerticalPolicy(QSizePolicy::Expanding);
label->setSizePolicy(policy);

layout->addWidget(label, 0, 1);

label = new QLabel();

label->setText("QLabel");

policy = label->sizePolicy();
policy.setHorizontalPolicy(QSizePolicy::Fixed);
policy.setVerticalPolicy(QSizePolicy::Expanding);
label->setSizePolicy(policy);

layout->addWidget(label, 1, 1);

// Create spacer item
QSpacerItem *spacerItem =
          new QSpacerItem(50, 0, QSizePolicy::Minimum, QSizePolicy::Minimum);

layout->addItem(spacerItem, 0, 2, 2, 1);

widget->setLayout(layout);
```
<p>I want the button to take as much space as possible, but also maintain its aspect ratio.</p>
<p>When adding only height to the widget, the items should expand the following way:</p>
<p>Structure of the layout with too much height</p>
<p>Because the other items are at their minimum width, the button has no available extra width to take and can therefore also not increase its height.</p>
<p>When adding only width to the widget, the items should expand the following way:</p>
<p>Structure of the layout with too much width</p>
<p>Again, because there is no available extra height to take for the button, it cannot increase its width. The available extra width should be used by the spacer item.</p>
<p>I've tried to use the following QSpacePolicy for the button:</p>
```auto policy = button->sizePolicy();
policy.setHeightForWidth(true);
policy.setHorizontalPolicy(QSizePolicy::Expanding);
policy.setVerticalPolicy(QSizePolicy::Expanding);
button->setSizePolicy(policy);
```

The button did not maintain its aspect ratio. QSizePolicy::setWidthForHeight did not help either.

Body:
I have a QGridLayout inside a QWidget which is structured as follows:

Default structure of the layout

In code:

auto widget = new QWidget();
auto layout = new QGridLayout(widget);
layout->setSpacing(30);

// Create button
auto button = new QPushButton();
button->setMinimumSize(160, 90);

auto policy = button->sizePolicy();
policy.setHeightForWidth(true);
policy.setHorizontalPolicy(QSizePolicy::Expanding);
policy.setVerticalPolicy(QSizePolicy::Expanding);
button->setSizePolicy(policy);

layout->addWidget(button, 0, 0, 2, 1);

// Create labels
auto label = new QLabel();

label->setText("QLabel");

policy = label->sizePolicy();
policy.setHorizontalPolicy(QSizePolicy::Fixed);
policy.setVerticalPolicy(QSizePolicy::Expanding);
label->setSizePolicy(policy);

layout->addWidget(label, 0, 1);

label = new QLabel();

label->setText("QLabel");

policy = label->sizePolicy();
policy.setHorizontalPolicy(QSizePolicy::Fixed);
policy.setVerticalPolicy(QSizePolicy::Expanding);
label->setSizePolicy(policy);

layout->addWidget(label, 1, 1);

// Create spacer item
QSpacerItem *spacerItem =
          new QSpacerItem(50, 0, QSizePolicy::Minimum, QSizePolicy::Minimum);

layout->addItem(spacerItem, 0, 2, 2, 1);

widget->setLayout(layout);

I want the button to take as much space as possible, but also maintain its aspect ratio.

When adding only height to the widget, the items should expand the following way:

Structure of the layout with too much height

Because the other items are at their minimum width, the button has no available extra width to take and can therefore also not increase its height.

When adding only width to the widget, the items should expand the following way:

Structure of the layout with too much width

Again, because there is no available extra height to take for the button, it cannot increase its width. The available extra width should be used by the spacer item.

I've tried to use the following QSpacePolicy for the button:

auto policy = button->sizePolicy();
policy.setHeightForWidth(true);
policy.setHorizontalPolicy(QSizePolicy::Expanding);
policy.setVerticalPolicy(QSizePolicy::Expanding);
button->setSizePolicy(policy);

The button did not maintain its aspect ratio. QSizePolicy::setWidthForHeight did not help either.


问:
How to create a DNS record for AWS internal load balancer
We have an internal load balancer serving nginx in AWS which is accessible from our VPN. The load balancer is using an amazon issued certificate from ACM. We are using an external DNS service and we configured the cname of "test.sample.dev" to point to the internal load balancer DNS name in AWS.

We are able to access the internal load balancer via "https://internal-sample.us-east-1.elb.amazonaws.com". But when we try to access "https://test.sample.dev", we are getting a "Secure Connection Failed Error. How can we fix this?


问:
Create a token pattern based on the concatenation of some given words
I have a list of keywords, for example:

keywords = ['airbnb.com', 'booking', 'deliveroo.uk - UK', ...]

My goal is to define the parameter token_pattern of CountVectorizer by concatenating all keywords.

The idea is this:

token_pattern = '|'.join([pattern_keyword_1, pattern_keyword_2, ...])

What interests me is that it matches the exact occurrences in the text and not the substrings.

For example, if I have 'def.com' in the keywords I DON'T want it to match 'abcdef.com'.

Is it possible to do it?

Thanks in advance.


问:
Location of DEBUG_TRACE logs in Civet web server APIs
I am using Civet web apis (https://github.com/civetweb/civetweb) in my application and the call to mg_write is failing somewhere and there are barely any logs to debug the same. I do see that some DEBUG_TRACE logs are getting written in some failure scenarios. Does anyone know where it gets written to?
Is there any flag that needs to be turned on?

I tried to enable access logs and error logs  by adding access_log_file path and error_log_file path as options while starting the server using mg_start API.I am not sure how to get DEBUG_TRACE logs written by Civet apis written to some file.


问:
Android Choosing NavGraph in the Activity
I have a simple activity which looks like this

```<code><layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:fitsSystemWindows="true">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintVertical_bias="0.0"
            app:navGraph="@navigation/nav_graph_A" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

I have two different navigation XML which have the following logic:
Navigation XML A starts in which the starting fragment has a button which if we press Navigation XML B kicks in which has another default start destination and recieves a number in the form of SafeArgs (veryNiceNumber: Int) - so we navigate between two navigation graph and Navigation XML A navigates to Navigation XML B so they have a connection.

What i would like to achieve is this:
I do not want to hardcode the default navGraph. I would like to use some logic to choose which navigation XML gets inflated first.

If the logic chooses Navigation XML B i want to send a random number to the safeArgs

This is the closest i got to the solution:

```<code>override fun onStart() {
    super.onStart()

    val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    val navController = navHostFragment.navController

    val inflater = navController.navInflater
    val graph = inflater.inflate(R.navigation.nav_graph_B)
    val bundle = Bundle()
    bundle.putString("veryNiceNumber", "12")
    graph.addInDefaultArgs(bundle)
    navController.graph = graph
}
</code>```

It navigets to the Navigation XML B but the navArgs throws an error as it doesnt recognise the bundle as navArgs.

I also tried to extract it like this: requireActivity().intent.extras but it is empty.

(Extra task: if the user presses the back button in Navigation XML B it navigates to Navigation XML A)

Body:
I have a simple activity which looks like this

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:fitsSystemWindows="true">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintVertical_bias="0.0"
            app:navGraph="@navigation/nav_graph_A" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

I have two different navigation XML which have the following logic:
Navigation XML A starts in which the starting fragment has a button which if we press Navigation XML B kicks in which has another default start destination and recieves a number in the form of SafeArgs (veryNiceNumber: Int) - so we navigate between two navigation graph and Navigation XML A navigates to Navigation XML B so they have a connection.

What i would like to achieve is this:
I do not want to hardcode the default navGraph. I would like to use some logic to choose which navigation XML gets inflated first.

If the logic chooses Navigation XML B i want to send a random number to the safeArgs

This is the closest i got to the solution:

override fun onStart() {
    super.onStart()

    val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    val navController = navHostFragment.navController

    val inflater = navController.navInflater
    val graph = inflater.inflate(R.navigation.nav_graph_B)
    val bundle = Bundle()
    bundle.putString("veryNiceNumber", "12")
    graph.addInDefaultArgs(bundle)
    navController.graph = graph
}

It navigets to the Navigation XML B but the navArgs throws an error as it doesnt recognise the bundle as navArgs.

I also tried to extract it like this: requireActivity().intent.extras but it is empty.

(Extra task: if the user presses the back button in Navigation XML B it navigates to Navigation XML A)


问:
Twilio - Is there anyway I can dial in a participants?
I tried doing this Twilio - How to move an existing call to a conference but I can only dial in one extra participant I want to add 10 more people.</p>


问:
Multiple Client write methods in I/O Multiplexing
I want to write to multiple clients by checking only FD_SET 1 in FD_ISSET in the if statement, but I want to know how.  Currently, only a single client can write, but how can I write to multiple clients?

```<code>struct result
{
    char buf[MAXLINE];
    struct tm tm;
};
int main()
{
    //omit
    while(1)
    {
        allfds = readfds;
        printf("Select Wait %d\n", maxfd);
        fd_num = select(maxfd + 1 , &allfds, (fd_set*)0,  (fd_set *)0, NULL);

        if (FD_ISSET(listen_fd, &allfds))
        {
            addrlen = sizeof(client_addr);
            client_fd = accept(listen_fd,(struct sockaddr *)&client_addr, &addrlen);
            k++;
            FD_SET(client_fd,&readfds);
            if (client_fd > maxfd)
                maxfd = client_fd;
            printf("Accept OK\n");
            printf("maxfd : %d\n",maxfd);
            continue;
        }
        for (i = 0; i <= maxfd; i++)
        {
            sockfd=i;
            if (FD_ISSET(sockfd, &allfds))
            {
                printf("sockfd : %d\n",sockfd);
                memset(result.buf, 0x00, MAXLINE);
                if (read(sockfd, &result, sizeof(result)) <= 0)
                {
                    close(sockfd);
                    FD_CLR(sockfd, &readfds);
                }
                else
                {
                    if (strncmp(result.buf, "quit\n", 5) ==0)
                    {
                        close(sockfd);
                        FD_CLR(sockfd, &readfds);
                    }
                    else
                    {
                        result_pointer = &result;
                        lt = &(result_pointer->tm);
                        result.buf[strlen(result.buf)-1]='\0';
                        printf("Read : %s %s",result.buf,asctime(lt));
                        for(int j=0;j<k;j++)
                        {
                        write(sockfd+j,&result,sizeof(result));
                        }

                    }
                }

                if (--fd_num <= 0)
                    break;
            }
        }
    }
}

</code>```

I used a for statement to execute write multiple times, but the value was not passed to all connected clients, and the buf value was also output strangely.

Body:
I want to write to multiple clients by checking only FD_SET 1 in FD_ISSET in the if statement, but I want to know how.  Currently, only a single client can write, but how can I write to multiple clients?

struct result
{
    char buf[MAXLINE];
    struct tm tm;
};
int main()
{
    //omit
    while(1)
    {
        allfds = readfds;
        printf("Select Wait %d\n", maxfd);
        fd_num = select(maxfd + 1 , &allfds, (fd_set*)0,  (fd_set *)0, NULL);

        if (FD_ISSET(listen_fd, &allfds))
        {
            addrlen = sizeof(client_addr);
            client_fd = accept(listen_fd,(struct sockaddr *)&client_addr, &addrlen);
            k++;
            FD_SET(client_fd,&readfds);
            if (client_fd > maxfd)
                maxfd = client_fd;
            printf("Accept OK\n");
            printf("maxfd : %d\n",maxfd);
            continue;
        }
        for (i = 0; i <= maxfd; i++)
        {
            sockfd=i;
            if (FD_ISSET(sockfd, &allfds))
            {
                printf("sockfd : %d\n",sockfd);
                memset(result.buf, 0x00, MAXLINE);
                if (read(sockfd, &result, sizeof(result)) <= 0)
                {
                    close(sockfd);
                    FD_CLR(sockfd, &readfds);
                }
                else
                {
                    if (strncmp(result.buf, "quit\n", 5) ==0)
                    {
                        close(sockfd);
                        FD_CLR(sockfd, &readfds);
                    }
                    else
                    {
                        result_pointer = &result;
                        lt = &(result_pointer->tm);
                        result.buf[strlen(result.buf)-1]='\0';
                        printf("Read : %s %s",result.buf,asctime(lt));
                        for(int j=0;j<k;j++)
                        {
                        write(sockfd+j,&result,sizeof(result));
                        }

                    }
                }

                if (--fd_num <= 0)
                    break;
            }
        }
    }
}

I used a for statement to execute write multiple times, but the value was not passed to all connected clients, and the buf value was also output strangely.


问:
PDFBox character getting split into two
We are using PDFBox to write some text over a PDF, it works mostly but for one specific character ത്ത, it's not working as expected. The Unicode representation of this character is \u0D24\u0D4D\u0D24.

When this character is printed, it is getting split into two characters,
ത് ത (without space).

How to solve this?

Title: PDFBox character getting split into two