问:
How can I change the namespace prefix of the timestamp element in the security element of a soap request (wcf)
For clearity, I am using wcf in .NET 4.8.1, because .NET Core doesn't support message security.

I am consuming a soap webservice that requires both transport security and message security, all based on certificates (one private key certificate for the transport security, another private key certificate for the signature and one public key certificate for the message encryption). I needed to write a custom ClientCredentials class to support a second client certificate, because by default you can only specify one. That part is working fine.

When I send a request, the receiver is getting the error 'No signed timestamp present in request', but there really is a signed timestamp present in the request. I validated the signature with SignedXml and that indicates that the signature is valid.

I am not sure for 100%, but my assumption is that the timestamp is not being recognized by the receiver because of the namespace prefix that's being used.

The timestamp that's being created in my soap message by WCF is als follows:

```<code><s:Envelope xmlns:s=http://www.w3.org/2003/05/soap-envelope xmlns:u=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd>

   <s:Header>

      <o:Security s:mustUnderstand="1" xmlns:o=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd>

                    <u:Timestamp u:Id="uuid-f0fe5620-a332-42ea-8520-f045137ee92e-1">

                              <u:Created>2022-12-15T14:24:29.157Z</u:Created>

                              <u:Expires>2022-12-15T14:29:29.157Z</u:Expires>

                    </u:Timestamp>
</code>```

The receiver did have success with a message that's being created by himself, in which the timestamp is as follows:

```<code><wsu:Timestamp wsu:Id="id-2-31b572d3a7dc8a1162f180b927789ef7">

        <wsu:Created>2022-12-19T13:32:19.110501977Z</wsu:Created>

        <wsu:Expires>2022-12-19T13:37:19.110Z</wsu:Expires>

</wsu:Timestamp>
</code>```

The main difference that I see is that in my message the namespace prefix u: is being used, while in the self made message of the receiver, the namespace prefix wsu: is being used.

I am using a custom binding with a SecurityBindingElement on which the IncludeTimestamp property is being set to true. This is a part of the code:

```<code>var securityElement = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, true);

securityElement.IncludeTimestamp = true;

securityElement.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;

securityElement.EnableUnsecuredResponse = true;
</code>```

I can't find a way to change the namespace prefix of the timestamp element. With a MessageFormatter you can change a namespace prefix of the body and subelements of the body, but you don't seem to have access to the ws-security headers. It's also  important to change it at the right stage in the pipeline, because it must be changed before the signature is being created. Otherwise the signature will not be valid anymore.

I know that semantically there is no difference between a u: namespace prefix and a wsu: namespace prefix, but I can't find another reason why my message is being rejected.

Any help would be appreciated.

When I send a message without a timestamp, but with a signature for just the body, the message is being accepted (when the require timestamp policies are being disabled by the receiver). So the technique of creating the signature seems to work. Also the transport security and the decryption of the message by the receiver is working fine.

I tried to write a custom MessageFormatter, but I don't seem to have access to the security headers at that stage. I succeeded to get the namespace prefix wsu: in the envelope, but then it's not being used in the timestamp element. In the timestamp element the namespace is being redefined with the u: namespace prefix.

I also tried to write a ClientMessageInspector, but also at that stage I don't seem to have access to the security headers in the request.

Body:
For clearity, I am using wcf in .NET 4.8.1, because .NET Core doesn't support message security.

I am consuming a soap webservice that requires both transport security and message security, all based on certificates (one private key certificate for the transport security, another private key certificate for the signature and one public key certificate for the message encryption). I needed to write a custom ClientCredentials class to support a second client certificate, because by default you can only specify one. That part is working fine.

When I send a request, the receiver is getting the error 'No signed timestamp present in request', but there really is a signed timestamp present in the request. I validated the signature with SignedXml and that indicates that the signature is valid.

I am not sure for 100%, but my assumption is that the timestamp is not being recognized by the receiver because of the namespace prefix that's being used.

The timestamp that's being created in my soap message by WCF is als follows:

<s:Envelope xmlns:s=http://www.w3.org/2003/05/soap-envelope xmlns:u=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd>

   <s:Header>

      <o:Security s:mustUnderstand="1" xmlns:o=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd>

                              2022-12-15T14:24:29.157Z

                              2022-12-15T14:29:29.157Z

The receiver did have success with a message that's being created by himself, in which the timestamp is as follows:

<wsu:Timestamp wsu:Id="id-2-31b572d3a7dc8a1162f180b927789ef7">

        <wsu:Created>2022-12-19T13:32:19.110501977Z</wsu:Created>

        <wsu:Expires>2022-12-19T13:37:19.110Z</wsu:Expires>

</wsu:Timestamp>

The main difference that I see is that in my message the namespace prefix u: is being used, while in the self made message of the receiver, the namespace prefix wsu: is being used.

I am using a custom binding with a SecurityBindingElement on which the IncludeTimestamp property is being set to true. This is a part of the code:

var securityElement = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, true);

securityElement.IncludeTimestamp = true;

securityElement.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;

securityElement.EnableUnsecuredResponse = true;

I can't find a way to change the namespace prefix of the timestamp element. With a MessageFormatter you can change a namespace prefix of the body and subelements of the body, but you don't seem to have access to the ws-security headers. It's also  important to change it at the right stage in the pipeline, because it must be changed before the signature is being created. Otherwise the signature will not be valid anymore.

I know that semantically there is no difference between a u: namespace prefix and a wsu: namespace prefix, but I can't find another reason why my message is being rejected.

Any help would be appreciated.

When I send a message without a timestamp, but with a signature for just the body, the message is being accepted (when the require timestamp policies are being disabled by the receiver). So the technique of creating the signature seems to work. Also the transport security and the decryption of the message by the receiver is working fine.

I tried to write a custom MessageFormatter, but I don't seem to have access to the security headers at that stage. I succeeded to get the namespace prefix wsu: in the envelope, but then it's not being used in the timestamp element. In the timestamp element the namespace is being redefined with the u: namespace prefix.

I also tried to write a ClientMessageInspector, but also at that stage I don't seem to have access to the security headers in the request.


来源: stackexchange

问:
How can create or add Users on RabbitMq server using console application?
Hello hope you are doing well,
I am new on rabbitmq and am learning different things,
Am trying now to create different users from console application , and publish messages from different users.
any advice to know how  can create users from console application ?

i did not find any thing related to this production using console application ,

My regards,

ContentLicense: CC BY-SA 4.0


问:
Using pipenv shell or other pipenv commands causes AttributeError: 'AnsiToWin32' object has no attribute 'fileno'
Need Help!! I'm new to python and django. I installed pipenv using pip install pipenv and it installed fine. But when i try to use pipenv commands such as pipenv shell or pipenv install requests. I always get the following error.

```<code>Creating a virtualenv for this project...
Pipfile: C:\Users\samue\Desktop\python\Pipfile
Using C:/Users/samue/AppData/Local/Programs/Python/Python311/python.exe (3.11.1) to create virtualenv...
created virtual environment CPython3.11.1.final.0-64 in 678ms
  creator CPython3Windows(dest=C:\Users\samue.virtualenvs\python-wLQjjHfe, clear=False, no_vcs_ignore=False, global=Fal
se)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\samue\
AppData\Local\pypa\virtualenv)
    added seed packages: pip==22.3.1, setuptools==65.6.3, wheel==0.38.4
  activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator

Traceback (most recent call last):
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\core.py", line 1041, in do_creat
e_virtualenv
    err.print(
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\patched\pip_vendor\rich\console
.py", line 1646, in print
    with self:
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\patched\pip_vendor\rich\console
.py", line 848, in exit
    self._exit_buffer()
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\patched\pip_vendor\rich\console
.py", line 806, in _exit_buffer
    self._check_buffer()
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\patched\pip_vendor\rich\console
.py", line 1990, in _check_buffer
    self.file.fileno() in _STD_STREAMS_OUTPUT
    ^^^^^^^^^^^^^^^^
AttributeError: 'AnsiToWin32' object has no attribute 'fileno'
</code>```

I tried venv and it worked fine but i need to work with pipenv . Eariler i used the latest python 3.11.1 and faced the error and now using python 3.10.9 also has the same error with pipenv .

EDIT: Fixed it! It was a bug with pipenv version 2022.12.19(on my system at least), installing version 2022.11.30 seemed to work for me.

Check this https://github.com/pypa/pipenv/issues/5560

Body:
Need Help!! I'm new to python and django. I installed pipenv using pip install pipenv and it installed fine. But when i try to use pipenv commands such as pipenv shell or pipenv install requests. I always get the following error.

Creating a virtualenv for this project...
Pipfile: C:\Users\samue\Desktop\python\Pipfile
Using C:/Users/samue/AppData/Local/Programs/Python/Python311/python.exe (3.11.1) to create virtualenv...
created virtual environment CPython3.11.1.final.0-64 in 678ms
  creator CPython3Windows(dest=C:\Users\samue.virtualenvs\python-wLQjjHfe, clear=False, no_vcs_ignore=False, global=Fal
se)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\samue\
AppData\Local\pypa\virtualenv)
    added seed packages: pip==22.3.1, setuptools==65.6.3, wheel==0.38.4
  activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator

Traceback (most recent call last):
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\core.py", line 1041, in do_creat
e_virtualenv
    err.print(
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\patched\pip_vendor\rich\console
.py", line 1646, in print
    with self:
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\patched\pip_vendor\rich\console
.py", line 848, in exit
    self._exit_buffer()
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\patched\pip_vendor\rich\console
.py", line 806, in _exit_buffer
    self._check_buffer()
  File "C:\Users\samue\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\patched\pip_vendor\rich\console
.py", line 1990, in _check_buffer
    self.file.fileno() in _STD_STREAMS_OUTPUT
    ^^^^^^^^^^^^^^^^
AttributeError: 'AnsiToWin32' object has no attribute 'fileno'

I tried venv and it worked fine but i need to work with pipenv . Eariler i used the latest python 3.11.1 and faced the error and now using python 3.10.9 also has the same error with pipenv .

EDIT: Fixed it! It was a bug with pipenv version 2022.12.19(on my system at least), installing version 2022.11.30 seemed to work for me.

Check this https://github.com/pypa/pipenv/issues/5560


问:
How to stream Mysql query result in node js and close if some forceclose event is received
i've a business logic to implement that entails fetching huge amount of data from mysql table approximately 1 billion.After fetching the record i've to hit an api of another system with each row.I've tried to implement it using stream.Now i am reading from mysql stream and writing into writeable stream and processing there.Now if my scripts receives a forceClose event i want to stop writing and ensure no more api hit is made.I've tried to implement it using mysql stream and scram jet below given is my code,but i am having few issues with my implementation i.e mysql read stream is done writing to writable stream and writable stream is processing the data and hitting api in the meanwhile ForceClose event is received the stream closes but the issues is few api calls are still made even after closing.Is there any fix.Below given is my code</p>
```<code>let stopSending = false;
let newDataStream = new DataStream();
pool.getConnection((err, connection) => {
let numbersStream = connection.query(`SELECT id,number from ${msisdnTableName} Where status='Pending'`).stream({
                    highWaterMark: 5});
numbersStream.on('data', (data) => {

      newDataStream.write(data)

      })
numbersStream.on('end', () => {

  connection.release();
  newDataStream.end();
                })
})

newDataStream.map(async (numberObj) => {
if(!stopSending){
let response=await axios.get("http://localhost:8081/data", {
      params: {
        number: numberObj.number
      }});
if(response.status==200){
  await mysqlUpdateStatus(numberObj.id,'Sent')
 }else{
  await mysqlUpdateStatus(numberObj.id,'Failed')
 }

}
})
.on('end',()=>{
  console.log('all data processed')
})

setTimeOut(()=>{
stopSending=true;
},1000)
</code>```

Body:
i've a business logic to implement that entails fetching huge amount of data from mysql table approximately 1 billion.After fetching the record i've to hit an api of another system with each row.I've tried to implement it using stream.Now i am reading from mysql stream and writing into writeable stream and processing there.Now if my scripts receives a forceClose event i want to stop writing and ensure no more api hit is made.I've tried to implement it using mysql stream and scram jet below given is my code,but i am having few issues with my implementation i.e mysql read stream is done writing to writable stream and writable stream is processing the data and hitting api in the meanwhile ForceClose event is received the stream closes but the issues is few api calls are still made even after closing.Is there any fix.Below given is my code

let stopSending = false;
let newDataStream = new DataStream();
pool.getConnection((err, connection) => {
let numbersStream = connection.query(`SELECT id,number from ${msisdnTableName} Where status='Pending'`).stream({
                    highWaterMark: 5});
numbersStream.on('data', (data) => {

      newDataStream.write(data)

      })
numbersStream.on('end', () => {

  connection.release();
  newDataStream.end();
                })
})

newDataStream.map(async (numberObj) => {
if(!stopSending){
let response=await axios.get("http://localhost:8081/data", {
      params: {
        number: numberObj.number
      }});
if(response.status==200){
  await mysqlUpdateStatus(numberObj.id,'Sent')
 }else{
  await mysqlUpdateStatus(numberObj.id,'Failed')
 }

}
})
.on('end',()=>{
  console.log('all data processed')
})

setTimeOut(()=>{
stopSending=true;
},1000)


问:
TailwindCSS / React Native: overflow scroll not working?
I want to be able to scroll down the list of tweets on my react native app using tailwind css and Expo. Any ideas?

const HomeScreen = () => {
  return (
    <>
      <View className="flex-col overflow-y-scroll h-screen">
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
      </View>
    </>
  );
};

export default HomeScreen;
```


问:
what is difference between import by package and import direct code in flutter
what  is the difference between importing files by `package</p>
```<code>import 'package:fileName/colorFile.dart';

</code>```

and direct import

```<code>import 'fileName/colorFile.dart';
</code>```

Body:
what  is the difference between importing files by `package

import 'package:fileName/colorFile.dart';

and direct import

import 'fileName/colorFile.dart';


问:
Vuex's action is unknown
My Vue3 application gives me error [vuex] unknown action type: updateUnit. There is issue only with action, because getter works fine.

This is file /store/index.ts where I have defined my store object.

```<code>interface State {
  unit: LearningUnit | null
}

const getters: GetterTree<State, any> = {
  unitDictionary: (state: State) => (): Array<Word> => {
    return dictionary
  }
}

const actions: ActionTree<State, any> = {
  async updateUnit ({ commit }, unit: LearningUnit): Promise<void> {
    commit('UPDATE_UNIT', unit)
  }
}

const mutations: MutationTree<State> = {
  UPDATE_UNIT (state, unit: LearningUnit) {
    state.unit = unit
  }
}

export default createStore<State>({
  state: {
    unit: null
  },
  actions: actions,
  mutations: mutations,
  getters: getters
})
</code>```

And this is how I am trying to call my action updateUnit from Vue component:

At first I define it in methods:

```<code>methods: {
  ...mapActions({
    updateUnit: 'updateUnit'
  })
}
</code>```

And then call from watcher like this this.updateUnit(params.unit).

Can you help me with this? Thank you.

Title: Vuex's action is unknown

Body:
My Vue3 application gives me error [vuex] unknown action type: updateUnit. There is issue only with action, because getter works fine.

This is file /store/index.ts where I have defined my store object.

interface State {
  unit: LearningUnit | null
}

const getters: GetterTree<State, any> = {
  unitDictionary: (state: State) => (): Array<Word> => {
    return dictionary
  }
}

const actions: ActionTree<State, any> = {
  async updateUnit ({ commit }, unit: LearningUnit): Promise<void> {
    commit('UPDATE_UNIT', unit)
  }
}

const mutations: MutationTree<State> = {
  UPDATE_UNIT (state, unit: LearningUnit) {
    state.unit = unit
  }
}

export default createStore<State>({
  state: {
    unit: null
  },
  actions: actions,
  mutations: mutations,
  getters: getters
})

And this is how I am trying to call my action updateUnit from Vue component:

At first I define it in methods:

methods: {
  ...mapActions({
    updateUnit: 'updateUnit'
  })
}

And then call from watcher like this this.updateUnit(params.unit).

Can you help me with this? Thank you.


问:
React-Bootsrap Multiple Modals
I have a navbar with the usual login and sign-up buttons. When I click the relevant link, a modal with the form should pop-up allowing the user to login or sign-up. At the moment, neither of the pop-ups seem to work. I have been following React-Bootstrap Multiple Modal and have been using the chosen answer to try and implement the modals.

The handle functions are in my app.jsx:

```<code>import React, {useEffect, useState} from 'react'
import {useRouter} from 'next/router'
import {SessionProvider, useSession} from 'next-auth/react'
import {SSRProvider} from 'react-bootstrap'
import 'application.css';
import Navigation from "../components/Navigation";
import Login from "../components/Login";
import SideNav from "../components/SideNav";
import SignUp from "../components/SignUp";

function MyApp({Component, pageProps}) {
    let id = '';
    const [show, setShow] = useState(null)
    function handleClose() {
        setShow({show: id});
    }

    function handleShow(id) {
        setShow({show: id});
    }
    const [showSideBar, setShowSideBar] = useState(false)
    const toggleSideMenu = () => setShowSideBar((prev) => !prev);

    return (
        <SessionProvider session={pageProps.session}>
            <SSRProvider>
                <SideNav showSideBar={showSideBar} />
                <Navigation
                  handleShow={handleShow}
                  handleClose={handleClose}
                  toggleSideMenu={toggleSideMenu}
                />

                <Login
                  show={show}
                  handleShow={handleShow}
                  handleClose={handleClose}
                />

                <SignUp
                  show={show}
                  handleShow={handleShow}
                  handleClose={handleClose}
                />

                {Component.auth
                    ? <Auth><Component {...pageProps} /></Auth>
                    : <Component {...pageProps} />
                }
            </SSRProvider>
        </SessionProvider>
    )
}

function Auth({children}) {
    // @ts-ignore
    const [session, loading] = useSession()
    const isUser = !!session?.user
    const router = useRouter()

    useEffect(() => {
        if (loading) return // Do nothing while loading
        if (!isUser) router.push('/login')
        // If not authenticated, force log in
    }, [isUser, loading])

    if (isUser) {
        return children
    }

    // Session is being fetched, or no user.
    // If no user, useEffect() will redirect.
    return <div>Loading...</div>
}

export default MyApp
</code>```

I pass the show, handleshow, handleclose to each component. In the navigation the buttons look like this:

```<code><Nav.Link href="#" onClick={() => handleShow('login')}><FontAwesomeIcon icon={solid('sign-in-alt')}/><span> Login</span></Nav.Link>
<Nav.Link href="#" onClick={() => handleShow('signup')}><FontAwesomeIcon icon={solid('user-plus')}/><span> Sign up</span></Nav.Link>
</code>```

And then finally, my Login.jsx with a modal:

```<code>import {getCsrfToken, signIn, useSession} from "next-auth/react";
import Router from "next/router";
import { Modal, CloseButton, Form } from 'react-bootstrap';
import Link from "next/link";
import { useState } from "react";

function Login({csrfToken, show, handleClose, handleShow, props}) {
  const [error, setError] = useState(false);

  //setShow(prev => !prev);

  const handleSubmit = async (e) => {
    e.preventDefault();

    const res = await signIn('credentials', {
      redirect: false,
      email: e.target.email1.value,
      password: e.target.password1.value,
      callbackUrl: `/dashboard`,
    });

    if (res?.error) {
      setError(true);
    } else {
      Router.push('/dashboard');
    }

  }

  return (
    <Modal show={show === "login"} onHide={handleClose} fade={false}>
      <Modal.Header className={"modal-dark bg-dark"}>
        <Modal.Title><h1>Log In</h1></Modal.Title>
        <CloseButton variant="white" onClick={handleClose}/>
      </Modal.Header>
      <Modal.Body className={"modal-dark bg-dark"}>
        <form noValidate onSubmit={(e) => handleSubmit(e)}>
          <input name="csrfToken" type="hidden" defaultValue={csrfToken}/>
          <Form.Group className="mt-3">
            <Form.Control
              id="email-address1"
              name="email1"
              type="email"
              autoComplete="email"
              required
              className=""
              placeholder="Email address"
            />
          </Form.Group>
          <Form.Group className="mt-3">
            <Form.Control
              id="password1"
              name="password1"
              type="password"
              autoComplete="current-password"
              required
              placeholder="Password"
            />
          </Form.Group>
          <button type={"submit"} className={"btn orange-button mt-3"}>Login</button>

          <div>
            or <Link href='/signup'>sign up</Link>
          </div>

          {error && <div className="bg-red-300 p-2 text-white rounded">Wrong email or password</div>}

        </form>

      </Modal.Body>
      <Modal.Footer className={"modal-dark bg-dark"}>
        <button onClick={handleClose}>
          Close
        </button>
      </Modal.Footer>
    </Modal>
  );
}

export default Login;
</code>```

In the developer tools looking at the React components tab, it is sending the correct information.

The props all seem to be there, the modal just doesn't seem to pop-up. Thanks

Title: React-Bootsrap Multiple Modals

Body:
I have a navbar with the usual login and sign-up buttons. When I click the relevant link, a modal with the form should pop-up allowing the user to login or sign-up. At the moment, neither of the pop-ups seem to work. I have been following React-Bootstrap Multiple Modal and have been using the chosen answer to try and implement the modals.

The handle functions are in my app.jsx:

import React, {useEffect, useState} from 'react'
import {useRouter} from 'next/router'
import {SessionProvider, useSession} from 'next-auth/react'
import {SSRProvider} from 'react-bootstrap'
import 'application.css';
import Navigation from "../components/Navigation";
import Login from "../components/Login";
import SideNav from "../components/SideNav";
import SignUp from "../components/SignUp";

function MyApp({Component, pageProps}) {
    let id = '';
    const [show, setShow] = useState(null)
    function handleClose() {
        setShow({show: id});
    }

    function handleShow(id) {
        setShow({show: id});
    }
    const [showSideBar, setShowSideBar] = useState(false)
    const toggleSideMenu = () => setShowSideBar((prev) => !prev);

    return (
        <SessionProvider session={pageProps.session}>
            <SSRProvider>
                <SideNav showSideBar={showSideBar} />
                <Navigation
                  handleShow={handleShow}
                  handleClose={handleClose}
                  toggleSideMenu={toggleSideMenu}
                />

                <Login
                  show={show}
                  handleShow={handleShow}
                  handleClose={handleClose}
                />

                <SignUp
                  show={show}
                  handleShow={handleShow}
                  handleClose={handleClose}
                />

                {Component.auth
                    ? <Auth><Component {...pageProps} /></Auth>
                    : <Component {...pageProps} />
                }
            </SSRProvider>
        </SessionProvider>
    )
}

function Auth({children}) {
    // @ts-ignore
    const [session, loading] = useSession()
    const isUser = !!session?.user
    const router = useRouter()

    useEffect(() => {
        if (loading) return // Do nothing while loading
        if (!isUser) router.push('/login')
        // If not authenticated, force log in
    }, [isUser, loading])

    if (isUser) {
        return children
    }

    // Session is being fetched, or no user.
    // If no user, useEffect() will redirect.
    return
Loading...

}

export default MyApp

I pass the show, handleshow, handleclose to each component. In the navigation the buttons look like this:

 handleShow('login')}><FontAwesomeIcon icon={solid('sign-in-alt')}/> Login
 handleShow('signup')}><FontAwesomeIcon icon={solid('user-plus')}/> Sign up

And then finally, my Login.jsx with a modal:

import {getCsrfToken, signIn, useSession} from "next-auth/react";
import Router from "next/router";
import { Modal, CloseButton, Form } from 'react-bootstrap';
import Link from "next/link";
import { useState } from "react";

function Login({csrfToken, show, handleClose, handleShow, props}) {
  const [error, setError] = useState(false);

  //setShow(prev => !prev);

  const handleSubmit = async (e) => {
    e.preventDefault();

    const res = await signIn('credentials', {
      redirect: false,
      email: e.target.email1.value,
      password: e.target.password1.value,
      callbackUrl: `/dashboard`,
    });

    if (res?.error) {
      setError(true);
    } else {
      Router.push('/dashboard');
    }

  }

  return (
    <Modal show={show === "login"} onHide={handleClose} fade={false}>
      <Modal.Header className={"modal-dark bg-dark"}>
        <Modal.Title>
Log In
</Modal.Title>
        <CloseButton variant="white" onClick={handleClose}/>
      </Modal.Header>
      <Modal.Body className={"modal-dark bg-dark"}>
        <form noValidate onSubmit={(e) => handleSubmit(e)}>
          <input name="csrfToken" type="hidden" defaultValue={csrfToken}/>
          <Form.Group className="mt-3">
            <Form.Control
              id="email-address1"
              name="email1"
              type="email"
              autoComplete="email"
              required
              className=""
              placeholder="Email address"
            />
          </Form.Group>
          <Form.Group className="mt-3">
            <Form.Control
              id="password1"
              name="password1"
              type="password"
              autoComplete="current-password"
              required
              placeholder="Password"
            />
          </Form.Group>
          <button type={"submit"} className={"btn orange-button mt-3"}>Login</button>

            or <Link href='/signup'>sign up</Link>

          {error &&
Wrong email or password
}

        </form>

      </Modal.Body>
      <Modal.Footer className={"modal-dark bg-dark"}>
        <button onClick={handleClose}>
          Close
        </button>
      </Modal.Footer>
    </Modal>
  );
}

export default Login;

In the developer tools looking at the React components tab, it is sending the correct information.

The props all seem to be there, the modal just doesn't seem to pop-up. Thanks


问:
send data from database to form
Friends, I designed a restaurant program, which includes a main or parent form and several sub-forms or child forms that are displayed inside the main form. My main form is Microsoft's standard form. But other forms are DevExpress. The problem I have is that when the amount entered in the order form is saved after clicking the payment button, I cannot send the amount saved in the database to the main form through the DevExpress form. From the technical point of view and the coding of the method, there is no problem, I just don't know why the data is not sent. While in the load event of the main form, when I call the same method, it runs without any problem. Please advise where the problem could be.

```<code>public static void ShowFoundBalance(System.Windows.Forms.Label cashCapital, System.Windows.Forms.Label nonCashCapital, System.Windows.Forms.Label totalCapital)
    {
        Domain.DataBaseContext dataBaseContext = null;
        try
        {
            dataBaseContext =
                new Domain.DataBaseContext();

            Domain.CashBox cashBox =
                dataBaseContext.CashBoxes
                .FirstOrDefault();

            if (cashBox != null)
            {
                cashCapital.Text = cashBox.CashCapital;
                nonCashCapital.Text = cashBox.NonCashCapital;
                totalCapital.Text = cashBox.TotalCapital;
            }
            else
            {
                cashCapital.Text = $"0 تومان";
                nonCashCapital.Text = $"0 تومان";
                totalCapital.Text = $"0 تومان";
            }
        }
        catch (System.Exception ex)
        {
            Utility.ExceptionShow(ex);
        }
        finally
        {
            if (dataBaseContext != null)
            {
                dataBaseContext.Dispose();
                dataBaseContext = null;
            }
        }
    }
</code>```

This is the method that should display the balance of the fund in the main form, which is called from within a DevExpress form. But it does not show any reaction. While this method works well in its original form.

Title: send data from database to form

Body:
Friends, I designed a restaurant program, which includes a main or parent form and several sub-forms or child forms that are displayed inside the main form. My main form is Microsoft's standard form. But other forms are DevExpress. The problem I have is that when the amount entered in the order form is saved after clicking the payment button, I cannot send the amount saved in the database to the main form through the DevExpress form. From the technical point of view and the coding of the method, there is no problem, I just don't know why the data is not sent. While in the load event of the main form, when I call the same method, it runs without any problem. Please advise where the problem could be.

public static void ShowFoundBalance(System.Windows.Forms.Label cashCapital, System.Windows.Forms.Label nonCashCapital, System.Windows.Forms.Label totalCapital)
    {
        Domain.DataBaseContext dataBaseContext = null;
        try
        {
            dataBaseContext =
                new Domain.DataBaseContext();

            Domain.CashBox cashBox =
                dataBaseContext.CashBoxes
                .FirstOrDefault();

            if (cashBox != null)
            {
                cashCapital.Text = cashBox.CashCapital;
                nonCashCapital.Text = cashBox.NonCashCapital;
                totalCapital.Text = cashBox.TotalCapital;
            }
            else
            {
                cashCapital.Text = $"0 تومان";
                nonCashCapital.Text = $"0 تومان";
                totalCapital.Text = $"0 تومان";
            }
        }
        catch (System.Exception ex)
        {
            Utility.ExceptionShow(ex);
        }
        finally
        {
            if (dataBaseContext != null)
            {
                dataBaseContext.Dispose();
                dataBaseContext = null;
            }
        }
    }

This is the method that should display the balance of the fund in the main form, which is called from within a DevExpress form. But it does not show any reaction. While this method works well in its original form.


问:
How do I add a new jquery.easing declaration in .d.ts file
I want to use jquery.easing in next.js typescript project. But when I import "jquery.easing";
Declration in a .tsx component file, It thorw an error:

add a new declaration (.d.ts) file containing declare module 'jquery.easing';

How can I do that ?
Thanks and regards.


问:
Singleton and inheritance overriding
I m stumbling upon singleton and multiple inheritance.

In the following code if i create slow_grizzly first i got the expected results.

But if i create alaska_bear first the slow_grizlly is completelely overridden by alaska_bear.

Not sure why is this happening, or if i m missing something.

```<code>class Singleton():
    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

class Animal(Singleton):
    def __init__(self, *args, is_white=False, **kwargs):
        self.is_white = is_white

class Bear(Animal):
    def __init__(self, region=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.region = region

class Grizzly(Bear):
    def __init__(self, max_speed, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.max_speed = max_speed

alaska_bear = Bear("Alaska")
slow_grizzly = Grizzly(44, region="Colorado", is_white=False)

print(alaska_bear.__dict__) #{'is_white': False, 'region': 'Alaska'}
print(slow_grizzly.__dict__)#expected {'is_white': False, 'region': 'Colorado', 'max_speed': 44}
#but got {'is_white': False, 'region': 'Alaska'}
</code>```

Title: Singleton and inheritance overriding

Body:
I m stumbling upon singleton and multiple inheritance.

In the following code if i create slow_grizzly first i got the expected results.

But if i create alaska_bear first the slow_grizlly is completelely overridden by alaska_bear.

Not sure why is this happening, or if i m missing something.

class Singleton():
    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

class Animal(Singleton):
    def __init__(self, *args, is_white=False, **kwargs):
        self.is_white = is_white

class Bear(Animal):
    def __init__(self, region=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.region = region

class Grizzly(Bear):
    def __init__(self, max_speed, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.max_speed = max_speed

alaska_bear = Bear("Alaska")
slow_grizzly = Grizzly(44, region="Colorado", is_white=False)

print(alaska_bear.__dict__) #{'is_white': False, 'region': 'Alaska'}
print(slow_grizzly.__dict__)#expected {'is_white': False, 'region': 'Colorado', 'max_speed': 44}
#but got {'is_white': False, 'region': 'Alaska'}


问:
Solve recurrence with symbols using SymPy: I got None
I tried to solve a recurrence relation.

$$
\def\r #1{\langle r^{#1} \rangle}
0 = 8 n E \r{n - 1}
    + (n - 1)[n(n - 2) - 4l(l + 1)] \r{n - 3}
    + 4(2n - 1) \r{n - 2}
$$
```
<p>This equation is from quantum mechanics. It derived from the Hamitonian with Coloumb potential.</p>
<p><img src="https://i.stack.imgur.com/HavJd.png" alt="enter image description here" /></p>
<pre class="lang-tex prettyprint-override"><code>$$
H = \frac{1}{2} p^2_r
    + \frac{l(l + 1)}{2 r^2}
    - \frac{1}{r}
$$
</code>```

E and l are symbols, <r^n> is the expected value of r^n repect to the energy eigenstate.

I have a Sage script using SymPy to solve the recurrence relation. My goal is to express <r^n> as a function of E and l. Here is my script.

import sympy
from sympy import Function, rsolve
from sympy.abc import n
l = sympy.symbols('l',integer=True)
energy = sympy.symbols('E')
r = Function('r')

f = 8 * n * energy * r(n - 1) \
    + 4 * (2 * n - 1) * r(n - 2) \
    + (n - 1) * (n * (n - 2) - 4 * l * (l + 1)) * r(n - 3)

print(rsolve(f, r(n), {r(0): 1}))
```
<p>I don't know why the output result is <code>None</code>. I have tried to set <code>l</code> and <code>energy</code> to explicit interger, for example, 1. But it didn't help.</p>
<h2>Expected result</h2>
<p>I am sorry. I don't know. The recurrence relation is too hard for my brain. I am not good at math.</p>
<h2>Output from print</h2>
<p>There is no error, and below is the output.</p>
```None
```
<h2>Extra question</h2>
<p>If my recurrence relation doesn't have a general solution, is it possible to get the results of specific <code>r(n)</code>, for example <code>r(10)</code>?</p>
<h2>Reply for my extra question</h2>
<p>I figured out the recursive method to generate the result of specific <code>r(n)</code>.</p>
<pre class="lang-py prettyprint-override"><code>from functools import cache
@cache
def expected_distance(n, l):
    if n <= -2:
        return 0
    if n == -1:
        return -2 * energy
    if n == 0:
        return 1
    return  simplify((
        - 4 * (2 * (n + 1) - 1) * expected_distance(n - 1, l) \
        - n * ((n + 1) * (n - 1) - 4 * l * (l + 1)) * expected_distance(n - 2, l)
        ) / (8 * (n + 1) * energy))
</code>```

Body:
I tried to solve a recurrence relation.

$$
\def\r #1{\langle r^{#1} \rangle}
0 = 8 n E \r{n - 1}
    + (n - 1)[n(n - 2) - 4l(l + 1)] \r{n - 3}
    + 4(2n - 1) \r{n - 2}
$$

This equation is from quantum mechanics. It derived from the Hamitonian with Coloumb potential.

$$
H = \frac{1}{2} p^2_r
    + \frac{l(l + 1)}{2 r^2}
    - \frac{1}{r}
$$

E and l are symbols, <r^n> is the expected value of r^n repect to the energy eigenstate.

I have a Sage script using SymPy to solve the recurrence relation. My goal is to express <r^n> as a function of E and l. Here is my script.

import sympy
from sympy import Function, rsolve
from sympy.abc import n
l = sympy.symbols('l',integer=True)
energy = sympy.symbols('E')
r = Function('r')

f = 8 * n * energy * r(n - 1) \
    + 4 * (2 * n - 1) * r(n - 2) \
    + (n - 1) * (n * (n - 2) - 4 * l * (l + 1)) * r(n - 3)

print(rsolve(f, r(n), {r(0): 1}))

I don't know why the output result is None. I have tried to set l and energy to explicit interger, for example, 1. But it didn't help.

Expected result

I am sorry. I don't know. The recurrence relation is too hard for my brain. I am not good at math.

Output from print

There is no error, and below is the output.

None

Extra question

If my recurrence relation doesn't have a general solution, is it possible to get the results of specific r(n), for example r(10)?

Reply for my extra question

I figured out the recursive method to generate the result of specific r(n).

from functools import cache
@cache
def expected_distance(n, l):
    if n <= -2:
        return 0
    if n == -1:
        return -2 * energy
    if n == 0:
        return 1
    return  simplify((
        - 4 * (2 * (n + 1) - 1) * expected_distance(n - 1, l) \
        - n * ((n + 1) * (n - 1) - 4 * l * (l + 1)) * expected_distance(n - 2, l)
        ) / (8 * (n + 1) * energy))


问:
making plugin for auto commiting any file change in github
I am making plugin in wordpress site, which see if any changes in any file occured, if they did, then committing the whole codebase to github. I know how to use github api in php, but I need to know, how will I look at changes happening in the wordpress site. Is there wp hook or php code to do it.

I tried to look at the current theme's directory and scanning all the files with scan($files) function, and check for file modifcations with wp_check_file_modifications($files) plugin function, but it works for core wordpress files.

```<code><!-- to get the current theme's directory -->
$theme_directory = get_template_directory();
<!-- to scan through all the files in current directory -->
$files = scandir($theme_directory);
echo 'All files in current theme Directory:' . "\n";
print_r($files);

if ( wp_check_file_modifications( $files ) ) {
    At least one of the files has been modified
  } else {
    All of the files have not been modified
}
</code>```

Is there any other way around it or any other idea with which I can approach this problem? Thanks in advance for help.

Body:
I am making plugin in wordpress site, which see if any changes in any file occured, if they did, then committing the whole codebase to github. I know how to use github api in php, but I need to know, how will I look at changes happening in the wordpress site. Is there wp hook or php code to do it.

I tried to look at the current theme's directory and scanning all the files with scan($files) function, and check for file modifcations with wp_check_file_modifications($files) plugin function, but it works for core wordpress files.

$theme_directory = get_template_directory();

$files = scandir($theme_directory);
echo 'All files in current theme Directory:' . "\n";
print_r($files);

if ( wp_check_file_modifications( $files ) ) {
    At least one of the files has been modified
  } else {
    All of the files have not been modified
}

Is there any other way around it or any other idea with which I can approach this problem? Thanks in advance for help.


问:
Some Android devices not playing higher midi notes
I developed an Android game a few years ago.  I have a newer device now (a Galaxy S20 FE, Android version 12), and I'm noticing problems with MIDI music and sound effects that I didn't experience on my old device (a Galaxy ON5, Android version 6.0.1).

For both music and sound effects, it doesn't seem to be playing higher notes on the new device.  I'm not sure what the cutoff is, but I have one particular pair of sound effects that are identical except for one of them being shifted a few notes higher.  I can hear the lower one without any problems, but I don't hear the higher one at all on the new device.  On the older device, I can hear both sounds, plus other sounds which are much higher.

If anyone wants to test it, this is the game:
https://play.google.com/store/apps/details?id=org.pandcorps.botsnbolts
The nearly identical sound effects are the player shooting (which I can't hear) and enemies shooting (which I can hear).  There are some cannons near the beginning of the Rockslide Bot level which are a quick place to test the enemy shooting sound.  The Hail Bot level's music has high notes that I can't hear at all on the new device (plus a lower bassline that's easy to hear).

Has anyone else experienced this?  Had anyone found a solution?

I use SoundPool for MIDI sound effects and JetPlayer for MIDI music.  I'm not sure if something changed in Android or if there's something different about the new phone.  I expected small changes in the MIDI audio between them, but not this drastic.


问:
How to make a dictionary with name being the string of different variable?
For example, I have the variable:

```<code>name_of_dic = 'abc'
</code>```

And I want do get dictionary:

```<code>'abc' = {}
</code>```

Body:
For example, I have the variable:

name_of_dic = 'abc'

And I want do get dictionary:

'abc' = {}


问:
How do I transform a distorted quadratic polynomial obtained from a 2D image of 3D space and obtain its formula?
Given an array of points representing a quadratic polynomial but that is warped/distorted due to the 3D perspective of the image (see figure 1). The first index of the array contains (x,y) pixel coordinate of the left intersection with the x-axis, the last index of the array contains the (x,y) pixel coordinate of the right intersection with the x-axis.

How can I transform each pixel coordinate of the array into a formula for the quadratic polynomial as depicted in figure 2? Is this even possible?

I have tried to use the cross-ratio as it does contain a vanishing point, but was unable to see if and how that would be helpful in this case. I also think the polynomial regression theory can be of use in some way.


问:
CANANCAN gem questions
I'm relatively new to rails and exploring cancancan gem . Now I do understand this gem and functionality. let me give example lines which I perfectly understand.

```<code>  can :read, :all
  cannot :read, GpPatient
  cannot :read, GpDenguePatient
  cannot :zero_patient, Patient
  cannot :released_patients, Patient
</code>```

Now these are generic function names like read includes show and index and so on.
Now I am putting lines which I don't understand clearly.

```<code>  can :combined_map, Patient
  can :case_response_evidence, Patient
</code>```

There names of actions are not the ones which are generic, What this is doing.
I am putting a controller code here also just to get the clear explanation.
Thanks.

```<code>class DashboardController < ApplicationController

def case_response_evidence
    authorize! :case_response_evidence, Patient
end
  def combined_map
    authorize! :combined_map, Patient
end
end
</code>```

Title: CANANCAN gem questions

Body:
I'm relatively new to rails and exploring cancancan gem . Now I do understand this gem and functionality. let me give example lines which I perfectly understand.

  can :read, :all
  cannot :read, GpPatient
  cannot :read, GpDenguePatient
  cannot :zero_patient, Patient
  cannot :released_patients, Patient

Now these are generic function names like read includes show and index and so on.
Now I am putting lines which I don't understand clearly.

  can :combined_map, Patient
  can :case_response_evidence, Patient

There names of actions are not the ones which are generic, What this is doing.
I am putting a controller code here also just to get the clear explanation.
Thanks.

class DashboardController < ApplicationController

def case_response_evidence
    authorize! :case_response_evidence, Patient
end
  def combined_map
    authorize! :combined_map, Patient
end
end


问:
How to trigger double click using Vanilla JavaScript
I have a International country code selector code for my website contact form, and for that form I want to implement auto double click on the menu button (open and close the menu automatically) after loading the complete website, to load the country flag icons.

Means, the flag icons of my dropdown only starts loading/downloading (one by one) when the user opens the dropdown, which looks ugly specially in mobile devices. I want to preload the flag icons in background, for that I want to implement double click on my ccButton (Var) to download all icons automatically just after loading the webpage.

OR is there any other way available to preload the icons? please suggest me.

  // Cache the elements
  const ccDiv = document.querySelector(".country-code");
  const ccButton = document.querySelector(".country-code .cc-telcode");
  const ccContainer = document.querySelector(".country-code .cc-container");
  const ccSearchInput = document.querySelector(".country-code .cc-search-box");
  const ccList = document.querySelector(".country-code .cc-data-list");
  var selectedCountry = ""; // saved by "code"

  // Add event listeners to the button, input, and list
  // We use a process called "event delegation" on the list
  // to catch events from its children as they "bubble up" the DOM
  // https://dmitripavlutin.com/javascript-event-delegation/
  ccButton.addEventListener("click", handleButton);
  ccSearchInput.addEventListener("input", handleInput);
  ccList.addEventListener("click", handleListClick);
  document.addEventListener("click", handleDocumentClick);

  // All of the data held as objects within an array
  const data = [
     { name: "Afganistan", code: "93", flag: "afg" },
     { name: "Albania", code: "355", flag: "alb" },
     { name: "Algeria", code: "213", flag: "dza" },
     { name: "American Samoa", code: "1-684", flag: "asm" },
     { name: "Andorra", code: "376", flag: "and" },
     { name: "Turkmenistan", code: "993", flag: "tkm" },
     { name: "Turks and Caicos Islands", code: "1-649", flag: "tca" },
     { name: "Tuvalu", code: "688", flag: "tuv" },
     { name: "U.S. Virgin Islands", code: "1-340", flag: "vir" },
     { name: "Uganda", code: "256", flag: "uga" },
     { name: "Ukraine", code: "380", flag: "ukr" },
     { name: "United Arab Emirates", code: "971", flag: "are" },
     { name: "United Kingdom", code: "44", flag: "gbr" },
     { name: "United States", code: "1", flag: "usa" },
     { name: "Uruguay", code: "598", flag: "ury" },
     { name: "Uzbekistan", code: "998", flag: "uzb" },
     { name: "Vanuatu", code: "678", flag: "vut" },
     { name: "Vatican", code: "379", flag: "vat" },
     { name: "Venezuela", code: "58", flag: "ven" },
     { name: "Vietnam", code: "84", flag: "vnm" },
     { name: "Wallis and Futuna", code: "681", flag: "wlf" },
     { name: "Western Sahara", code: "212", flag: "esh" },
     { name: "Yemen", code: "967", flag: "yem" },
     { name: "Zambia", code: "260", flag: "zmb" },
     { name: "Zimbabwe", code: "263", flag: "zwe" },
  ];

  // Handles the document click - it checks to see if the clicked
  // part of the document has a parent element which is either
  // `null` or is the HTML element, and then closes the container
  // if it's open

  function handleDocumentClick(e) {
    const { parentElement } = e.target;
  document.addEventListener("click", (event) => {
    if (!ccDiv.contains(event.target)) {
     ccContainer.classList.remove("show-cc-list");
    }
  });
  }

  // Filters the data based on the characters
  // at the start of the provided name
  function filterData(data, value) {
    return data.filter((obj) => {
      return (
        obj.name.toLowerCase().startsWith(value.toLowerCase()) ||
        obj.code.toLowerCase().startsWith(value.toLowerCase())
      );
    });
  }

  // Create a series of list items based on the
  // data passed to it
  function createListHtml(data) {
    return data.map((obj) => {
        const { name, code, flag } = obj;
        let isSelected = "";
        if (obj.code == selectedCountry) isSelected = "selected";
        return `

${name} (+${code})

      `;
      })
      .join("");
  }

  // Toggle the container on/off
  function handleButton() {
    ccContainer.classList.toggle("show-cc-list");
    ccList.innerHTML = createListHtml(data);
  }

  // No data available list item
  function createNoDataHtml() {
    return '
No data available
';
  }

  // When the input is changed filter the data
  // according to the current value, and then
  // create some list items using that filtered data
  function handleInput(e) {
    const { value } = e.target;
    if (value) {
      const filtered = filterData(data, value);
      if (filtered.length) {
          ccList.innerHTML = createListHtml(filtered);
      } else {
          ccList.innerHTML = createNoDataHtml();
      }
    } else {
      ccList.innerHTML = createListHtml(data);
    }
  }

  // Create some button HTML
  function createButtonHtml(code, flag) {
    return `

      <option class="cc-code" value="+${code}">+${code}</option>
    `;
  }

  // When an item is clicked, grab the relevant data
  // attributes, create the new button HTML, and then
  // close the container
  function handleListClick(e) {
    const item = e.target.closest("li") || e.target;
    if (item.classList.contains("cc-list-items")) {
      const { code, flag } = item.dataset;
      selectedCountry = item.dataset.code;
      ccButton.innerHTML = createButtonHtml(code, flag);
      ccContainer.classList.remove("show-cc-list");
    }
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cc-telcode {
       margin-bottom: 1em;
       display: flex;
       justify-content: center;
       width: 100%;
  }

   .cc-telcode div.cc-code,
   .cc-list-items div.name {
       margin-left: 0.25em;
  }
   .cc-container {
       display: none;
       width: 300px;
       position: absolute;
  }
   .show-cc-list {
       display: block;
       z-index: +999;
  }
   .cc-data-list {
       max-height: 100px;
       list-style: none;
       margin: 1em 0 0 0;
       padding: 0;
       overflow-y: scroll;
       border: 1px soldi darkgray;
  }
   .cc-list-items {
       display: flex;
       padding: 0.25em;
       border: 1px solid lightgray;
  }
   .cc-list-items:hover {
       cursor: pointer;
       background-color: lightyellow;
  }

   #selected {
       cursor: pointer;
       background-color: rgb(73, 118, 241);
  }

  .country-code {
     width:150px;
  }</code>```

<link href="https://amitdutta.co.in/flag/css/flag-icon.css" rel="stylesheet"/>

  <button class="cc-telcode">Tel code</button>

     <input type="text" class="cc-search-box" placeholder="Search for country" />

```

Body:
I have a International country code selector code for my website contact form, and for that form I want to implement auto double click on the menu button (open and close the menu automatically) after loading the complete website, to load the country flag icons.

Means, the flag icons of my dropdown only starts loading/downloading (one by one) when the user opens the dropdown, which looks ugly specially in mobile devices. I want to preload the flag icons in background, for that I want to implement double click on my ccButton (Var) to download all icons automatically just after loading the webpage.

OR is there any other way available to preload the icons? please suggest me.

  // Cache the elements
  const ccDiv = document.querySelector(".country-code");
  const ccButton = document.querySelector(".country-code .cc-telcode");
  const ccContainer = document.querySelector(".country-code .cc-container");
  const ccSearchInput = document.querySelector(".country-code .cc-search-box");
  const ccList = document.querySelector(".country-code .cc-data-list");
  var selectedCountry = ""; // saved by "code"

  // Add event listeners to the button, input, and list
  // We use a process called "event delegation" on the list
  // to catch events from its children as they "bubble up" the DOM
  // https://dmitripavlutin.com/javascript-event-delegation/
  ccButton.addEventListener("click", handleButton);
  ccSearchInput.addEventListener("input", handleInput);
  ccList.addEventListener("click", handleListClick);
  document.addEventListener("click", handleDocumentClick);

  // All of the data held as objects within an array
  const data = [
     { name: "Afganistan", code: "93", flag: "afg" },
     { name: "Albania", code: "355", flag: "alb" },
     { name: "Algeria", code: "213", flag: "dza" },
     { name: "American Samoa", code: "1-684", flag: "asm" },
     { name: "Andorra", code: "376", flag: "and" },
     { name: "Turkmenistan", code: "993", flag: "tkm" },
     { name: "Turks and Caicos Islands", code: "1-649", flag: "tca" },
     { name: "Tuvalu", code: "688", flag: "tuv" },
     { name: "U.S. Virgin Islands", code: "1-340", flag: "vir" },
     { name: "Uganda", code: "256", flag: "uga" },
     { name: "Ukraine", code: "380", flag: "ukr" },
     { name: "United Arab Emirates", code: "971", flag: "are" },
     { name: "United Kingdom", code: "44", flag: "gbr" },
     { name: "United States", code: "1", flag: "usa" },
     { name: "Uruguay", code: "598", flag: "ury" },
     { name: "Uzbekistan", code: "998", flag: "uzb" },
     { name: "Vanuatu", code: "678", flag: "vut" },
     { name: "Vatican", code: "379", flag: "vat" },
     { name: "Venezuela", code: "58", flag: "ven" },
     { name: "Vietnam", code: "84", flag: "vnm" },
     { name: "Wallis and Futuna", code: "681", flag: "wlf" },
     { name: "Western Sahara", code: "212", flag: "esh" },
     { name: "Yemen", code: "967", flag: "yem" },
     { name: "Zambia", code: "260", flag: "zmb" },
     { name: "Zimbabwe", code: "263", flag: "zwe" },
  ];

  // Handles the document click - it checks to see if the clicked
  // part of the document has a parent element which is either
  // `null` or is the HTML element, and then closes the container
  // if it's open

  function handleDocumentClick(e) {
    const { parentElement } = e.target;
  document.addEventListener("click", (event) => {
    if (!ccDiv.contains(event.target)) {
     ccContainer.classList.remove("show-cc-list");
    }
  });
  }

  // Filters the data based on the characters
  // at the start of the provided name
  function filterData(data, value) {
    return data.filter((obj) => {
      return (
        obj.name.toLowerCase().startsWith(value.toLowerCase()) ||
        obj.code.toLowerCase().startsWith(value.toLowerCase())
      );
    });
  }

  // Create a series of list items based on the
  // data passed to it
  function createListHtml(data) {
    return data.map((obj) => {
        const { name, code, flag } = obj;
        let isSelected = "";
        if (obj.code == selectedCountry) isSelected = "selected";
        return `

${name} (+${code})

      `;
      })
      .join("");
  }

  // Toggle the container on/off
  function handleButton() {
    ccContainer.classList.toggle("show-cc-list");
    ccList.innerHTML = createListHtml(data);
  }

  // No data available list item
  function createNoDataHtml() {
    return '
No data available
';
  }

  // When the input is changed filter the data
  // according to the current value, and then
  // create some list items using that filtered data
  function handleInput(e) {
    const { value } = e.target;
    if (value) {
      const filtered = filterData(data, value);
      if (filtered.length) {
          ccList.innerHTML = createListHtml(filtered);
      } else {
          ccList.innerHTML = createNoDataHtml();
      }
    } else {
      ccList.innerHTML = createListHtml(data);
    }
  }

  // Create some button HTML
  function createButtonHtml(code, flag) {
    return `

      <option class="cc-code" value="+${code}">+${code}</option>
    `;
  }

  // When an item is clicked, grab the relevant data
  // attributes, create the new button HTML, and then
  // close the container
  function handleListClick(e) {
    const item = e.target.closest("li") || e.target;
    if (item.classList.contains("cc-list-items")) {
      const { code, flag } = item.dataset;
      selectedCountry = item.dataset.code;
      ccButton.innerHTML = createButtonHtml(code, flag);
      ccContainer.classList.remove("show-cc-list");
    }
  }

.cc-telcode {
       margin-bottom: 1em;
       display: flex;
       justify-content: center;
       width: 100%;
  }

   .cc-telcode div.cc-code,
   .cc-list-items div.name {
       margin-left: 0.25em;
  }
   .cc-container {
       display: none;
       width: 300px;
       position: absolute;
  }
   .show-cc-list {
       display: block;
       z-index: +999;
  }
   .cc-data-list {
       max-height: 100px;
       list-style: none;
       margin: 1em 0 0 0;
       padding: 0;
       overflow-y: scroll;
       border: 1px soldi darkgray;
  }
   .cc-list-items {
       display: flex;
       padding: 0.25em;
       border: 1px solid lightgray;
  }
   .cc-list-items:hover {
       cursor: pointer;
       background-color: lightyellow;
  }

   #selected {
       cursor: pointer;
       background-color: rgb(73, 118, 241);
  }

  .country-code {
     width:150px;
  }

<link href="https://amitdutta.co.in/flag/css/flag-icon.css" rel="stylesheet"/>

  <button class="cc-telcode">Tel code</button>

     <input type="text" class="cc-search-box" placeholder="Search for country" />


问:
How do I return a value and print it out?
Hello I am currently programming a UEFI bootloader with GNU-EFI and I am just about to program a small config system I have tested it so far and it works, but now I did not want to have everything in one file and split it into several files. Now I have the problem that in my File.c file in the ReadFile function somehow the buffer is not returned. I already checked if the buffer contains anything at all and t does. Hope someone can help me.

File.c

```<code>UINT8 *ReadFile(EFI_FILE_HANDLE Volume, CHAR16 *FileName) {

    // Declare variables
    EFI_STATUS Status;
    EFI_FILE_HANDLE FileHandle;
    UINT64 ReadSize;
    UINT8 *Buffer;

    // Open the file
    Status = uefi_call_wrapper(
        Volume->Open,
        5,
        Volume,
        &FileHandle,
        FileName,
        EFI_FILE_MODE_READ,
        EFI_FILE_READ_ONLY | EFI_FILE_HIDDEN | EFI_FILE_SYSTEM
    );
    if(EFI_ERROR(Status)) {
        Print(L"Could not open file! Reason: %r\n", Status);
    }

    // Read the contents of the file
    ReadSize = FileSize(FileHandle);
    Buffer = AllocatePool(ReadSize);

    Status = uefi_call_wrapper(
        FileHandle->Read,
        3,
        FileHandle,
        &ReadSize,
        Buffer
    );
    if(EFI_ERROR(Status)) {
        Print(L"Could not read file! Reason: %r\n", Status);
    }

    // Close the file
    Status = uefi_call_wrapper(
        FileHandle->Close,
        1,
        FileHandle
    );
    if(EFI_ERROR(Status)) {
        Print(L"Could not close file! Reason: %r\n", Status);
    }

    return Buffer;
}
</code>```

Main.c

```<code>    UINT8 *Buffer = ReadFile(Volume, FileName);

    Print(L"File content:\n%a\n", Buffer);
</code>```

Body:
Hello I am currently programming a UEFI bootloader with GNU-EFI and I am just about to program a small config system I have tested it so far and it works, but now I did not want to have everything in one file and split it into several files. Now I have the problem that in my File.c file in the ReadFile function somehow the buffer is not returned. I already checked if the buffer contains anything at all and t does. Hope someone can help me.

File.c

UINT8 *ReadFile(EFI_FILE_HANDLE Volume, CHAR16 *FileName) {

    // Declare variables
    EFI_STATUS Status;
    EFI_FILE_HANDLE FileHandle;
    UINT64 ReadSize;
    UINT8 *Buffer;

    // Open the file
    Status = uefi_call_wrapper(
        Volume->Open,
        5,
        Volume,
        &FileHandle,
        FileName,
        EFI_FILE_MODE_READ,
        EFI_FILE_READ_ONLY | EFI_FILE_HIDDEN | EFI_FILE_SYSTEM
    );
    if(EFI_ERROR(Status)) {
        Print(L"Could not open file! Reason: %r\n", Status);
    }

    // Read the contents of the file
    ReadSize = FileSize(FileHandle);
    Buffer = AllocatePool(ReadSize);

    Status = uefi_call_wrapper(
        FileHandle->Read,
        3,
        FileHandle,
        &ReadSize,
        Buffer
    );
    if(EFI_ERROR(Status)) {
        Print(L"Could not read file! Reason: %r\n", Status);
    }

    // Close the file
    Status = uefi_call_wrapper(
        FileHandle->Close,
        1,
        FileHandle
    );
    if(EFI_ERROR(Status)) {
        Print(L"Could not close file! Reason: %r\n", Status);
    }

    return Buffer;
}

Main.c

    UINT8 *Buffer = ReadFile(Volume, FileName);

    Print(L"File content:\n%a\n", Buffer);


问:
Constraint Layout memory leak on Fragment
So, i'am trying to learn about memory leaking with Leak Canary, and found that every fragment that i have is leaking. I'am using viewbinding in here, and here is the log:

```<code>androidx.constraintlayout.widget.ConstraintLayout instance
    Leaking: YES (ObjectWatcher was watching this because com.lelestacia.lelenimexml.feature.anime.ui.home.
    AnimeFragment received Fragment#onDestroyView() callback (references to its views should be cleared to prevent leaks))
    Retaining 3.0 kB in 63 objects
    key = e41d026f-fe51-475c-bb6a-ddbb25fe0bd0
    watchDurationMillis = 13782
    retainedDurationMillis = 8781
    View not part of a window view hierarchy
    View.mAttachInfo is null (view detached)
    View.mWindowAttachCount = 1
    mContext instance of dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper, wrapping
    activity com.lelestacia.lelenimexml.MainActivity with mDestroyed = false
</code>```

Even when i tried to set the binding to null inside onDestroyView, the constraint layout of all fragment is still leaking.

Body:
So, i'am trying to learn about memory leaking with Leak Canary, and found that every fragment that i have is leaking. I'am using viewbinding in here, and here is the log:

androidx.constraintlayout.widget.ConstraintLayout instance
    Leaking: YES (ObjectWatcher was watching this because com.lelestacia.lelenimexml.feature.anime.ui.home.
    AnimeFragment received Fragment#onDestroyView() callback (references to its views should be cleared to prevent leaks))
    Retaining 3.0 kB in 63 objects
    key = e41d026f-fe51-475c-bb6a-ddbb25fe0bd0
    watchDurationMillis = 13782
    retainedDurationMillis = 8781
    View not part of a window view hierarchy
    View.mAttachInfo is null (view detached)
    View.mWindowAttachCount = 1
    mContext instance of dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper, wrapping
    activity com.lelestacia.lelenimexml.MainActivity with mDestroyed = false

Even when i tried to set the binding to null inside onDestroyView, the constraint layout of all fragment is still leaking.


问:
Python Humanizing is failing at numbers above a googol
So, i am using Humanize in Python and Nextcord for a discord bot to shorten my Numbers with many zeros in a json file.
When i am humanizing it with following code:

```<code>import humanize

def humanizing(num):
    num = humanize.intword(num)
    num = num.replace(".0", "")
    return num

@client.command()
async def account(ctx, player: nextcord.Member = None):
    if player is None:
        player = ctx.author
    await open_account(player)
    await check(player)
    user = player
    users = await get_bank_data()
    wallet_amt = users[str(user.id)]["Wallet"]
    print(humanizing(wallet_amt))
</code>```
```<code>{
    "593456006160318464": {
        "Wallet": 1000000000000000000000000000000000000,
        "Bank": 0,
        "Bounty": 0,
        "Username": "Navis"
    }
}
</code>```

and the user has 1000000000000000000000000000000000000 money, it says 0 googol instead of 1 googol. Adding more Zeroes will cause a failure and say then like 10000 decillion

Does Humanize just break at this point or is it because of me?
These Code snippets are the important stuff for the problem.
If you need more of my code tell me!

Body:
So, i am using Humanize in Python and Nextcord for a discord bot to shorten my Numbers with many zeros in a json file.
When i am humanizing it with following code:

import humanize

def humanizing(num):
    num = humanize.intword(num)
    num = num.replace(".0", "")
    return num

@client.command()
async def account(ctx, player: nextcord.Member = None):
    if player is None:
        player = ctx.author
    await open_account(player)
    await check(player)
    user = player
    users = await get_bank_data()
    wallet_amt = users[str(user.id)]["Wallet"]
    print(humanizing(wallet_amt))

{
    "593456006160318464": {
        "Wallet": 1000000000000000000000000000000000000,
        "Bank": 0,
        "Bounty": 0,
        "Username": "Navis"
    }
}

and the user has 1000000000000000000000000000000000000 money, it says 0 googol instead of 1 googol. Adding more Zeroes will cause a failure and say then like 10000 decillion

Does Humanize just break at this point or is it because of me?
These Code snippets are the important stuff for the problem.
If you need more of my code tell me!


问:
Can you use a variable value as a variable name in Python
Can you use a variable value as part of another variable name in Python.

For example, lets assume that I have a few variables named a1, a2, a3

Then can I access the variable using the value of another variable, lets say b = 2, therefore can I access a2
Something like (this is wrong but helps to explain)

```<code>a1 = "First"
a2 = "Second"
a3 = "Third"
b = 2
print(a%s,b)
</code>```

This should print variable a2.

Thanks

Body:
Can you use a variable value as part of another variable name in Python.

For example, lets assume that I have a few variables named a1, a2, a3

Then can I access the variable using the value of another variable, lets say b = 2, therefore can I access a2
Something like (this is wrong but helps to explain)

a1 = "First"
a2 = "Second"
a3 = "Third"
b = 2
print(a%s,b)

This should print variable a2.

Thanks


问:
use a three.js shader pass effect with fiber
I would like to use this shader pass below in a react-fiber project :

https://github.com/felixturner/bad-tv-shader

how to convert this :

```<code>composer = new THREE.EffectComposer( renderer);
renderPass = new THREE.RenderPass( scene, camera );
badTVPass = new THREE.ShaderPass( THREE.BadTVShader );
composer.addPass( renderPass );
composer.addPass( badTVPass );
badTVPass.renderToScreen = true;
</code>```

into react-fiber ?
Thanks.

Body:
I would like to use this shader pass below in a react-fiber project :

https://github.com/felixturner/bad-tv-shader

how to convert this :

composer = new THREE.EffectComposer( renderer);
renderPass = new THREE.RenderPass( scene, camera );
badTVPass = new THREE.ShaderPass( THREE.BadTVShader );
composer.addPass( renderPass );
composer.addPass( badTVPass );
badTVPass.renderToScreen = true;

into react-fiber ?
Thanks.


问:
My Kotlinplugin for Minecraft is not working
My Plugin for Fabric 1.19.3 makes an error when i perform a command in chat
Here is the code for the command class

```<code>
package me.lukas.mcplugin1.commands

import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.TextColor
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender

class TestCommand : CommandExecutor {

    override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>?): Boolean {

        sender.sendMessage(Component.text("Test").color(TextColor.color(0 ,200, 0)))

        return false
    }
}

</code>```

And Here is the code for the main class

```<code>package me.lukas.mcplugin1

import me.lukas.mcplugin1.commands.JumpCommand
import me.lukas.mcplugin1.commands.TestCommand
import org.bukkit.plugin.java.JavaPlugin

class McPlugin1 : JavaPlugin() {

    override fun onEnable() {
        // Plugin startup logic
        logger.info("Du hast es geschafft !")
        registerCommands()
    }

    private fun registerCommands () {
        getCommand("jump")?.setExecutor(JumpCommand())
        getCommand("test")?.setExecutor(TestCommand())
        logger.info("Registered Commands")
    }

    override fun onDisable() {
        // Plugin shutdown logic
        logger.info("Tschüss")
    }
}

</code>```

Can anyone Help Me to find the error

I expected that i get the message "test" but it gave me an error
here is the serverconsole error after i enterd the command

```<code>[17:54:59 WARN]: Unexpected exception while parsing console command "test"
org.bukkit.command.CommandException: Unhandled exception executing command 'test' in plugin Loginplugin v1.0-SNAPSHOT
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:47) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:155) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.craftbukkit.v1_19_R2.CraftServer.dispatchCommand(CraftServer.java:929) ~[paper-1.19.3.jar:git-Paper-365]
        at org.bukkit.craftbukkit.v1_19_R2.CraftServer.dispatchServerCommand(CraftServer.java:892) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.dedicated.DedicatedServer.handleConsoleInputs(DedicatedServer.java:494) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.dedicated.DedicatedServer.tickChildren(DedicatedServer.java:441) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1397) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1173) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:316) ~[paper-1.19.3.jar:git-Paper-365]
        at java.lang.Thread.run(Thread.java:1589) ~[?:?]
Caused by: java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
        at me.lukas.mcplugin1.commands.TestCommand.onCommand(TestCommand.kt) ~[Mcplugin1.0.jar:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:45) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        ... 9 more
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
        at org.bukkit.plugin.java.PluginClassLoader.loadClass0(PluginClassLoader.java:177) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.plugin.java.PluginClassLoader.loadClass(PluginClassLoader.java:124) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[?:?]
        at me.lukas.mcplugin1.commands.TestCommand.onCommand(TestCommand.kt) ~[Mcplugin1.0.jar:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:45) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        ... 9 more

</code>```

Body:
My Plugin for Fabric 1.19.3 makes an error when i perform a command in chat
Here is the code for the command class

package me.lukas.mcplugin1.commands

import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.TextColor
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender

class TestCommand : CommandExecutor {

    override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>?): Boolean {

        sender.sendMessage(Component.text("Test").color(TextColor.color(0 ,200, 0)))

        return false
    }
}

And Here is the code for the main class

package me.lukas.mcplugin1

import me.lukas.mcplugin1.commands.JumpCommand
import me.lukas.mcplugin1.commands.TestCommand
import org.bukkit.plugin.java.JavaPlugin

class McPlugin1 : JavaPlugin() {

    override fun onEnable() {
        // Plugin startup logic
        logger.info("Du hast es geschafft !")
        registerCommands()
    }

    private fun registerCommands () {
        getCommand("jump")?.setExecutor(JumpCommand())
        getCommand("test")?.setExecutor(TestCommand())
        logger.info("Registered Commands")
    }

    override fun onDisable() {
        // Plugin shutdown logic
        logger.info("Tschüss")
    }
}

Can anyone Help Me to find the error

I expected that i get the message "test" but it gave me an error
here is the serverconsole error after i enterd the command

[17:54:59 WARN]: Unexpected exception while parsing console command "test"
org.bukkit.command.CommandException: Unhandled exception executing command 'test' in plugin Loginplugin v1.0-SNAPSHOT
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:47) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:155) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.craftbukkit.v1_19_R2.CraftServer.dispatchCommand(CraftServer.java:929) ~[paper-1.19.3.jar:git-Paper-365]
        at org.bukkit.craftbukkit.v1_19_R2.CraftServer.dispatchServerCommand(CraftServer.java:892) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.dedicated.DedicatedServer.handleConsoleInputs(DedicatedServer.java:494) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.dedicated.DedicatedServer.tickChildren(DedicatedServer.java:441) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1397) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1173) ~[paper-1.19.3.jar:git-Paper-365]
        at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:316) ~[paper-1.19.3.jar:git-Paper-365]
        at java.lang.Thread.run(Thread.java:1589) ~[?:?]
Caused by: java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
        at me.lukas.mcplugin1.commands.TestCommand.onCommand(TestCommand.kt) ~[Mcplugin1.0.jar:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:45) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        ... 9 more
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
        at org.bukkit.plugin.java.PluginClassLoader.loadClass0(PluginClassLoader.java:177) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.plugin.java.PluginClassLoader.loadClass(PluginClassLoader.java:124) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[?:?]
        at me.lukas.mcplugin1.commands.TestCommand.onCommand(TestCommand.kt) ~[Mcplugin1.0.jar:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:45) ~[paper-api-1.19.3-R0.1-SNAPSHOT.jar:?]
        ... 9 more


问:
Why is the stream provider providing values when it should only provide null once?
My stream provider seems to keep providing values even though it shouldnt. I do not understand why the code is not working, it should stream as initial value null and since the initial value is null then it should return sign_in(). In the sign_in() widget it should await till I press a GestureDetector() that would sign me in anonymously. Only once I press that same GestureDetector() the user stops being null and the stream  should return an InstanceOfUser, consequently returning Home().

main.dart

```<code>Widget build(BuildContext context) {
  return StreamProvider<UserId?>.value(
    initialData: null,
    value: AuthService().user,
    child: MaterialApp(
      home: Wrapper(),
    ),
  );
</code>```

auth.dart

```<code>class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  //create user obj
  UserId? _userFromFirebaseUser(User? user) {

    print("_userFromFBase");
    return (user != null) ? UserId(uid: user.uid): null;
  }

  Stream<UserId?> get user {
    print("stream");
    return _auth.authStateChanges()
        .map(_userFromFirebaseUser);
  }

  //anon sign in
  Future signInAnon() async {
    try {
      UserCredential authResult = await _auth.signInAnonymously();
      User? user = authResult.user;
      return _userFromFirebaseUser(user);
    } catch(e) {
      //ignore: avoid_print
      print(e.toString());
      return null;
    }
  }
}

</code>```

wrapper.dart

```<code>final UserId? user = Provider.of<UserId?>(context);
print(user);

  return (user != null ) ? Home() : SignIn();
</code>```

sign_in.dart

```<code>GestureDetector(
  onTap: () async {
    dynamic result = await _auth.signInAnon();
    if (result == null) {
      print('error signing in');
    }
    else
    {
      print('signed in');
      print(result.uid);
    }
  },
  child: Container(
    height: 60.0,
    width:  size.width/2 - 40,
    decoration: BoxDecoration(
      color: Colors.black,
      borderRadius:
        BorderRadius.all(Radius.circular(20.0))
    ),
    child: Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: const [
          Text("Anon.png", style: TextStyle(fontSize:  12.0,)),
          SizedBox(width: 5.0),
          Text("Anon", style: TextStyle(color: Colors.white,
          fontWeight: FontWeight.w500, fontSize: 18.0)),
        ],
      ),
    ),
  ),
),
</code>```

I have no idea whats going on so any help would be welcome. Btw, I am rather new to flutter.

I tried changing the stream provider get user func but it didnt seem to help...

Body:
My stream provider seems to keep providing values even though it shouldnt. I do not understand why the code is not working, it should stream as initial value null and since the initial value is null then it should return sign_in(). In the sign_in() widget it should await till I press a GestureDetector() that would sign me in anonymously. Only once I press that same GestureDetector() the user stops being null and the stream  should return an InstanceOfUser, consequently returning Home().

main.dart

Widget build(BuildContext context) {
  return StreamProvider<UserId?>.value(
    initialData: null,
    value: AuthService().user,
    child: MaterialApp(
      home: Wrapper(),
    ),
  );

auth.dart

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  //create user obj
  UserId? _userFromFirebaseUser(User? user) {

    print("_userFromFBase");
    return (user != null) ? UserId(uid: user.uid): null;
  }

  Stream<UserId?> get user {
    print("stream");
    return _auth.authStateChanges()
        .map(_userFromFirebaseUser);
  }

  //anon sign in
  Future signInAnon() async {
    try {
      UserCredential authResult = await _auth.signInAnonymously();
      User? user = authResult.user;
      return _userFromFirebaseUser(user);
    } catch(e) {
      //ignore: avoid_print
      print(e.toString());
      return null;
    }
  }
}

wrapper.dart

final UserId? user = Provider.of<UserId?>(context);
print(user);

  return (user != null ) ? Home() : SignIn();

sign_in.dart

GestureDetector(
  onTap: () async {
    dynamic result = await _auth.signInAnon();
    if (result == null) {
      print('error signing in');
    }
    else
    {
      print('signed in');
      print(result.uid);
    }
  },
  child: Container(
    height: 60.0,
    width:  size.width/2 - 40,
    decoration: BoxDecoration(
      color: Colors.black,
      borderRadius:
        BorderRadius.all(Radius.circular(20.0))
    ),
    child: Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: const [
          Text("Anon.png", style: TextStyle(fontSize:  12.0,)),
          SizedBox(width: 5.0),
          Text("Anon", style: TextStyle(color: Colors.white,
          fontWeight: FontWeight.w500, fontSize: 18.0)),
        ],
      ),
    ),
  ),
),

I have no idea whats going on so any help would be welcome. Btw, I am rather new to flutter.

I tried changing the stream provider get user func but it didnt seem to help...


问:
What is the simplest way to create a music player using react-native-sounds with play & pause toggle controls in same button?
I wanted to create a music player using react-native-sounds but and it was playing music flawless but the issue wast it was not stoping when i press the button, btw the button of play & pause is same.I also want it to pause when another track is playing or navigating out of that screen.

I have tried giving all type of condition's in the button to play and pause on state change,
twist is that when I use seprate button it pause and play fine but not in same button.


问:
How to upload a Video in back4app
so I‘m working with flutter and Back4App and I want to Upload Videos from the Gallery or from the Camera to Back4App. I couldn‘t find a tutorial to it online so I‘m kinda stuck. And help is much appreciated!

Also I can already choose videos from the Gallery or take Videos with the camera but after that my App crashes and the Video wont show in my app.

Title: How to upload a Video in back4app


问:
When trying to update an instance of related models I get the Ids on the template instead of the names, using {{form}}
URLS.py

urlpatterns = [
    path('stock/update/<int:pk>/', views.StockUpdateView, name='stock-update'),
```
<p>VIEWS.py</p>
<pre class="lang-py prettyprint-override"><code>def StockUpdateView(request, pk):
     stock = Stock.objects.get(id=pk)
     form = StockForm(instance=stock)

     if request.method == 'POST':
          form = StockForm(request.POST, instance=stock)
          if form.is_valid():
               form.save()
               return redirect('/inventory/stock')
     context = {"form": form}
     return render(request, 'inventory/update-stock.html', context)
</code>```

TEMPLATE.html

<form action="" method="POST" class="row g-3">

Stock update form:

        {% csrf_token %}
        {% for field in form %}

          {{field}}

        {% endfor %}
```
<p>MODEL.py</p>
<pre class="lang-py prettyprint-override"><code>class Stock(models.Model):
    class Meta:
        verbose_name_plural = "Stocks"

    name = models.ForeignKey(Warehouse, on_delete=models.CASCADE)
    product_id = models.ForeignKey('products.Product', on_delete=models.CASCADE)
    quantity = models.IntegerField(default=0)
    product_price = models.DecimalField(max_digits=19, decimal_places=2, default=0 ,validators=[MinValueValidator(0)])

    def get_absolute_url(self):
        return reverse("stock-update", args=[self.pk])

    def __str__(self):
        return f"{self.product_id} {self.quantity} {self.product_price}"
</code>```

I have changed from using the {{ form }} tag to looping over the fields trying to get the name of the related table instead of the IDs.

Body:
URLS.py

urlpatterns = [
    path('stock/update/<int:pk>/', views.StockUpdateView, name='stock-update'),

VIEWS.py

def StockUpdateView(request, pk):
     stock = Stock.objects.get(id=pk)
     form = StockForm(instance=stock)

     if request.method == 'POST':
          form = StockForm(request.POST, instance=stock)
          if form.is_valid():
               form.save()
               return redirect('/inventory/stock')
     context = {"form": form}
     return render(request, 'inventory/update-stock.html', context)

TEMPLATE.html

<form action="" method="POST" class="row g-3">

Stock update form:

        {% csrf_token %}
        {% for field in form %}

          {{field}}

        {% endfor %}

MODEL.py

class Stock(models.Model):
    class Meta:
        verbose_name_plural = "Stocks"

    name = models.ForeignKey(Warehouse, on_delete=models.CASCADE)
    product_id = models.ForeignKey('products.Product', on_delete=models.CASCADE)
    quantity = models.IntegerField(default=0)
    product_price = models.DecimalField(max_digits=19, decimal_places=2, default=0 ,validators=[MinValueValidator(0)])

    def get_absolute_url(self):
        return reverse("stock-update", args=[self.pk])

    def __str__(self):
        return f"{self.product_id} {self.quantity} {self.product_price}"

I have changed from using the {{ form }} tag to looping over the fields trying to get the name of the related table instead of the IDs.


问:
EmptyBody().onAppear not works when sheet present with item
When I present sheet with .sheet(isPresented... onAppear of EmptyView() triggered
but when I use .sheet(item... then onAppear doesn't trigger. I don't understand what mistake I am doing?

item:

```<code>enum ActiveSheet: Identifiable {
var id: String { UUID().uuidString }
case customA
case customB
}
</code>```

Main View:

```<code>struct ContentView: View {
@State private var activeSheet: ActiveSheet?

var body: some View {
    VStack {
        Button(action: { activeSheet = .customA }) {
            Text("View A")
        }
        Button(action: { activeSheet = .customB }) {
            Text("View B")
        }
    }
    .buttonStyle(.borderedProminent)
    //If I use this .sheet(isPresented... then onAppear triggers, but not with item
    .sheet(item: $activeSheet) { item in
        switch item {
        case .customA:
            CustomViewA()
        case .customB:
            CustomViewB()
        }
      }
    }
  }
</code>```

Empty Views:

```<code>    struct CustomViewA: View {
     var body: some View {
        EmptyView()
            .onAppear {
                print("OnAppear")
            }
         }
       }
   struct CustomViewB: View {
    var body: some View {
        EmptyView()
            .onAppear {
                print("OnAppear")
            }
         }
      }
</code>```

Body:
When I present sheet with .sheet(isPresented... onAppear of EmptyView() triggered
but when I use .sheet(item... then onAppear doesn't trigger. I don't understand what mistake I am doing?

item:

enum ActiveSheet: Identifiable {
var id: String { UUID().uuidString }
case customA
case customB
}

Main View:

struct ContentView: View {
@State private var activeSheet: ActiveSheet?

var body: some View {
    VStack {
        Button(action: { activeSheet = .customA }) {
            Text("View A")
        }
        Button(action: { activeSheet = .customB }) {
            Text("View B")
        }
    }
    .buttonStyle(.borderedProminent)
    //If I use this .sheet(isPresented... then onAppear triggers, but not with item
    .sheet(item: $activeSheet) { item in
        switch item {
        case .customA:
            CustomViewA()
        case .customB:
            CustomViewB()
        }
      }
    }
  }

Empty Views:

    struct CustomViewA: View {
     var body: some View {
        EmptyView()
            .onAppear {
                print("OnAppear")
            }
         }
       }
   struct CustomViewB: View {
    var body: some View {
        EmptyView()
            .onAppear {
                print("OnAppear")
            }
         }
      }


问:
How to prevent scrolling of body when popup is visible? It should work on iOS mobile also. Popup can be scroll tough
Tried all these option, two frameworks, none works:

import preventScroll from 'prevent-scroll'
import {
    disableBodyScroll,
    enableBodyScroll,
    clearAllBodyScrollLocks,
} from 'body-scroll-lock'

    useEffect(() => {
        document.body.style.overflow = 'hidden'
        document.body.style.touchAction = 'none'

        document.addEventListener('scroll', function (event) {
            event.preventDefault()
        })

        disableBodyScroll()
        preventScroll.on()

        // other approach from here: https://css-tricks.com/prevent-page-scrolling-when-a-modal-is-open/
        document.body.style.position = 'fixed'
        document.body.style.top = `-${window.scrollY}px`

        return () => {
            document.body.style.overflow = 'auto'
            document.body.style.touchAction = 'auto'

            document.removeEventListener('scroll', function (event) {
                event.preventDefault()
            })
            preventScroll.off()

            clearAllBodyScrollLocks()

            document.body.style.position = ''
            document.body.style.top = ''
        }
    }, [])
```

The last approach comes from here will show a black stripe here: https://css-tricks.com/prevent-page-scrolling-when-a-modal-is-open/
Keyboard is not visible on screen shot.

Body:
Tried all these option, two frameworks, none works:

import preventScroll from 'prevent-scroll'
import {
    disableBodyScroll,
    enableBodyScroll,
    clearAllBodyScrollLocks,
} from 'body-scroll-lock'

    useEffect(() => {
        document.body.style.overflow = 'hidden'
        document.body.style.touchAction = 'none'

        document.addEventListener('scroll', function (event) {
            event.preventDefault()
        })

        disableBodyScroll()
        preventScroll.on()

        // other approach from here: https://css-tricks.com/prevent-page-scrolling-when-a-modal-is-open/
        document.body.style.position = 'fixed'
        document.body.style.top = `-${window.scrollY}px`

        return () => {
            document.body.style.overflow = 'auto'
            document.body.style.touchAction = 'auto'

            document.removeEventListener('scroll', function (event) {
                event.preventDefault()
            })
            preventScroll.off()

            clearAllBodyScrollLocks()

            document.body.style.position = ''
            document.body.style.top = ''
        }
    }, [])

The last approach comes from here will show a black stripe here: https://css-tricks.com/prevent-page-scrolling-when-a-modal-is-open/
Keyboard is not visible on screen shot.


问:
Jquery change link inside iframe tag
I have this code, on each click i want change the link inside the iframe tag.

```<code><div id="video" class="video">
    <iframe width="1030" height="600"
        src="https://www.youtube.com/embed/tgbNymZ7vqY">
    </iframe>
 </div>

 $(document).ready(function(){

 $('#sub-01').click(function(){
    $('iframe src').text('https://www.youtube.com/watch?v=AQPlp-xT-Cc');
 });

});
</code>```

Somebody can help me? Thanks in advance..

Title: Jquery change link inside iframe tag

Body:
I have this code, on each click i want change the link inside the iframe tag.

 $(document).ready(function(){

 $('#sub-01').click(function(){
    $('iframe src').text('https://www.youtube.com/watch?v=AQPlp-xT-Cc');
 });

});

Somebody can help me? Thanks in advance..


问:
Puppeteer opens about:blank page sometimes
I have been experiencing this issue from a long time now. I have a web scraper on a Windows VM and I have it set to run every few hours. It works most of the time but a lot of times Puppeteer just opens this page  and not the site or page I want to open.

Why does that happen and what can be the fix for this?

A simple reproduction for this issue can be this code

import puppeteer from 'puppeteer'
import { scheduleJob } from 'node-schedule';

async function run() {
  const browser = await puppeteer.launch({
    headless: false,
    executablePath: chromePath,
    defaultViewport: null,
    timeout: 0,
    args: ['--no-sandbox', '--start-maximized'],
  });
  const page = await browser.newPage();

  await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, 'webdriver', {
      get: () => false,
    });
  });

  await page.goto('https://aliexpress.com', {
    waitUntil: 'networkidle0',
    timeout: 0,
  });
}

run();
scheduleJob('scrape aliexpress', `0 */${hours} * * *`, run);
```


问:
how to send a File to an REST api
so I have this example REST api:

```<code>https://example-api.com/
</code>```

and for sending a request to make an action on a file, I can do this:

```<code>curl -F "file=@test.txt" https://example-api.com/makeActionOnFile
</code>```

this will take test.txt file and send it to the endpoint, this example is working using curl

How can I do the same thing by making a request on a File object in Dart/Flutter?

Can it be done using the HTTP package?

Thank you

Title: how to send a File to an REST api

Body:
so I have this example REST api:

https://example-api.com/

and for sending a request to make an action on a file, I can do this:

curl -F "file=@test.txt" https://example-api.com/makeActionOnFile

this will take test.txt file and send it to the endpoint, this example is working using curl

How can I do the same thing by making a request on a File object in Dart/Flutter?

Can it be done using the HTTP package?

Thank you


问:
Use cases of a copy assignment operator that returns const
I have seen code that defines a copy assignment operator to return a const reference, e.g.

```<code>const MyClass & operator= (const MyClass &);
</code>```

I'm confused about the intention, and how such operator can be used.

For example, let's say I use it to do something like a = b (a and b are objects of MyClass). Wouldn't that require a to have been declared as const, and if so, wouldn't that mean that I cannot modify a? (i.e. what's the point?)

Body:
I have seen code that defines a copy assignment operator to return a const reference, e.g.

const MyClass & operator= (const MyClass &);

I'm confused about the intention, and how such operator can be used.

For example, let's say I use it to do something like a = b (a and b are objects of MyClass). Wouldn't that require a to have been declared as const, and if so, wouldn't that mean that I cannot modify a? (i.e. what's the point?)


问:
Mapbox Autosuggest JS Filter full addresses
When using the mapbox js autofill component, I am trying to only retrieve full addresses and not include streets / highways in the autosuggest response.

How do I initialize autofill to only include full addresses?

```<code>    autofillCollection = mapboxsearch.autofill({
        options: {
            country: 'us',
            language: 'en',
        }
    });
</code>```

Body:
When using the mapbox js autofill component, I am trying to only retrieve full addresses and not include streets / highways in the autosuggest response.

How do I initialize autofill to only include full addresses?

    autofillCollection = mapboxsearch.autofill({
        options: {
            country: 'us',
            language: 'en',
        }
    });