问:
Implement async socket recvmsg for RX and TX timestamping in Rust

Objective

This project is a test for using AsyncFd (from tokio) to wrap a socket file descriptor.

Code example

Socket file:

use nix::{
    cmsg_space,
    sys::{
        socket::{ControlMessageOwned, MsgFlags, SockaddrIn},
        time::TimeSpec,
    },
};
use tokio::io::unix::{AsyncFd, TryIoError};

use std::{
    io::{IoSlice, IoSliceMut},
    marker::PhantomData,
    os::unix::prelude::{AsRawFd, RawFd},
};

pub struct AsyncSocket<'a, T: 'a> {
    inner: AsyncFd<RawFd>,
    phantom: PhantomData<&'a T>,
}

impl<'a, T> AsyncSocket<'a, T> {
    pub fn new(fd: RawFd) -> tokio::io::Result<Self> {
        Ok(Self {
            // inner: AsyncFd::new(fd)?,
            inner: AsyncFd::new(fd)?,
            phantom: PhantomData,
        })
    }

    pub async fn write_to(
        &'a self,
        buffer: &'a [IoSlice<'_>; 1],
        socket_address: &SockaddrIn,
    ) -> Result<usize, TryIoError> {
        let mut guard = self.inner.writable().await.unwrap();
        let flags = MsgFlags::empty();
        let cmsgs = &mut [];
        match guard.try_io(|inner| {
            match nix::sys::socket::sendmsg(
                inner.as_raw_fd(),
                buffer,
                cmsgs,
                flags,
                Some(socket_address),
            ) {
                Ok(read_bytes) => Ok(read_bytes),
                Err(would_block) => Err(std::io::Error::from_raw_os_error(would_block as i32)),
            }
        }) {
            Ok(res) => match res {
                Ok(read_bytes) => Ok(read_bytes),
                Err(e) => {
                    eprintln!("Error {}", e);
                    Ok(0)
                }
            },
            Err(e) => Err(e),
        }
    }

    pub async fn read(
        &'a self,
        buffer: &'a mut [IoSliceMut<'_>; 1],
        flags: MsgFlags,
    ) -> Result<usize, TryIoError> {
        buffer[0].fill(0);
        let mut guard = self.inner.readable().await.unwrap();

        match guard.try_io(|inner| {
            let sys_time = nix::time::clock_gettime(nix::time::ClockId::CLOCK_REALTIME).unwrap();
            println!("Real clock {:?}", sys_time);
            println!("FLAG = {:?}", flags);
            match nix::sys::socket::recvmsg::<()>(
                inner.as_raw_fd(),
                buffer,
                Some(&mut cmsg_space!(
                    nix::sys::socket::MsgFlags,
                    nix::sys::socket::TimestampingFlag,
                    nix::sys::socket::SockFlag
                )),
                flags,
            ) {
                Ok(result) => {
                    let mut ts = TimeSpec::new(0, 0);
                    let mut _thw = TimeSpec::new(0, 0);
                    let control_messages: Vec<ControlMessageOwned> = result.cmsgs().collect();

                    println!("Control message length = {}", control_messages.len());
                    for c in control_messages {
                        match c {
                            ControlMessageOwned::ScmTimestampsns(timestamps) => {
                                _thw = timestamps.hw_raw;
                                ts = timestamps.system;
                                println!("Timestamps {:?}", timestamps);
                            }
                            ControlMessageOwned::ScmRights(_) => println!("ScmRights"),
                            ControlMessageOwned::ScmCredentials(_) => println!("ScmCredentials"),
                            ControlMessageOwned::ScmTimestamp(_) => println!("ScmTimestamp"),
                            ControlMessageOwned::ScmTimestampns(_) => println!("ScmTimestampns"),
                            ControlMessageOwned::Ipv4PacketInfo(_) => println!("Ipv4PacketInfo"),
                            ControlMessageOwned::Ipv6PacketInfo(_) => println!("Ipv6PacketInfo"),
                            ControlMessageOwned::Ipv4OrigDstAddr(_) => println!("Ipv4OrigDstAddr"),
                            ControlMessageOwned::Ipv6OrigDstAddr(_) => println!("Ipv6OrigDstAddr"),
                            ControlMessageOwned::UdpGroSegments(_) => println!("UdpGroSegments"),
                            ControlMessageOwned::RxqOvfl(_) => println!("RxqOvfl"),
                            ControlMessageOwned::Ipv4RecvErr(a, b) => {
                                println!("Received ipv4 Err {:?} from {:?}", a, b);
                            }
                            ControlMessageOwned::Ipv6RecvErr(_, _) => println!("Ipv6RecvErr"),
                            _ => println!("Other"),
                        }
                    }

                    let soft_diff = diff_systime(ts, sys_time);

                    // let hw_diff = diff_systime(thw, sys_time);

                    if soft_diff != sys_time {
                        let delta = std::time::Duration::from(soft_diff).as_micros();
                        println!("Soft Delta is {}", delta);
                    }
                    // } else if hw_diff != sys_time {
                    // //     let delta = std::time::Duration::from(hw_diff).as_micros();
                    // //     println!("Hard Delta is {}", delta);
                    // // }

                    return Ok(result.bytes);
                }
                Err(errno) => {
                    match errno {
                        nix::errno::Errno::EAGAIN => println!("EAGAIN Error"),
                        _ => println!("Other error {:?}", errno),
                    }
                    let error = std::io::Error::from_raw_os_error(errno as i32);
                    Err(error)
                }
            }
        }) {
            Ok(res) => match res {
                Ok(read_bytes) => Ok(read_bytes),
                Err(_e) => {
                    println!("Error from socket {:?}", std::io::Error::last_os_error());
                    Ok(0)
                }
            },
            Err(e) => {
                println!("Guard error {:?}", std::io::Error::last_os_error());
                Err(e)
            }
        }
        // }
    }
}

impl<'a, T> AsRawFd for AsyncSocket<'a, T> {
    fn as_raw_fd(&self) -> RawFd {
        self.inner.as_raw_fd()
    }
}

impl<'a, T> Drop for AsyncSocket<'a, T> {
    fn drop(&mut self) {
        let fd = self.inner.as_raw_fd();
        unsafe { nix::libc::close(fd) };
    }
}

fn diff_systime(first: TimeSpec, second: TimeSpec) -> TimeSpec {
    if second > first {
        second - first
    } else {
        first - second
    }
}
```
<p>Error.rs</p>
<pre class="lang-rust prettyprint-override"><code>#[derive(thiserror::Error, Debug)]
pub enum LibError {
    AddrParseError(#[from] std::net::AddrParseError),
    #[error(transparent)]
    IO(#[from] std::io::Error),
    OSError(#[from] nix::Error),
}

impl std::fmt::Display for LibError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", &self)
    }
}
</code>```

Main.rs:

use std::{
    io::{IoSlice, IoSliceMut},
    str::FromStr,
    sync::{
        atomic::{AtomicU8, Ordering},
        Arc,
    },
    time::Duration,
};
mod error;
mod socket;

use nix::sys::socket::{
    bind, setsockopt,
    sockopt::{self},
    AddressFamily, MsgFlags, SockFlag, SockProtocol, SockType, SockaddrIn, TimestampingFlag,
};
use socket::AsyncSocket;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let local_sock_addr = SockaddrIn::from_str("0.0.0.0:6790").unwrap();
    let local_sock_addr1 = SockaddrIn::from_str("192.168.1.84:44581").unwrap();

    let send_sock_addr = SockaddrIn::from_str("192.168.1.123:6790").unwrap();

    let rsock = nix::sys::socket::socket(
        AddressFamily::Inet,
        SockType::Datagram,
        SockFlag::all(),
        SockProtocol::Udp,
    )?;

    let ssock = nix::sys::socket::socket(
        AddressFamily::Inet,
        SockType::Datagram,
        SockFlag::all(),
        SockProtocol::Udp,
    )?;

    // let sock_txtime = sock_txtime {
    //     clockid: nix::time::ClockId::CLOCK_MONOTONIC.as_raw(),
    //     flags: SOF_TXTIME_REPORT_ERRORS,
    // };
    setsockopt(rsock, sockopt::Timestamping, &TimestampingFlag::all())?;
    setsockopt(ssock, sockopt::Timestamping, &TimestampingFlag::all())?;
    // setsockopt(ssock, sockopt::ReuseAddr, &true)?;
    // setsockopt(rsock, sockopt::ReuseAddr, &true)?;

    // setsockopt(ssock, sockopt::TxTime, &sock_txtime)?;
    bind(ssock, &local_sock_addr1)?;
    bind(rsock, &local_sock_addr)?;

    let recv_socket: AsyncSocket<i32> = AsyncSocket::new(rsock)?;
    let send_socket: AsyncSocket<i32> = AsyncSocket::new(ssock)?;
    let atomic_i = Arc::new(AtomicU8::new(1));

    let mut read_buf = [0u8; 1024];
    let mut iov2 = [IoSliceMut::new(&mut read_buf)];

    // let mut rbuf1 = [0u8; 1024];
    let mut rbuf2 = [0u8; 1024];
    // let mut iov3 = [IoSliceMut::new(&mut rbuf1)];
    let mut iov4 = [IoSliceMut::new(&mut rbuf2)];

    loop {
        tokio::select! {
            read = recv_socket.read(&mut iov2, MsgFlags::empty()) => {
                match read {
                    Ok(v) => {
                        println!("Recv sock Received {} bytes in mes {:?}", v, iov2[0].iter().take(v).collect::<Vec<&u8>>());
                        let i = atomic_i.load(Ordering::Relaxed);
                        let sbuf: Vec<u8> = (1u8..=i).map(|el| el).collect();

                        let iov1 = [IoSlice::new(&mut sbuf.as_slice())];
                        tokio::time::sleep(Duration::from_millis(15)).await;

                        let _ = recv_socket.write_to(&iov1, &local_sock_addr1).await;

                    },
                    Err(e) => println!("Recv Err {:?}", e),
                }
            },
            _tick = tokio::time::sleep(Duration::from_millis(500)) => {
                // println!("Tick");
                let i = atomic_i.load(Ordering::Relaxed);
                if i == 3 {
                    continue;
                    // In case you want the sending to last forever

                    // atomic_i
                    //     .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| Some(n - n))
                    //     .unwrap();
                    // break;
                }
                let sbuf: Vec<u8> = (1u8..=i).map(|el| el).collect();
                let iov1 = [IoSlice::new(&mut sbuf.as_slice())];
                let _ = send_socket.write_to(&iov1, &send_sock_addr).await;
                // Calling read here results in a deadlock
                println!("Message {} sent", i);
                atomic_i.fetch_add(1, Ordering::Relaxed);
            },
            read2 = send_socket.read(&mut iov4, MsgFlags::empty()) => {
                match read2 {
                                Ok(v) => {
                                    println!("Send sock Received {} bytes in mes {:?}", v, iov4[0].iter().take(v).collect::<Vec<&u8>>());
                                    // This second read call is done to retrieve any messages present in the Error queue (timestamps are there)
                                    // match send_socket.read(&mut iov3, MsgFlags::MSG_ERRQUEUE).await {
                                    //     Ok(v) => println!("Send sock Received from Error queue {} bytes in mes {:?}", v, iov3[0].iter().take(v).collect::<Vec<&u8>>()),
                                    //     Err(e) => println!("Send Err {:?}", e),
                                    // }
                                 },
                                Err(e) => println!("Send Err {:?}", e),
                            }
            },
            // Adding this entry results in very inconsistent behavior for receiving Tx timestamps
            // read1 = send_socket.read(&mut iov3, MsgFlags::MSG_ERRQUEUE) => {
            //     match read1 {
                                // Ok(v) => println!("Send sock Received from Error queue {} bytes in mes {:?}", v, iov3[0].iter().take(v).collect::<Vec<&u8>>()),
                                // Err(e) => println!("Send Err {:?}", e),
            //                 }
            // },

        }
        println!("\n")
    }

    // Ok(())
}
```
<p>Cargo.toml:</p>
<pre class="lang-ini prettyprint-override"><code>[package]
name = "socket-timestamp-test"
version = "0.1.0"
edition = "2021"

[dependencies]
bytes = "1.3.0"
futures = "0.3.25"
log = "0.4.17"
mio = { version = "0.8.5", features = ["os-ext"] }
nix = { version = "0.26.1", features = ["socket"] }
num_enum = "0.5.7"
thiserror = "1.0.37"
tokio = { version = "1.2", features = [
    "sync",
    "net",
    "macros",
    "rt-multi-thread",
    "time",
] }
</code>```

Motivation

The motivation is to be able to access configuration that is not present in common user network libraries (such as tokio, std, socket2, smoltcp, etc), such as retrieving timestamp messages for RX and TX packets.
These values can be retrieved with a call to libc's recvmsg in a correctly configured socket (configured with SOF timestamping flags).
Tx timestamps can be retrieved from the Socket Error Queue, by accessing the socket's control messages.

Current problems

Tx timestamps are stored (when MSG_ERRQUEUE is used) in the error queue, but polling of the socket only happens when a message is received buffer. This results in the following behavior:

Socket 1 sends message
Timestamping stuff is queued
... no polling is triggered and the message is not retrieved

Socket 1 receives the response
If recvmsg is called with MSG_ERRQUEUE:

Socket is polled until all timestamps from the sent messages are received

If recvmsg is called without MSG_ERRQUEUE:

Socket is polled and receives the payload of the response, but no data from error queue is read (which is the expected behavior)

If two calls to recvmsg are placed in the select! closure, it results in inconsistent behavior where sometimes you get error queued messages but sometimes you don't. This means that a second another call to recvmsg is required to receive the remaining Tx timestamps.

Intended overall behavior

If socket is configured to generate TX timestamps, and the Error queue has received such information, the async runtime should automatically poll the results.
When data comes in the normal recv buffer, the async runtime should also poll these results.

Possible solutions

One way to fix it would be to poll the socket with recvmsg(...MSG_ERRQUEUE) after sending the packet. But this is cumbersome and due to scheduling, the recvmsg call can't be done immediately after the send. Ideally I would like polling to happen when there is a message in the recv buffer and when there is no message in the recv buffer, but there is a queued entry in the Error queue.
Another solution would be to place a recvmsg with MSG_ERRQUEUE right after the recvmsg (without MSG_ERRQUE). The problem here is that if the socket has not received anything, we won't poll the error queue as well.

Request for comments

I would like help in figuring out how to retrieve TX timestamps without having to manually call recvmsg (...MSG_ERRQUEUE) to get it.

I'm open to suggestions on different approaches to the problem, i.e., without tokio AsyncFd.

Body:
Objective

This project is a test for using AsyncFd (from tokio) to wrap a socket file descriptor.

Code example

Socket file:

use nix::{
    cmsg_space,
    sys::{
        socket::{ControlMessageOwned, MsgFlags, SockaddrIn},
        time::TimeSpec,
    },
};
use tokio::io::unix::{AsyncFd, TryIoError};

use std::{
    io::{IoSlice, IoSliceMut},
    marker::PhantomData,
    os::unix::prelude::{AsRawFd, RawFd},
};

pub struct AsyncSocket<'a, T: 'a> {
    inner: AsyncFd<RawFd>,
    phantom: PhantomData<&'a T>,
}

impl<'a, T> AsyncSocket<'a, T> {
    pub fn new(fd: RawFd) -> tokio::io::Result<Self> {
        Ok(Self {
            // inner: AsyncFd::new(fd)?,
            inner: AsyncFd::new(fd)?,
            phantom: PhantomData,
        })
    }

    pub async fn write_to(
        &'a self,
        buffer: &'a [IoSlice<'_>; 1],
        socket_address: &SockaddrIn,
    ) -> Result<usize, TryIoError> {
        let mut guard = self.inner.writable().await.unwrap();
        let flags = MsgFlags::empty();
        let cmsgs = &mut [];
        match guard.try_io(|inner| {
            match nix::sys::socket::sendmsg(
                inner.as_raw_fd(),
                buffer,
                cmsgs,
                flags,
                Some(socket_address),
            ) {
                Ok(read_bytes) => Ok(read_bytes),
                Err(would_block) => Err(std::io::Error::from_raw_os_error(would_block as i32)),
            }
        }) {
            Ok(res) => match res {
                Ok(read_bytes) => Ok(read_bytes),
                Err(e) => {
                    eprintln!("Error {}", e);
                    Ok(0)
                }
            },
            Err(e) => Err(e),
        }
    }

    pub async fn read(
        &'a self,
        buffer: &'a mut [IoSliceMut<'_>; 1],
        flags: MsgFlags,
    ) -> Result<usize, TryIoError> {
        buffer[0].fill(0);
        let mut guard = self.inner.readable().await.unwrap();

        match guard.try_io(|inner| {
            let sys_time = nix::time::clock_gettime(nix::time::ClockId::CLOCK_REALTIME).unwrap();
            println!("Real clock {:?}", sys_time);
            println!("FLAG = {:?}", flags);
            match nix::sys::socket::recvmsg::<()>(
                inner.as_raw_fd(),
                buffer,
                Some(&mut cmsg_space!(
                    nix::sys::socket::MsgFlags,
                    nix::sys::socket::TimestampingFlag,
                    nix::sys::socket::SockFlag
                )),
                flags,
            ) {
                Ok(result) => {
                    let mut ts = TimeSpec::new(0, 0);
                    let mut _thw = TimeSpec::new(0, 0);
                    let control_messages: Vec<ControlMessageOwned> = result.cmsgs().collect();

                    println!("Control message length = {}", control_messages.len());
                    for c in control_messages {
                        match c {
                            ControlMessageOwned::ScmTimestampsns(timestamps) => {
                                _thw = timestamps.hw_raw;
                                ts = timestamps.system;
                                println!("Timestamps {:?}", timestamps);
                            }
                            ControlMessageOwned::ScmRights(_) => println!("ScmRights"),
                            ControlMessageOwned::ScmCredentials(_) => println!("ScmCredentials"),
                            ControlMessageOwned::ScmTimestamp(_) => println!("ScmTimestamp"),
                            ControlMessageOwned::ScmTimestampns(_) => println!("ScmTimestampns"),
                            ControlMessageOwned::Ipv4PacketInfo(_) => println!("Ipv4PacketInfo"),
                            ControlMessageOwned::Ipv6PacketInfo(_) => println!("Ipv6PacketInfo"),
                            ControlMessageOwned::Ipv4OrigDstAddr(_) => println!("Ipv4OrigDstAddr"),
                            ControlMessageOwned::Ipv6OrigDstAddr(_) => println!("Ipv6OrigDstAddr"),
                            ControlMessageOwned::UdpGroSegments(_) => println!("UdpGroSegments"),
                            ControlMessageOwned::RxqOvfl(_) => println!("RxqOvfl"),
                            ControlMessageOwned::Ipv4RecvErr(a, b) => {
                                println!("Received ipv4 Err {:?} from {:?}", a, b);
                            }
                            ControlMessageOwned::Ipv6RecvErr(_, _) => println!("Ipv6RecvErr"),
                            _ => println!("Other"),
                        }
                    }

                    let soft_diff = diff_systime(ts, sys_time);

                    // let hw_diff = diff_systime(thw, sys_time);

                    if soft_diff != sys_time {
                        let delta = std::time::Duration::from(soft_diff).as_micros();
                        println!("Soft Delta is {}", delta);
                    }
                    // } else if hw_diff != sys_time {
                    // //     let delta = std::time::Duration::from(hw_diff).as_micros();
                    // //     println!("Hard Delta is {}", delta);
                    // // }

                    return Ok(result.bytes);
                }
                Err(errno) => {
                    match errno {
                        nix::errno::Errno::EAGAIN => println!("EAGAIN Error"),
                        _ => println!("Other error {:?}", errno),
                    }
                    let error = std::io::Error::from_raw_os_error(errno as i32);
                    Err(error)
                }
            }
        }) {
            Ok(res) => match res {
                Ok(read_bytes) => Ok(read_bytes),
                Err(_e) => {
                    println!("Error from socket {:?}", std::io::Error::last_os_error());
                    Ok(0)
                }
            },
            Err(e) => {
                println!("Guard error {:?}", std::io::Error::last_os_error());
                Err(e)
            }
        }
        // }
    }
}

impl<'a, T> AsRawFd for AsyncSocket<'a, T> {
    fn as_raw_fd(&self) -> RawFd {
        self.inner.as_raw_fd()
    }
}

impl<'a, T> Drop for AsyncSocket<'a, T> {
    fn drop(&mut self) {
        let fd = self.inner.as_raw_fd();
        unsafe { nix::libc::close(fd) };
    }
}

fn diff_systime(first: TimeSpec, second: TimeSpec) -> TimeSpec {
    if second > first {
        second - first
    } else {
        first - second
    }
}

Error.rs

#[derive(thiserror::Error, Debug)]
pub enum LibError {
    AddrParseError(#[from] std::net::AddrParseError),
    #[error(transparent)]
    IO(#[from] std::io::Error),
    OSError(#[from] nix::Error),
}

impl std::fmt::Display for LibError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", &self)
    }
}

Main.rs:

use std::{
    io::{IoSlice, IoSliceMut},
    str::FromStr,
    sync::{
        atomic::{AtomicU8, Ordering},
        Arc,
    },
    time::Duration,
};
mod error;
mod socket;

use nix::sys::socket::{
    bind, setsockopt,
    sockopt::{self},
    AddressFamily, MsgFlags, SockFlag, SockProtocol, SockType, SockaddrIn, TimestampingFlag,
};
use socket::AsyncSocket;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let local_sock_addr = SockaddrIn::from_str("0.0.0.0:6790").unwrap();
    let local_sock_addr1 = SockaddrIn::from_str("192.168.1.84:44581").unwrap();

    let send_sock_addr = SockaddrIn::from_str("192.168.1.123:6790").unwrap();

    let rsock = nix::sys::socket::socket(
        AddressFamily::Inet,
        SockType::Datagram,
        SockFlag::all(),
        SockProtocol::Udp,
    )?;

    let ssock = nix::sys::socket::socket(
        AddressFamily::Inet,
        SockType::Datagram,
        SockFlag::all(),
        SockProtocol::Udp,
    )?;

    // let sock_txtime = sock_txtime {
    //     clockid: nix::time::ClockId::CLOCK_MONOTONIC.as_raw(),
    //     flags: SOF_TXTIME_REPORT_ERRORS,
    // };
    setsockopt(rsock, sockopt::Timestamping, &TimestampingFlag::all())?;
    setsockopt(ssock, sockopt::Timestamping, &TimestampingFlag::all())?;
    // setsockopt(ssock, sockopt::ReuseAddr, &true)?;
    // setsockopt(rsock, sockopt::ReuseAddr, &true)?;

    // setsockopt(ssock, sockopt::TxTime, &sock_txtime)?;
    bind(ssock, &local_sock_addr1)?;
    bind(rsock, &local_sock_addr)?;

    let recv_socket: AsyncSocket<i32> = AsyncSocket::new(rsock)?;
    let send_socket: AsyncSocket<i32> = AsyncSocket::new(ssock)?;
    let atomic_i = Arc::new(AtomicU8::new(1));

    let mut read_buf = [0u8; 1024];
    let mut iov2 = [IoSliceMut::new(&mut read_buf)];

    // let mut rbuf1 = [0u8; 1024];
    let mut rbuf2 = [0u8; 1024];
    // let mut iov3 = [IoSliceMut::new(&mut rbuf1)];
    let mut iov4 = [IoSliceMut::new(&mut rbuf2)];

    loop {
        tokio::select! {
            read = recv_socket.read(&mut iov2, MsgFlags::empty()) => {
                match read {
                    Ok(v) => {
                        println!("Recv sock Received {} bytes in mes {:?}", v, iov2[0].iter().take(v).collect::<Vec<&u8>>());
                        let i = atomic_i.load(Ordering::Relaxed);
                        let sbuf: Vec<u8> = (1u8..=i).map(|el| el).collect();

                        let iov1 = [IoSlice::new(&mut sbuf.as_slice())];
                        tokio::time::sleep(Duration::from_millis(15)).await;

                        let _ = recv_socket.write_to(&iov1, &local_sock_addr1).await;

                    },
                    Err(e) => println!("Recv Err {:?}", e),
                }
            },
            _tick = tokio::time::sleep(Duration::from_millis(500)) => {
                // println!("Tick");
                let i = atomic_i.load(Ordering::Relaxed);
                if i == 3 {
                    continue;
                    // In case you want the sending to last forever

                    // atomic_i
                    //     .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| Some(n - n))
                    //     .unwrap();
                    // break;
                }
                let sbuf: Vec<u8> = (1u8..=i).map(|el| el).collect();
                let iov1 = [IoSlice::new(&mut sbuf.as_slice())];
                let _ = send_socket.write_to(&iov1, &send_sock_addr).await;
                // Calling read here results in a deadlock
                println!("Message {} sent", i);
                atomic_i.fetch_add(1, Ordering::Relaxed);
            },
            read2 = send_socket.read(&mut iov4, MsgFlags::empty()) => {
                match read2 {
                                Ok(v) => {
                                    println!("Send sock Received {} bytes in mes {:?}", v, iov4[0].iter().take(v).collect::<Vec<&u8>>());
                                    // This second read call is done to retrieve any messages present in the Error queue (timestamps are there)
                                    // match send_socket.read(&mut iov3, MsgFlags::MSG_ERRQUEUE).await {
                                    //     Ok(v) => println!("Send sock Received from Error queue {} bytes in mes {:?}", v, iov3[0].iter().take(v).collect::<Vec<&u8>>()),
                                    //     Err(e) => println!("Send Err {:?}", e),
                                    // }
                                 },
                                Err(e) => println!("Send Err {:?}", e),
                            }
            },
            // Adding this entry results in very inconsistent behavior for receiving Tx timestamps
            // read1 = send_socket.read(&mut iov3, MsgFlags::MSG_ERRQUEUE) => {
            //     match read1 {
                                // Ok(v) => println!("Send sock Received from Error queue {} bytes in mes {:?}", v, iov3[0].iter().take(v).collect::<Vec<&u8>>()),
                                // Err(e) => println!("Send Err {:?}", e),
            //                 }
            // },

        }
        println!("\n")
    }

    // Ok(())
}

Cargo.toml:

[package]
name = "socket-timestamp-test"
version = "0.1.0"
edition = "2021"

[dependencies]
bytes = "1.3.0"
futures = "0.3.25"
log = "0.4.17"
mio = { version = "0.8.5", features = ["os-ext"] }
nix = { version = "0.26.1", features = ["socket"] }
num_enum = "0.5.7"
thiserror = "1.0.37"
tokio = { version = "1.2", features = [
    "sync",
    "net",
    "macros",
    "rt-multi-thread",
    "time",
] }

Motivation

The motivation is to be able to access configuration that is not present in common user network libraries (such as tokio, std, socket2, smoltcp, etc), such as retrieving timestamp messages for RX and TX packets.
These values can be retrieved with a call to libc's recvmsg in a correctly configured socket (configured with SOF timestamping flags).
Tx timestamps can be retrieved from the Socket Error Queue, by accessing the socket's control messages.

Current problems

Tx timestamps are stored (when MSG_ERRQUEUE is used) in the error queue, but polling of the socket only happens when a message is received buffer. This results in the following behavior:

Socket 1 sends message
Timestamping stuff is queued
... no polling is triggered and the message is not retrieved

Socket 1 receives the response
If recvmsg is called with MSG_ERRQUEUE:

Socket is polled until all timestamps from the sent messages are received

If recvmsg is called without MSG_ERRQUEUE:

Socket is polled and receives the payload of the response, but no data from error queue is read (which is the expected behavior)

If two calls to recvmsg are placed in the select! closure, it results in inconsistent behavior where sometimes you get error queued messages but sometimes you don't. This means that a second another call to recvmsg is required to receive the remaining Tx timestamps.

Intended overall behavior

If socket is configured to generate TX timestamps, and the Error queue has received such information, the async runtime should automatically poll the results.
When data comes in the normal recv buffer, the async runtime should also poll these results.

Possible solutions

One way to fix it would be to poll the socket with recvmsg(...MSG_ERRQUEUE) after sending the packet. But this is cumbersome and due to scheduling, the recvmsg call can't be done immediately after the send. Ideally I would like polling to happen when there is a message in the recv buffer and when there is no message in the recv buffer, but there is a queued entry in the Error queue.
Another solution would be to place a recvmsg with MSG_ERRQUEUE right after the recvmsg (without MSG_ERRQUE). The problem here is that if the socket has not received anything, we won't poll the error queue as well.

Request for comments

I would like help in figuring out how to retrieve TX timestamps without having to manually call recvmsg (...MSG_ERRQUEUE) to get it.

I'm open to suggestions on different approaches to the problem, i.e., without tokio AsyncFd.


来源: stackexchange

问:
GCP - "Terraform Import" on VPC SC Perimeter removing Access List
I am trying to import VPC SC Perimeter in to terraform state, but the plan shows removing one Access Level(test_ent_perim_access_002) in the perimeter, not sure why. Also Access List "test_ent_perim_access_001" is getting removed and again added.

Below is the resource

```<code>resource "google_access_context_manager_service_perimeter" "test-ent-prod-perim-001" {
    parent         = "accessPolicies/263896276372"
    name           = "accessPolicies/263896276372/servicePerimeters/test_ent_prod_perim_001"
    title          = "test_ent_prod_perim_001"
    description = "Test Org VPC SC perimeter"
    perimeter_type = "PERIMETER_TYPE_REGULAR"
    status {
      resources = ["7654356728263"]
      restricted_services = ["bigquery.googleapis.com"]
          access_levels       = [
              "accessPolicies/263896276372/accessLevels/test_onprem_ipwhitelist",
              "accessPolicies/263896276372/accessLevels/test_ent_cmn_perim_access_001",
              "accessPolicies/263896276372/accessLevels/test_ent_perim_access_001",
              "accessPolicies/263896276372/accessLevels/test_ent_perim_access_002",
              ]
    }
  }
</code>```

Below is the import command

```<code>- terraform import --var-file=$VARS --var-file=$BACKEND --var-file=vars/$ENV/terraform.tfvars google_access_context_manager_service_perimeter.test-ent-prod-perim-001 accessPolicies/263896276372/servicePerimeters/test_ent_prod_perim_001
</code>```

Below is the plan where it shows the removal of Access Level

```<code>Terraform will perform the following actions:
  # google_access_context_manager_service_perimeter.test-ent-prod-perim-001 will be updated in-place
  ~ resource "google_access_context_manager_service_perimeter" "test-ent-prod-perim-001" {
      ~ description               = "Perimeter shielding projects" -> "Prod VPC perimeter"
        id                        = "accessPolicies/263896276372/servicePerimeters/test_ent_prod_perim_001"
        name                      = "accessPolicies/263896276372/servicePerimeters/test_ent_prod_perim_001"
        # (4 unchanged attributes hidden)
      ~ status {
          ~ access_levels       = [
              - "accessPolicies/263896276372/accessLevels/test_ent_perim_access_001",
                "accessPolicies/263896276372/accessLevels/test_onprem_ipwhitelist",
                # (1 unchanged element hidden)
                "accessPolicies/263896276372/accessLevels/test_ent_perim_access_002",
              - "accessPolicies/263896276372/accessLevels/test_ent_perim_access_002",
              + "accessPolicies/263896276372/accessLevels/test_ent_perim_access_001",
            ]
            # (2 unchanged attributes hidden)
        }
        # (1 unchanged block hidden)
    }
Plan: 0 to add, 1 to change, 0 to destroy.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to import VPC SC Perimeter in to terraform state, but the plan shows removing one Access Level(test_ent_perim_access_002) in the perimeter, not sure why. Also Access List "test_ent_perim_access_001" is getting removed and again added.

Below is the resource

resource "google_access_context_manager_service_perimeter" "test-ent-prod-perim-001" {
    parent         = "accessPolicies/263896276372"
    name           = "accessPolicies/263896276372/servicePerimeters/test_ent_prod_perim_001"
    title          = "test_ent_prod_perim_001"
    description = "Test Org VPC SC perimeter"
    perimeter_type = "PERIMETER_TYPE_REGULAR"
    status {
      resources = ["7654356728263"]
      restricted_services = ["bigquery.googleapis.com"]
          access_levels       = [
              "accessPolicies/263896276372/accessLevels/test_onprem_ipwhitelist",
              "accessPolicies/263896276372/accessLevels/test_ent_cmn_perim_access_001",
              "accessPolicies/263896276372/accessLevels/test_ent_perim_access_001",
              "accessPolicies/263896276372/accessLevels/test_ent_perim_access_002",
              ]
    }
  }

Below is the import command

- terraform import --var-file=$VARS --var-file=$BACKEND --var-file=vars/$ENV/terraform.tfvars google_access_context_manager_service_perimeter.test-ent-prod-perim-001 accessPolicies/263896276372/servicePerimeters/test_ent_prod_perim_001

Below is the plan where it shows the removal of Access Level

Terraform will perform the following actions:
  # google_access_context_manager_service_perimeter.test-ent-prod-perim-001 will be updated in-place
  ~ resource "google_access_context_manager_service_perimeter" "test-ent-prod-perim-001" {
      ~ description               = "Perimeter shielding projects" -> "Prod VPC perimeter"
        id                        = "accessPolicies/263896276372/servicePerimeters/test_ent_prod_perim_001"
        name                      = "accessPolicies/263896276372/servicePerimeters/test_ent_prod_perim_001"
        # (4 unchanged attributes hidden)
      ~ status {
          ~ access_levels       = [
              - "accessPolicies/263896276372/accessLevels/test_ent_perim_access_001",
                "accessPolicies/263896276372/accessLevels/test_onprem_ipwhitelist",
                # (1 unchanged element hidden)
                "accessPolicies/263896276372/accessLevels/test_ent_perim_access_002",
              - "accessPolicies/263896276372/accessLevels/test_ent_perim_access_002",
              + "accessPolicies/263896276372/accessLevels/test_ent_perim_access_001",
            ]
            # (2 unchanged attributes hidden)
        }
        # (1 unchanged block hidden)
    }
Plan: 0 to add, 1 to change, 0 to destroy.


问:
How to search with codes in React site
I have this page link with ordering codes:

```<code>https://example.com/en/search-some-products?query=my-product-0-11
</code>```

You can see I am passing my-product-0-11 in above URL (-0-11 is some codes) and when I hit for search it shows me no result and when I removed those codes and pass only my-product and it shows my product which has name My Product.

I want to show same product even I pass product name with: my-product-0-11.

Below is my code syntax:

```<code>const Results = connectStateResults(
    ({ searchState, searchResults, children }) =>
      searchResults && searchResults.nbHits !== 0 ? (
        children
      ) : (
        <div>No results have been found for {searchState.query}.</div>
      )
  );
</code>```

When I search with my-product-0-11 it says: No results have been found for as you can also see in my code snippet above.

Title: How to search with codes in React site

Body:
I have this page link with ordering codes:

https://example.com/en/search-some-products?query=my-product-0-11

You can see I am passing my-product-0-11 in above URL (-0-11 is some codes) and when I hit for search it shows me no result and when I removed those codes and pass only my-product and it shows my product which has name My Product.

I want to show same product even I pass product name with: my-product-0-11.

Below is my code syntax:

const Results = connectStateResults(
    ({ searchState, searchResults, children }) =>
      searchResults && searchResults.nbHits !== 0 ? (
        children
      ) : (

No results have been found for {searchState.query}.

      )
  );

When I search with my-product-0-11 it says: No results have been found for as you can also see in my code snippet above.


问:
nodejs list only shows items after refresh
I have a list thats nested inside a list, I made it with NodeJS, Express, EJS and MongoDB.
creating the first list works, however when creating items in the second list, they only appear after I refresh the website or create another item (creating an item automatically refreshes and site), I have struggled with this bug for a few day now, please dont laugh at me if its something stupid I am fairly new and this is my first real project.

```<code>
route for the custom list
</code>```

app.route("/BucketList/:customListID")
.get(function (req, res) {

```<code>    previousRoute = "/BucketList";
    if (req.isAuthenticated()) {
        loggedIn = true;
        const customListID = req.params.customListID;
        const customListName = req.params.customListName
        Country.findOne({ _id: customListID }, function (err, foundList) {
            if (!err) {
                if (!foundList) {
                    res.redirect("/BucketList")
                } else {
                    foundList.save();
                    res.render("list", { customListID: customListID, customListName: customListName, customListCode: foundList.code, newListItems: foundList.items });
                }

            } else {
                console.log(err);
            }

        })
    } else {
        loggedIn = false;
        res.redirect("/login");
    }

})
.post(function (req, res) {
    const customListID = req.params.customListID;
    const customListName = req.params.customListName;
    const itemName = req.body.newItem;

    const item = new Item({
        name: itemName
    });

    Country.findOne({ _id: customListID }, function (err, foundList) {
        foundList.items.push(item);
        foundList.save();
        res.redirect("/BucketList/" + customListID);

    });

})
</code>```

```
```

                            <form class="d-flex justify-content-center align-items-center mb-4"
                                action="/BucketList/<%=customListID%>" method="post">

                                    <input type="text" id="form3" class="form-control form-control-lg" name="newItem"
                                        placeholder="New Item" autocomplete="off" />

                                <button type="submit" class="btn btn-primary btn-lg ms-2" name="list"
                                    value="<%= customListID %>">Add</button>
                            </form>
                            <% newListItems.forEach(function(item) { %>

                                            <input class="form-check-input me-2" type="checkbox" value=""
                                                aria-label="..." />
                                            <%=item.name%>

                                        <form action="/deleteItem" method="post">
                                            <button type="submit" id="item-remove-button" title="Remove item"
                                                name="itemDeleteButton" value="<%= item._id %>"
                                                onchange="this.form.submit()">

                                            </button>
                                            <input type="hidden" name="listID" value="<%= customListID %>"></input>
                                        </form>

                                <% }) %>

```
```
```

Body:
I have a list thats nested inside a list, I made it with NodeJS, Express, EJS and MongoDB.
creating the first list works, however when creating items in the second list, they only appear after I refresh the website or create another item (creating an item automatically refreshes and site), I have struggled with this bug for a few day now, please dont laugh at me if its something stupid I am fairly new and this is my first real project.

route for the custom list

app.route("/BucketList/:customListID")
.get(function (req, res) {

    previousRoute = "/BucketList";
    if (req.isAuthenticated()) {
        loggedIn = true;
        const customListID = req.params.customListID;
        const customListName = req.params.customListName
        Country.findOne({ _id: customListID }, function (err, foundList) {
            if (!err) {
                if (!foundList) {
                    res.redirect("/BucketList")
                } else {
                    foundList.save();
                    res.render("list", { customListID: customListID, customListName: customListName, customListCode: foundList.code, newListItems: foundList.items });
                }

            } else {
                console.log(err);
            }

        })
    } else {
        loggedIn = false;
        res.redirect("/login");
    }

})
.post(function (req, res) {
    const customListID = req.params.customListID;
    const customListName = req.params.customListName;
    const itemName = req.body.newItem;

    const item = new Item({
        name: itemName
    });

    Country.findOne({ _id: customListID }, function (err, foundList) {
        foundList.items.push(item);
        foundList.save();
        res.redirect("/BucketList/" + customListID);

    });

})

                            <form class="d-flex justify-content-center align-items-center mb-4"
                                action="/BucketList/<%=customListID%>" method="post">

                                    <input type="text" id="form3" class="form-control form-control-lg" name="newItem"
                                        placeholder="New Item" autocomplete="off" />

                                <button type="submit" class="btn btn-primary btn-lg ms-2" name="list"
                                    value="<%= customListID %>">Add</button>
                            </form>
                            <% newListItems.forEach(function(item) { %>

                                            <input class="form-check-input me-2" type="checkbox" value=""
                                                aria-label="..." />
                                            <%=item.name%>

                                        <form action="/deleteItem" method="post">
                                            <button type="submit" id="item-remove-button" title="Remove item"
                                                name="itemDeleteButton" value="<%= item._id %>"
                                                onchange="this.form.submit()">

                                            </button>
                                            <input type="hidden" name="listID" value="<%= customListID %>"></input>
                                        </form>

                                <% }) %>


问:
How do I access this variable outside of my class?
```<code>class DayFix:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
    def fix(self):
        if self.month > 12:
            self.year += 1
            self.month = 1
        elif self.month == 2 and self.day > 29:
            self.month += 1
            self.day = 1
        elif self.month == 4 or self.month == 6 or self.month == 9 or self.month == 11:
            if self.day > 30:
                self.month += 1
                self.day = 1
        elif self.month == 1 or self.month == 3 or self.month == 5 or self.month == 7 or self.month == 8 or self.month == 10:
            if self.day > 31:
                self.month += 1
                self.day = 1
        elif self.month == 12 and self.day > 31:
            self.year += 1
            self.month = 1
            self.day = 1
        test_date = '' + str(self.year) + '-' + str(self.month) + '-' + str(self.day) + ''
        tof = bool(len(pd.bdate_range(test_date, test_date)))
        while tof == False:
            self.day += 1
            test_date = '' + str(self.year) + '-' + str(self.month) + '-' + str(self.day) + ''
            tof = bool(len(pd.bdate_range(test_date, test_date)))
            if tof == True:
                break

</code>```

Yes, I am aware it probably looks like trash, I am very new to this. I need to use the updated "test_date" variable after it goes through the while loop outside of the class, but I am not sure how to get it after running the class with:

```<code>d = DayFix(2020, 1, 10)
d.fix()
</code>```

Thanks ahead of time.

Have not tried any fix yet, not sure what to expect.

Body:
class DayFix:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
    def fix(self):
        if self.month > 12:
            self.year += 1
            self.month = 1
        elif self.month == 2 and self.day > 29:
            self.month += 1
            self.day = 1
        elif self.month == 4 or self.month == 6 or self.month == 9 or self.month == 11:
            if self.day > 30:
                self.month += 1
                self.day = 1
        elif self.month == 1 or self.month == 3 or self.month == 5 or self.month == 7 or self.month == 8 or self.month == 10:
            if self.day > 31:
                self.month += 1
                self.day = 1
        elif self.month == 12 and self.day > 31:
            self.year += 1
            self.month = 1
            self.day = 1
        test_date = '' + str(self.year) + '-' + str(self.month) + '-' + str(self.day) + ''
        tof = bool(len(pd.bdate_range(test_date, test_date)))
        while tof == False:
            self.day += 1
            test_date = '' + str(self.year) + '-' + str(self.month) + '-' + str(self.day) + ''
            tof = bool(len(pd.bdate_range(test_date, test_date)))
            if tof == True:
                break

Yes, I am aware it probably looks like trash, I am very new to this. I need to use the updated "test_date" variable after it goes through the while loop outside of the class, but I am not sure how to get it after running the class with:

d = DayFix(2020, 1, 10)
d.fix()

Thanks ahead of time.

Have not tried any fix yet, not sure what to expect.


问:
libboost_python-dev for Python 3.8 on Ubuntu 22.04
I have a production server with Ubuntu 20.04 and Python v3.8.10.

My development environment is Ubuntu 22.04 with Python v3.10.6.

Both environments make use of a virtual environment when running python code.

Thus far the differences between Python 3.8 and 3.10 have not necessitated that I match my environments exactly. However, I am now forced to use a poorly maintained Python library in my code (provided by a payment gateway), and I encountered version-specific bugs with the library immediately after installing it. Needless to say, I am not confident that if I get it working in the development environment, it will work in the production environment as well. I need to be sure it works in production the first time.

I believe I have managed to successfully install Python 3.8 from source on my development system (without uninstalling Python 3.10). I managed to set up the virtualenv with the older version of Python successfully as well. The installation of requirements, however, fails with /usr/bin/ld: cannot find -lboost_python: No such file or directory during the installation of the pgmagick package. My understanding of the error is that I am missing the libboost_python-dev package for Python v3.8.

How can I install the older libboost_python-dev package on ubuntu 22.04?


问:
Eslint configuration for separated Vue component
Here is my eslintrc.json

```<code>{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/vue3-essential"
    ],
    "parserOptions": {
        "ecmaVersion": "latest"
    },
    "plugins": [
        "vue",
        "eslint-plugin-vue"
    ],

    "rules": {
        "vue/no-async-in-computed-properties": "error",
        "vue/no-unused-vars": "error"
    }
}

</code>```

And This is my vue component(mycomponent.js).
I am using vue CDN to define the vue component.

```<code>const myComponent = Vue.defineComponent({
    template: '#myTemplate',
    components: {
        'other-component': otherComponent,
    },

   props: {...}
   watch: {...}
   data() {return {...}}
   methods: {
       fn1() {
           let a;
       }
   }

});

</code>```

As you can see, The vue component has an unused variable in the fn1 function.
But it doesn't give any error.
Please review if there is any issues in the eslint configuration.

I already installed the eslint-plugin-vue package.

Body:
Here is my eslintrc.json

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/vue3-essential"
    ],
    "parserOptions": {
        "ecmaVersion": "latest"
    },
    "plugins": [
        "vue",
        "eslint-plugin-vue"
    ],

    "rules": {
        "vue/no-async-in-computed-properties": "error",
        "vue/no-unused-vars": "error"
    }
}

And This is my vue component(mycomponent.js).
I am using vue CDN to define the vue component.

const myComponent = Vue.defineComponent({
    template: '#myTemplate',
    components: {
        'other-component': otherComponent,
    },

   props: {...}
   watch: {...}
   data() {return {...}}
   methods: {
       fn1() {
           let a;
       }
   }

});

As you can see, The vue component has an unused variable in the fn1 function.
But it doesn't give any error.
Please review if there is any issues in the eslint configuration.

I already installed the eslint-plugin-vue package.


问:
How to make my Neo4j db available from other internet?
I have a constructed DB that have a structure I need. I works with this by using Neo4j Desktop. Now I've deployed an app what works with my db in local network, but can't work from eternal networks. Now I need to fix it but I can't find any info about that.
When I've tried to connect to db via address http://localhost:PORT from my phone connected to same network I didn't got anything related to db.

I tried to add some settings in neo4j.conf file such as org.neo4j.server.webserver.address=0.0.0.0 and dbms.connector.http.address=0.0.0.0:7474.
Also I have a DDNS but I don't know how can I use it to connect to my db.

I'm expecting that I can connect to my db from any network.


问:
Is there a dynamic way to post/get/patch... data by sending only models in Flutter
is there a way or a library that can map the model of my choice to a http request so I can use it for fetching and posting data

For instance this is how currently it is

```<code>//SOME RANDOM MODEL
    TestModel{
    string name;
    string email;
    string someInfo;
    ...}

//SOME RANDOM HTTP REQ
    Future<TestModel> editTestModelAndFetchSomethingNew (TestModel tm){
    url = 'www.random.com' //ignore this its just for reference

    try{
     resp = await http.post(
    url,
    body: json.encode({
    'name':tm.name,
    'email':tm.email,
    'someInfo':tm.someInfo
    ...).then((resp){
    TestModel newModel = TestModel(
    name:json.decode(resp.body)['name']
    ...
</code>```

is there a way more convinient way than writing it all down for instance to be like this:

```<code> Future<TestModel> editTestModelAndFetchSomethingNew (TestModel tm) async {

    TestModel model = await (some library or some service).postModelRequest(
      url,
      tm,
      (some generator to map each of the parameters - example: tm.generate() ),
    ))!;

    return model;
  }
</code>```

I have been searching for this type of solution for a while but havent found anything that can make this more convenient so Im curious if there is a way to make this or if there is a library for this. Thanks in advance

Body:
is there a way or a library that can map the model of my choice to a http request so I can use it for fetching and posting data

For instance this is how currently it is

//SOME RANDOM MODEL
    TestModel{
    string name;
    string email;
    string someInfo;
    ...}

//SOME RANDOM HTTP REQ
    Future<TestModel> editTestModelAndFetchSomethingNew (TestModel tm){
    url = 'www.random.com' //ignore this its just for reference

    try{
     resp = await http.post(
    url,
    body: json.encode({
    'name':tm.name,
    'email':tm.email,
    'someInfo':tm.someInfo
    ...).then((resp){
    TestModel newModel = TestModel(
    name:json.decode(resp.body)['name']
    ...

is there a way more convinient way than writing it all down for instance to be like this:

 Future<TestModel> editTestModelAndFetchSomethingNew (TestModel tm) async {

    TestModel model = await (some library or some service).postModelRequest(
      url,
      tm,
      (some generator to map each of the parameters - example: tm.generate() ),
    ))!;

    return model;
  }

I have been searching for this type of solution for a while but havent found anything that can make this more convenient so Im curious if there is a way to make this or if there is a library for this. Thanks in advance


问:
How to disable Basic Authentication on the client
I have a site that uses basic authentication to prevent widespread public access to a particular folder.  The material in the folder is not "secret" - it's just preferred not to be available to the whole world.

Some of our users - but only a small percentage - can no longer access material in this folder - they just get an immediate 404 error, no request for the username/password.  The same thing happens if we have them specify the username/password with the url (ie. https://user:passwrd@mysite.com/privatefolder/page.html).  Things work as always for everyone else.

I know basic auth is unsafe... we have 'real' security for things that matter.

I suspect that basic auth has been disabled on the client - either at the machine or browser level - but I can't for the life of me figure out how to do that, so that I can then start to solve the problem.  Or, is this something that can be filtered at a higher level (ie. location firewall)?

It would be a headache to attach individual usernames and passwords to this folder - most users will never remember individual credentials and will complain (rightfully) about the hassle - so would like to replicate the problem to explore solutions.

How might organizations disable basic-auth at the client level for their users?

Any help appreciated.


问:
Pascal Calculator
I am now developing a calculator in Pascal and I am getting this error that while the exponent is negative the result is always 0. Can someone help me with this?
Here is the piece of code for this function that I wrote so far:</p>
```<code>5: Begin
    clrscr;
    Writeln('POWER');
    Write('Base: ');
    Readln(pot1);
    Write('Exponent: ');
    Readln(pot2);
    res5 := 1;
    if pot2 < 0 then
     Begin
        pot1 := 1 div pot1;
        pot2 := -pot2;
        res5 := 1 / res5;
     End;
    while pot2 > 0 do
        Begin
          res5 := res5 * pot1;
          pot2 := pot2 - 1;
        End;
        Writeln('The result is: ', res5:0:4);
        Readkey;
   End;
</code>```

Title: Pascal Calculator

Body:
I am now developing a calculator in Pascal and I am getting this error that while the exponent is negative the result is always 0. Can someone help me with this?
Here is the piece of code for this function that I wrote so far:

5: Begin
    clrscr;
    Writeln('POWER');
    Write('Base: ');
    Readln(pot1);
    Write('Exponent: ');
    Readln(pot2);
    res5 := 1;
    if pot2 < 0 then
     Begin
        pot1 := 1 div pot1;
        pot2 := -pot2;
        res5 := 1 / res5;
     End;
    while pot2 > 0 do
        Begin
          res5 := res5 * pot1;
          pot2 := pot2 - 1;
        End;
        Writeln('The result is: ', res5:0:4);
        Readkey;
   End;


问:
How do I refresh the Firebase Provider Access Token?
Is there a Firebase method to access and refresh the OAuth Provider token, similar to the Firebase ID Token?

I'm using Firebase Auth with Microsoft as my provider. Firebase returns two tokens:

Provider Access Token: this is the Microsoft token that I can use to make calls to Microsoft APIs

Firebase ID Token: this is the Firebase Auth token that I can use to access Google resources

I'm using signInWithRedirect and getRedirectResult to access these tokens:

```<code>signInWithRedirect(authInstance, provider)

# ...later in the file handle redirect
const result = await getRedirectResult(authInstance)
if (result) {
  const credential = OAuthProvider.credentialFromResult(result)
  const accessToken = credential?.accessToken
  const idToken = credential?.idToken
}
</code>```

There is an easy method to access the Firebase ID token that will automatically refresh it if expires, for example: authInstance.currentUser.getIdToken(). I'm having to set the accessToken in a cookie because there doesn't appear to be a method to retrieve it from Firebase. After one hour, the accessToken expires and I need to refresh it.

I can't find an easy way to retrieve and refresh the Provider Access Token outside of the getRedirectResult(). The OAuthProvider.credentialFromResult() method receives a UserCredential type that only seems to be returned after logging in.

How have others solved this issue -- how do you access and refresh the Provider Token in a place after the initial login?

Body:
Is there a Firebase method to access and refresh the OAuth Provider token, similar to the Firebase ID Token?

I'm using Firebase Auth with Microsoft as my provider. Firebase returns two tokens:

Provider Access Token: this is the Microsoft token that I can use to make calls to Microsoft APIs

Firebase ID Token: this is the Firebase Auth token that I can use to access Google resources

I'm using signInWithRedirect and getRedirectResult to access these tokens:

signInWithRedirect(authInstance, provider)

# ...later in the file handle redirect
const result = await getRedirectResult(authInstance)
if (result) {
  const credential = OAuthProvider.credentialFromResult(result)
  const accessToken = credential?.accessToken
  const idToken = credential?.idToken
}

There is an easy method to access the Firebase ID token that will automatically refresh it if expires, for example: authInstance.currentUser.getIdToken(). I'm having to set the accessToken in a cookie because there doesn't appear to be a method to retrieve it from Firebase. After one hour, the accessToken expires and I need to refresh it.

I can't find an easy way to retrieve and refresh the Provider Access Token outside of the getRedirectResult(). The OAuthProvider.credentialFromResult() method receives a UserCredential type that only seems to be returned after logging in.

How have others solved this issue -- how do you access and refresh the Provider Token in a place after the initial login?


问:
Draw a Custom Tiled map in MapLibre android
I want to use MapLibre to display a Map in an android app, using a custom MapTiler map with raster Tiles from an URL with X Y Zoom format: "http://serverAddres:port/api/maps/style_satellite/%d/%d/%d.png"

Does map Libre Support this? and how do I tell it to consume that Tiles in getMapAsync? I tryed creating a style, or a source with no luck.

I didn't find any examples on the documentation or web search, only using map tilers own styles.


问:
How to upload a media with the private Twitter's API?
I recently developed a program that allows you to connect to Twitter and do some tasks automatically (like Tweeter, Liking) using only the account information: username;password;email_or_phone.

My problem is that I am now trying to add the functionality of Tweeting with an image but I can't.

Here is my code and my error:

async def tweet_success(self, msg: str, img_path: str):
    # Get the number of bytes of the image
    img_bytes = str(os.path.getsize(img_path))

    # Get the media_id to add an image to my tweet
    params = {'command': 'INIT','total_bytes': img_bytes,'media_type': 'image/png','media_category': 'tweet_image'}
    response = requests.post('https://upload.twitter.com/i/media/upload.json', params=params, headers=self.get_headers())
    media_id = response.text.split('{"media_id":')[1].split(',')[0]

    params = {'command': 'APPEND','media_id': media_id,'segment_index': '0',}
    # Try to get the raw binary of the image, My problem is here
    data = open(img_path, "rb").read()
    response = requests.post('https://upload.twitter.com/i/media/upload.json', params=params, headers=self.get_headers(), data=data,)
```
```{"request":"\/i\/media\/upload.json","error":"media parameter is missing."}
```
<p>Can someone help me ?</p>
<p>I tried</p>
```data = open(img_path, "rb").read()
data = f'------WebKitFormBoundaryaf0mMLIS7kpsKwPv\r\nContent-Disposition: form-data; name="media"; filename="blob"\r\nContent-Type: application/octet-stream\r\n\r\n{data}\r\n------WebKitFormBoundaryaf0mMLIS7kpsKwPv--\r\n'
```
```data = open(img_path, "rb").read()
data = f'------WebKitFormBoundaryaf0mMLIS7kpsKwPv\r\nContent-Disposition: form-data; name="media"; filename="blob"\r\nContent-Type: application/octet-stream\r\n\r\n{data}\r\n------WebKitFormBoundaryaf0mMLIS7kpsKwPv--\r\n'.encode()
```
```data = open(img_path, "rb").read()
data = base64.b64encode(data)
```

Body:
I recently developed a program that allows you to connect to Twitter and do some tasks automatically (like Tweeter, Liking) using only the account information: username;password;email_or_phone.

My problem is that I am now trying to add the functionality of Tweeting with an image but I can't.

Here is my code and my error:

async def tweet_success(self, msg: str, img_path: str):
    # Get the number of bytes of the image
    img_bytes = str(os.path.getsize(img_path))

    # Get the media_id to add an image to my tweet
    params = {'command': 'INIT','total_bytes': img_bytes,'media_type': 'image/png','media_category': 'tweet_image'}
    response = requests.post('https://upload.twitter.com/i/media/upload.json', params=params, headers=self.get_headers())
    media_id = response.text.split('{"media_id":')[1].split(',')[0]

    params = {'command': 'APPEND','media_id': media_id,'segment_index': '0',}
    # Try to get the raw binary of the image, My problem is here
    data = open(img_path, "rb").read()
    response = requests.post('https://upload.twitter.com/i/media/upload.json', params=params, headers=self.get_headers(), data=data,)

{"request":"\/i\/media\/upload.json","error":"media parameter is missing."}

Can someone help me ?

I tried

data = open(img_path, "rb").read()
data = f'------WebKitFormBoundaryaf0mMLIS7kpsKwPv\r\nContent-Disposition: form-data; name="media"; filename="blob"\r\nContent-Type: application/octet-stream\r\n\r\n{data}\r\n------WebKitFormBoundaryaf0mMLIS7kpsKwPv--\r\n'

data = open(img_path, "rb").read()
data = f'------WebKitFormBoundaryaf0mMLIS7kpsKwPv\r\nContent-Disposition: form-data; name="media"; filename="blob"\r\nContent-Type: application/octet-stream\r\n\r\n{data}\r\n------WebKitFormBoundaryaf0mMLIS7kpsKwPv--\r\n'.encode()

data = open(img_path, "rb").read()
data = base64.b64encode(data)


问:
TCL string map with a "\ "
I have a phone number like 012.345.67.89 and I need to change it to 012\ 345\ 67\ 89

Because I don't want a list but a string.

I've tried

```<code>set out [string map [list . {\ }] $in]
set out [string map [list . "\\ "] $in]
</code>```

But I only get
{012 345 67 89}
and not
012\ 345\ 67\ 89
Can someone help me to find a way to put litteraly the
\  (with the whitespace).

I even try with regsub with no success.

The problem here, is that I can't split and join easily because it could be a foreign phone number with random length...

Thank you by advance for your help :)

Title: TCL string map with a "\ "

Body:
I have a phone number like 012.345.67.89 and I need to change it to 012\ 345\ 67\ 89

Because I don't want a list but a string.

I've tried

set out [string map [list . {\ }] $in]
set out [string map [list . "\\ "] $in]

But I only get
{012 345 67 89}
and not
012\ 345\ 67\ 89
Can someone help me to find a way to put litteraly the
\  (with the whitespace).

I even try with regsub with no success.

The problem here, is that I can't split and join easily because it could be a foreign phone number with random length...

Thank you by advance for your help :)


问:
How to fill between two curves of different x and y ranges with matplotlib
Say I have two lines, defined by the data

```<code>x1 = [0,1,2,3]
y1 = [3,5,4,6]
x2 = [1.5,2.5,3.5,4.5]
y2 = [1,3,2,4]
</code>```

which make the plot

```<code>plt.figure(figsize=(10,10))
plt.plot(x1, y1)
plt.plot(x2, y2)
plt.show()
</code>```

How can I fill between those two lines? I want the polygon made by connecting the endpoints of these lines, but plt.fill_between and plt.fill_betweenx don't work, as they are on both different x and y ranges.

Body:
Say I have two lines, defined by the data

x1 = [0,1,2,3]
y1 = [3,5,4,6]
x2 = [1.5,2.5,3.5,4.5]
y2 = [1,3,2,4]

which make the plot

plt.figure(figsize=(10,10))
plt.plot(x1, y1)
plt.plot(x2, y2)
plt.show()

How can I fill between those two lines? I want the polygon made by connecting the endpoints of these lines, but plt.fill_between and plt.fill_betweenx don't work, as they are on both different x and y ranges.


问:
"Required parameter key not set" error in AWS ATHENA
I am using AWS ATHENA in my lambda function to query and fetch results.

For simpler queries, sometimes the query execution fails with error "Required parameter key not set"

But on re-execution, the query gets executed successfully.

For complex queries, the query never gets executed and fails with the same error "Required parameter key not set." These queries take more than 5 seconds to execute when queries in the Athena console of the AWS account.

What changes do I need to make to successfully execute Athena query from my lambda function? Below is the code.

```<code>def execute_query(query, athena_database, service_query_result_folder):
    # Function to execute the sql query and get the results.
    athena_client = boto3.client(service_name="athena", region_name=region)
    result_location = f"s3://{s3_bucket}/{service_query_result_folder}/"
    logger.info(f"Athena result location: {result_location}")
    execution_start_response = athena_client.start_query_execution(
        QueryString=query,
        QueryExecutionContext={"Database": athena_database},
        ResultConfiguration={"OutputLocation": result_location}
    )
    queryId = execution_start_response["QueryExecutionId"]
    logger.info(f"Executed query with execution id: {queryId}")
    result_file = queryId + ".csv"
    result_file_with_prefix = service_query_result_folder + '/' + result_file
    result_file_location = result_location + result_file
    execution_get_response = athena_client.get_query_execution(QueryExecutionId=queryId)
    execution_details = execution_get_response["QueryExecution"]
    execution_status = execution_details["Status"]["State"]
    if execution_status == "SUCCEEDED":
        logger.info(f"Athena query execution {execution_status}. Execution details: {execution_details}")
        logger.info(f"Result file location: {result_file_location}")
        logger.info(f"Result fie: {result_file}")
        return result_file_with_prefix
    elif execution_status == "FAILED" or execution_status == "CANCELLED":
        logger.error("Athena query execution {}. Details: {}".format(execution_status, execution_get_response))

</code>```

I tried updating the query to result with one row, but I'm still facing the issue.

Body:
I am using AWS ATHENA in my lambda function to query and fetch results.

For simpler queries, sometimes the query execution fails with error "Required parameter key not set"

But on re-execution, the query gets executed successfully.

For complex queries, the query never gets executed and fails with the same error "Required parameter key not set." These queries take more than 5 seconds to execute when queries in the Athena console of the AWS account.

What changes do I need to make to successfully execute Athena query from my lambda function? Below is the code.

def execute_query(query, athena_database, service_query_result_folder):
    # Function to execute the sql query and get the results.
    athena_client = boto3.client(service_name="athena", region_name=region)
    result_location = f"s3://{s3_bucket}/{service_query_result_folder}/"
    logger.info(f"Athena result location: {result_location}")
    execution_start_response = athena_client.start_query_execution(
        QueryString=query,
        QueryExecutionContext={"Database": athena_database},
        ResultConfiguration={"OutputLocation": result_location}
    )
    queryId = execution_start_response["QueryExecutionId"]
    logger.info(f"Executed query with execution id: {queryId}")
    result_file = queryId + ".csv"
    result_file_with_prefix = service_query_result_folder + '/' + result_file
    result_file_location = result_location + result_file
    execution_get_response = athena_client.get_query_execution(QueryExecutionId=queryId)
    execution_details = execution_get_response["QueryExecution"]
    execution_status = execution_details["Status"]["State"]
    if execution_status == "SUCCEEDED":
        logger.info(f"Athena query execution {execution_status}. Execution details: {execution_details}")
        logger.info(f"Result file location: {result_file_location}")
        logger.info(f"Result fie: {result_file}")
        return result_file_with_prefix
    elif execution_status == "FAILED" or execution_status == "CANCELLED":
        logger.error("Athena query execution {}. Details: {}".format(execution_status, execution_get_response))

I tried updating the query to result with one row, but I'm still facing the issue.


问:
Android 11: Connect to Wifi programmatically without user prompt
I have read that starting from API Level 29 or 30, Android always shows a confirmation prompt when an app tries to connect to a wifi network? Is this true for every connection attempt or does this only apply to the first connection attempt?

I am looking to develop an app that should do the following and are looking forward to some feedback whether this is actually possible

the app will be set up as a launcher, so it is the only app that will be used on the phone

upon start, the app tries to connect to a certain wifi in order to communicate with devices which are within this wifi

while using the app, the user should not have to confirm the wifi connection although a confirmation upon the first setup would be okay


问:
Invalid Resx file. ResX input is not valid. Cannot find valid "resheader" tags for the ResX reader and writer type names
I have this resource file for checking and everytime I run the program it prints the error Invalid Resx file. ResX input is not valid. Cannot find valid "resheader" tags for the ResX reader and writer type names.

But I have the root and resheader elements in my file so what's wrong ?

```<code><root>
  <resheader name="text1">
    <value>Hello</value>
  </resheader>
  <resheader name="text2">
    <value>my</value>
  </resheader>
  <resheader name="text3">
    <value>name</value>
  </resheader>
  <resheader name="text4">
    <value>is</value>
  </resheader>
  <resheader name="text5">
    <value>Jacob</value>
  </resheader>
</root>
</code>```

Body:
I have this resource file for checking and everytime I run the program it prints the error Invalid Resx file. ResX input is not valid. Cannot find valid "resheader" tags for the ResX reader and writer type names.

But I have the root and resheader elements in my file so what's wrong ?

<root>
  <resheader name="text1">
    <value>Hello</value>
  </resheader>
  <resheader name="text2">
    <value>my</value>
  </resheader>
  <resheader name="text3">
    <value>name</value>
  </resheader>
  <resheader name="text4">
    <value>is</value>
  </resheader>
  <resheader name="text5">
    <value>Jacob</value>
  </resheader>
</root>


问:
PermissionError: [Errno 13] Permission denied: 'C:/Users/XXX.XXXXX/Downloads' when interacting with Pandas and GUI
I am trying to hook up a PySimpleGUI to my CSV formatter function from another .py file in the same directory. I am trying to feed it the input file and an output file. The program works if I manually input the output destination, but I get PermissionError: [Errno 13] Permission denied: 'C:/Users/XXX.XXXXX/Downloads' if I use the GUI interface. I want the output file to be whatever is selected in the GUI.

```<code>import PySimpleGUI as sg
import pandas as pd
from pathlib import Path
from SBOE_Formatter import boe_formatter

def select_target_client(client_pick):
    # <---Client Picker menu--->
    sg.theme("DarkTeal10")

    layout = [[sg.T("Client picker")],
              [sg.T(""), sg.Combo(client_pick["CLIENTS"]["c1"].split("|"), size=(30, 5),
                                  default_value=client_pick["CLIENTS"]["client default"], s=1, key="-SET_CLIENT-")],
              [sg.B("Save client selection", s=20)]]

    window = sg.Window("Client selector", layout, modal=True, size=(300, 100))

    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        if event == "Save client selection":
            client_pick["CLIENTS"]["c2"] = values["-SET_CLIENT-"]

            sg.popup_no_titlebar("Client selection saved")
            break
    window.close()

def main_window():
    # <---Main Window--->
    sg.theme("DarkTeal10")

    layout = [[sg.T("Eligibility File:", s=15, justification="r"), sg.I(key="-EF_IN-"), sg.FileBrowse()],
              [sg.T("User List File:", s=15, justification="r"), sg.I(key="-UL_IN-"), sg.FileBrowse()],
              [sg.T("Target Location:", s=15, justification="r"), sg.I(key="-OUT-"), sg.FolderBrowse()],
              [sg.B("Format EF only", s=16), sg.B("Merge files", s=16), sg.B("Select client type", s=16)]]

    window = sg.Window("Eligibility/User-List Merger", layout)

    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        if event == "Select client type":
            select_target_client(client_list)
        if event == "Format EF only":
            boe_formatter(values["-EF_IN-"], values["-OUT-"])

if __name__ == "__main__":
    client_path = str(Path.cwd())
    client_list = sg.UserSettings(
        path=client_path, filename="Clients_List.ini", use_config_file=True, convert_bools_and_none=True
    )
    main_window()
</code>```

I have looked all around, and some solutions I see are to run this from the command prompt as an administrator, but that does not help me as I am looking to package the final system up for co-workers to quickly edit files, and they wont know how to run it in the command prompt.

Body:
I am trying to hook up a PySimpleGUI to my CSV formatter function from another .py file in the same directory. I am trying to feed it the input file and an output file. The program works if I manually input the output destination, but I get PermissionError: [Errno 13] Permission denied: 'C:/Users/XXX.XXXXX/Downloads' if I use the GUI interface. I want the output file to be whatever is selected in the GUI.

import PySimpleGUI as sg
import pandas as pd
from pathlib import Path
from SBOE_Formatter import boe_formatter

def select_target_client(client_pick):
    # <---Client Picker menu--->
    sg.theme("DarkTeal10")

    layout = [[sg.T("Client picker")],
              [sg.T(""), sg.Combo(client_pick["CLIENTS"]["c1"].split("|"), size=(30, 5),
                                  default_value=client_pick["CLIENTS"]["client default"], s=1, key="-SET_CLIENT-")],
              [sg.B("Save client selection", s=20)]]

    window = sg.Window("Client selector", layout, modal=True, size=(300, 100))

    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        if event == "Save client selection":
            client_pick["CLIENTS"]["c2"] = values["-SET_CLIENT-"]

            sg.popup_no_titlebar("Client selection saved")
            break
    window.close()

def main_window():
    # <---Main Window--->
    sg.theme("DarkTeal10")

    layout = [[sg.T("Eligibility File:", s=15, justification="r"), sg.I(key="-EF_IN-"), sg.FileBrowse()],
              [sg.T("User List File:", s=15, justification="r"), sg.I(key="-UL_IN-"), sg.FileBrowse()],
              [sg.T("Target Location:", s=15, justification="r"), sg.I(key="-OUT-"), sg.FolderBrowse()],
              [sg.B("Format EF only", s=16), sg.B("Merge files", s=16), sg.B("Select client type", s=16)]]

    window = sg.Window("Eligibility/User-List Merger", layout)

    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        if event == "Select client type":
            select_target_client(client_list)
        if event == "Format EF only":
            boe_formatter(values["-EF_IN-"], values["-OUT-"])

if __name__ == "__main__":
    client_path = str(Path.cwd())
    client_list = sg.UserSettings(
        path=client_path, filename="Clients_List.ini", use_config_file=True, convert_bools_and_none=True
    )
    main_window()

I have looked all around, and some solutions I see are to run this from the command prompt as an administrator, but that does not help me as I am looking to package the final system up for co-workers to quickly edit files, and they wont know how to run it in the command prompt.


问:
Setting datetime only for month and year using pn.widgets.DateRangeSlider
I am currently creating an interactive dashboard with panel library. My data are given by year and month only. So I want to define one of the panel widgets "time" in terms of the date (yyyy-mm). So far I've got this:

```<code>import datetime as dt
Time =  pn.widgets.DateRangeSlider(name='Time', start=dt.datetime(2021, 10, 1),
end=dt.datetime(2022, 10, 1), step=24*3600*30*1000)
</code>```

Is there a possibility to set the dt.datetime only for year and month leaving aside the day?

Body:
I am currently creating an interactive dashboard with panel library. My data are given by year and month only. So I want to define one of the panel widgets "time" in terms of the date (yyyy-mm). So far I've got this:

import datetime as dt
Time =  pn.widgets.DateRangeSlider(name='Time', start=dt.datetime(2021, 10, 1),
end=dt.datetime(2022, 10, 1), step=24*3600*30*1000)

Is there a possibility to set the dt.datetime only for year and month leaving aside the day?


问:
SSAS TokenizationBehavior
Within the dimension properties for an attribute within SSAS, there is an option called TokenizationBehavior which is defaulted to TokenizationNone.  The alternative is TokenizationText.

I tried it out and it gives an error message as per below. There is little content on the internet about anybody trying this out or what it is actually for. Any ideas? I'm not sure if this Tokenization is for parsing text or a security mechanism?  And why it doesn't work or how it's supposed to work in SSAS?

The ddl500:TokenizationBehavior element (namespacehttp://schemas.microsoft.com/analysisservices/2013/engine/500) cannot appear under Envelope/Body/Execute/Command/Batch/Alter/ObjectDefinition/Database/Dimensions/Dimension/Attributes/Attribute

I looked at the XML code which adds the below line if you put TokenizationText in the dimension attribute properties:

<ddl500:TokenizationBehavior valuens="ddl500_500">TokenizationText</ddl500:TokenizationBehavior>

Title: SSAS TokenizationBehavior


问:
Getting desperate with Python file importing
So I searched for dozen different tutorials and currently i am struggling with importing a file from different subdirectory. I am using python3.
the folders look like this:

```<code>app
|-gui/
|   |-interface.py
|-src/
|   |-main.py
|-utils/
|   |-var.py
</code>```

In main.py i am trying do import var.py with a two classes. This way: import utils.var.
Horewer its the classic error: ModuleNotFoundError: No module named 'utils'.
I tried all different combinations app.utils.var, var, utils, app.utils, nothing seems to work. Even tried relative imports like ..utils.var etc.
What seems to be the problem???

Body:
So I searched for dozen different tutorials and currently i am struggling with importing a file from different subdirectory. I am using python3.
the folders look like this:

app
|-gui/
|   |-interface.py
|-src/
|   |-main.py
|-utils/
|   |-var.py

In main.py i am trying do import var.py with a two classes. This way: import utils.var.
Horewer its the classic error: ModuleNotFoundError: No module named 'utils'.
I tried all different combinations app.utils.var, var, utils, app.utils, nothing seems to work. Even tried relative imports like ..utils.var etc.
What seems to be the problem???


问:
Ray-Cube Intersection C++
I am writing a ray tracing program in C++ to get better at the language. However I am having some troubles implementing my ray-cube intersection functionality.

Here is my class

```<code>class Cube {
public:
    Cube() {};
    ~Cube() {};

    float Intersection(Ray ray) {
        // Intersection Code Here
    }

public:
    glm::vec3 Position;
    glm::vec3 Size;
    int MaterialIndex = 0;
};

</code>```

I can't find any good references anywhere that fit my need (using vec3s for size and position). I need to return a float that is the distance to the Cube or -1 if it does not hit.

For reference here is my Sphere class

```<code>
class Sphere {
public:
    Sphere() {};
    ~Sphere() {};

    float Intersection(Ray ray) {
        glm::vec3 origin = ray.Origin - Position;

        float a = glm::dot(ray.Direction, ray.Direction);
        float b = 2.0f * glm::dot(origin, ray.Direction);
        float c = glm::dot(origin, origin) - Radius * Radius;

        // Quadratic forumula discriminant:
        // b^2 - 4ac

        float discriminant = b * b - 4.0f * a * c;

        // Quadratic formula:
        // (-b +- sqrt(discriminant)) / 2a

        // float t0 = (-b + glm::sqrt(discriminant)) / (2.0f * a); // Second hit distance (currently unused)
        float closestT = (-b - glm::sqrt(discriminant)) / (2.0f * a);

        return closestT;
    };

public:
    float Radius = 0.5f;
    glm::vec3 Position;
    int MaterialIndex = 0;
};
</code>```

Can anyone help me?

Title: Ray-Cube Intersection C++

Body:
I am writing a ray tracing program in C++ to get better at the language. However I am having some troubles implementing my ray-cube intersection functionality.

Here is my class

class Cube {
public:
    Cube() {};
    ~Cube() {};

    float Intersection(Ray ray) {
        // Intersection Code Here
    }

public:
    glm::vec3 Position;
    glm::vec3 Size;
    int MaterialIndex = 0;
};

I can't find any good references anywhere that fit my need (using vec3s for size and position). I need to return a float that is the distance to the Cube or -1 if it does not hit.

For reference here is my Sphere class

class Sphere {
public:
    Sphere() {};
    ~Sphere() {};

    float Intersection(Ray ray) {
        glm::vec3 origin = ray.Origin - Position;

        float a = glm::dot(ray.Direction, ray.Direction);
        float b = 2.0f * glm::dot(origin, ray.Direction);
        float c = glm::dot(origin, origin) - Radius * Radius;

        // Quadratic forumula discriminant:
        // b^2 - 4ac

        float discriminant = b * b - 4.0f * a * c;

        // Quadratic formula:
        // (-b +- sqrt(discriminant)) / 2a

        // float t0 = (-b + glm::sqrt(discriminant)) / (2.0f * a); // Second hit distance (currently unused)
        float closestT = (-b - glm::sqrt(discriminant)) / (2.0f * a);

        return closestT;
    };

public:
    float Radius = 0.5f;
    glm::vec3 Position;
    int MaterialIndex = 0;
};

Can anyone help me?


问:
Silverlight 4/5 and recording video using webcam and mic
Is there any support for video+audio recording using webcam and mic in silverlight.

I want to record the video with audio using silverlight and store at the server side using wcf  service.

ContentLicense: CC BY-SA 3.0


问:
Backtest using yahoo finance and backtest
I'm getting an error message when I try to run the code below. How can I change my code to provide comprehensive daily and monthly returns? I want to use this code in particular for BIST30 and BIST100. Should I modify my code for a few details?

```<code>\#%%
import yfinance as yf
import backtrader as bt

# Download historical data for the asset

ticker = "SASA.IS"
data = yf.download(ticker, period="max", start="2020-01-02")

# Create a Backtrader data feed from the Pandas dataframe

data = bt.feeds.PandasData(dataname=data)

# Create a Backtrader strategy

class MyStrategy(bt.Strategy):
def __init__(self):
self.data_close = self.datas\[0\].close
self.sma = bt.indicators.SimpleMovingAverage(self.datas\[0\], period=200)
self.order = None

    def next(self):
        if self.order:
            # If an order is pending, do nothing
            return

        if self.data_close > self.sma:
            # If the price crosses above the moving average, buy the asset
            self.order = self.buy()

# Create a Backtrader cerebro object

cerebro = bt.Cerebro()

# Add the data feed to the cerebro object

cerebro.adddata(data)

# Add the strategy to the cerebro object

cerebro.addstrategy(MyStrategy)

# Run the backtest

result = cerebro.run()

# Get the Returns analyzer

returns_analyzer = result\[0\].analyzers.returns

# Get the detailed returns

returns = returns_analyzer.get_analysis()

# Print the detailed returns

print(returns)
</code>```

I'm attempting to use this code to view daily and monthly returns.

```<code>
\[***100%***\*\*\]  1 of 1 completed
-

AttributeError                            Traceback (most recent call last)
\<ipython-input-15-b254cc0d9b5a\> in \<module\>
39
40 # Get the Returns analyzer
\---\> 41 returns_analyzer = result\[0\].analyzers.returns
42
43 # Get the detailed returns

AttributeError: 'ItemCollection' object has no attribute 'returns'
</code>```

Body:
I'm getting an error message when I try to run the code below. How can I change my code to provide comprehensive daily and monthly returns? I want to use this code in particular for BIST30 and BIST100. Should I modify my code for a few details?

\#%%
import yfinance as yf
import backtrader as bt

# Download historical data for the asset

ticker = "SASA.IS"
data = yf.download(ticker, period="max", start="2020-01-02")

# Create a Backtrader data feed from the Pandas dataframe

data = bt.feeds.PandasData(dataname=data)

# Create a Backtrader strategy

class MyStrategy(bt.Strategy):
def __init__(self):
self.data_close = self.datas\[0\].close
self.sma = bt.indicators.SimpleMovingAverage(self.datas\[0\], period=200)
self.order = None

    def next(self):
        if self.order:
            # If an order is pending, do nothing
            return

        if self.data_close > self.sma:
            # If the price crosses above the moving average, buy the asset
            self.order = self.buy()

# Create a Backtrader cerebro object

cerebro = bt.Cerebro()

# Add the data feed to the cerebro object

cerebro.adddata(data)

# Add the strategy to the cerebro object

cerebro.addstrategy(MyStrategy)

# Run the backtest

result = cerebro.run()

# Get the Returns analyzer

returns_analyzer = result\[0\].analyzers.returns

# Get the detailed returns

returns = returns_analyzer.get_analysis()

# Print the detailed returns

print(returns)

I'm attempting to use this code to view daily and monthly returns.

\[***100%***\*\*\]  1 of 1 completed
-

AttributeError                            Traceback (most recent call last)
\<ipython-input-15-b254cc0d9b5a\> in \<module\>
39
40 # Get the Returns analyzer
\---\> 41 returns_analyzer = result\[0\].analyzers.returns
42
43 # Get the detailed returns

AttributeError: 'ItemCollection' object has no attribute 'returns'


问:
unable to changing a value in an object called file
I am trying to change the value of name inside the file object . Any idea how i would go about it ?

```<code>  setFile(e.target.files[0]);
    console.log(file)
  const name = "john"
</code>```

i want to change the name to "john" .

File {name: 'image1 (1).png', lastModified: 1671648766099, lastModifiedDate: Wed Dec 21 2022 21:52:46 GMT+0300...}

I have tried doing File['name'] = name but it did not work and it gives me App.js:14 Uncaught TypeError: Cannot set property name of # which has only a getter error

Body:
I am trying to change the value of name inside the file object . Any idea how i would go about it ?

  setFile(e.target.files[0]);
    console.log(file)
  const name = "john"

i want to change the name to "john" .

File {name: 'image1 (1).png', lastModified: 1671648766099, lastModifiedDate: Wed Dec 21 2022 21:52:46 GMT+0300...}

I have tried doing File['name'] = name but it did not work and it gives me App.js:14 Uncaught TypeError: Cannot set property name of # which has only a getter error


问:
How can I draw a quadratic curve that is going through a certain control point
I'm trying to draw a quadratic curve that has movable control points on the canvas. Everything is okay but how can I draw a quadratic curve that is going through a certain control point?

I tried this:

const startPoints = [0,0];
const controlPoints = [100, 40];
const endPoints = [200, 200];

ctx.moveTo(...startPoints);
ctx.quadraticCurveTo(...controlPoints, ...endPoints);
ctx.stroke();
```

It draws a quadratic curve like this (purple circles are the points):

the middle circle is the control point of the curve.

But what I want to draw is like this:

I mean, I want the quadratic curve to go through the control point. How can I do that?

Body:
I'm trying to draw a quadratic curve that has movable control points on the canvas. Everything is okay but how can I draw a quadratic curve that is going through a certain control point?

I tried this:

const startPoints = [0,0];
const controlPoints = [100, 40];
const endPoints = [200, 200];

ctx.moveTo(...startPoints);
ctx.quadraticCurveTo(...controlPoints, ...endPoints);
ctx.stroke();

It draws a quadratic curve like this (purple circles are the points):

the middle circle is the control point of the curve.

But what I want to draw is like this:

I mean, I want the quadratic curve to go through the control point. How can I do that?


问:
How can I have a user confirm their credentials from within a Capacitor project?
I have a Capacitor project and want to be able to guard an action (sending another user money) by first requiring the user to confirm their credentials (PIN / fingerprint / face).  I'm thinking what I need to make use of is createConfirmDeviceCredentialIntent on Android and its equivalent on iOS.  How can I do that?</p>


问:
Test billing products
In the past we could test the in app purchase with static skus like following:

android.test.purchased

android.test.canceled

android.test.refunded

android.test.item_unavailable

This did work without the need of a published app.

Now (in billing v5) we can query products from the billing api. Is there a simple way to test the api without the app published? I could not find anything anymore... I'd simply want some static responses for products that are owned/not owned/not found...

I want to query products for those testing purposes only just to showcase the usage of a library of mine and I don't want to put this app to the play store just for this use case...

Title: Test billing products


问:
After RStudio upgrade, styler's style_selection function not working
After upgrading RStudio in Ubuntu 22.04.1 (via rstudio-2022.12.0-353-amd64.deb available at https://posit.co/download/rstudio-desktop/) the function style_selection that is part of the styler package has stopped working for me. The problem appeared while I was running styler version 1.7.0 - after upgrading to current version 1.8.1, the problem described below persisted. I'm running R version 4.1.2.

It seems that, in contrast to typical R packages, styler is a part of RStudio via Addins - for reference, in RStudio, clicks Tools, then Addins, then Browse Addins, and then Keyboard Shortcuts. Take note of the shortcut for the Addin named Style Selection - mine is ctrl+shift+a (this is possibly the default, but not certain).

Minimal example:

```<code>library(styler)
2+2 # take note of spacing
</code>```

Highlight the above code and then hit the shortcut for Style Selection which for me is ctrl+shift+a. Expected result:

```<code>library(styler)
2 + 2 # take note of spacing
</code>```

Instead of expected result, I receive the following error message:

```<code>> styler:::style_selection()
Using style transformers `styler::tidyverse_style()`
Error in `styler:::style_selection()`:
! No code selected
Run `rlang::last_error()` to see where the error occurred.
</code>```

(Running rlang::last_error() and rlang::last_trace() don't seem to return anything meaningful.)

Any ideas? Thank you.

Update: Downgrading to rstudio-2022.07.2-576-amd64.deb resolves the problem. However, running the current version would be preferred.

Body:
After upgrading RStudio in Ubuntu 22.04.1 (via rstudio-2022.12.0-353-amd64.deb available at https://posit.co/download/rstudio-desktop/) the function style_selection that is part of the styler package has stopped working for me. The problem appeared while I was running styler version 1.7.0 - after upgrading to current version 1.8.1, the problem described below persisted. I'm running R version 4.1.2.

It seems that, in contrast to typical R packages, styler is a part of RStudio via Addins - for reference, in RStudio, clicks Tools, then Addins, then Browse Addins, and then Keyboard Shortcuts. Take note of the shortcut for the Addin named Style Selection - mine is ctrl+shift+a (this is possibly the default, but not certain).

Minimal example:

library(styler)
2+2 # take note of spacing

Highlight the above code and then hit the shortcut for Style Selection which for me is ctrl+shift+a. Expected result:

library(styler)
2 + 2 # take note of spacing

Instead of expected result, I receive the following error message:

> styler:::style_selection()
Using style transformers `styler::tidyverse_style()`
Error in `styler:::style_selection()`:
! No code selected
Run `rlang::last_error()` to see where the error occurred.

(Running rlang::last_error() and rlang::last_trace() don't seem to return anything meaningful.)

Any ideas? Thank you.

Update: Downgrading to rstudio-2022.07.2-576-amd64.deb resolves the problem. However, running the current version would be preferred.


问:
How to use group-by operations in tensorflow?
I am having trouble to translate this operation which is easily implemented in R or Python into tensorflow syntax.

Suppose I have data of the following form:

```<code>ID <- c("ABC", "DEF", "GHI")
date <- as.Date(c("30/11/2022", "31/12/2022"))
var1 <- rnorm(20)
var2 <- rnorm(20)

expand.grid(ID, date, var1, var2)
</code>```

Now I run a neural network with "var1" and "var2" so I get an output vector. I than have outputs corresponding to a date and ID. I want to apply this operation grouped by date, so that the outputs sum to 1 for each date.

```<code>data |>
  group_by(date) |>
    # Outputs sum up to 1 for each date
    output_norm = output / sum(output)
  ) |>
  ungroup()
</code>```

Unfortunately, I was not able to come up with a solution on how to implement this.

I tried playing around with "tf.math.unsorted_segment_sum" however the output of this function has the size of my groups.

Body:
I am having trouble to translate this operation which is easily implemented in R or Python into tensorflow syntax.

Suppose I have data of the following form:

ID <- c("ABC", "DEF", "GHI")
date <- as.Date(c("30/11/2022", "31/12/2022"))
var1 <- rnorm(20)
var2 <- rnorm(20)

expand.grid(ID, date, var1, var2)

Now I run a neural network with "var1" and "var2" so I get an output vector. I than have outputs corresponding to a date and ID. I want to apply this operation grouped by date, so that the outputs sum to 1 for each date.

data |>
  group_by(date) |>
    # Outputs sum up to 1 for each date
    output_norm = output / sum(output)
  ) |>
  ungroup()

Unfortunately, I was not able to come up with a solution on how to implement this.

I tried playing around with "tf.math.unsorted_segment_sum" however the output of this function has the size of my groups.


Title: bn.fit and cluster objects?