问:
Lag is causing collision to be late
I have a jump pad that when it triggers the player and his velocity.y is less than 0(So, it activates only if the player is falling) the problem is that sometimes it does not work probably because of the lag so the player touches the ground in the following frame.How can I fix this?here is my code for triggering the pad.

```<code>void OnTriggerEnter2D(Collider2D others)
{
    if(others.gameObject.name== "JumpPad"){
        Debug.Log(rb.velocity.y);
    }
    if (others.gameObject.name == "JumpPad" && rb.velocity.y<0)
    {
        rb.velocity = new Vector2(rb.velocity.x, PadJumpingPower);
    }
}
</code>```

and this is my character control script

```<code>if (IsGrounded())
        {
            Jump = false;
        }
        else
        {
            Jump = true;
        }
        animator.SetFloat("speed", Mathf.Abs(horizontal));
        animator.SetBool("Jumping", Jump);
        horizontal = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
            Jump = true;
        }

        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
        }

        Flip();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }

    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

    private void Flip()
    {
        if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
        {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }

    }
</code>```

Title: Lag is causing collision to be late

Body:
I have a jump pad that when it triggers the player and his velocity.y is less than 0(So, it activates only if the player is falling) the problem is that sometimes it does not work probably because of the lag so the player touches the ground in the following frame.How can I fix this?here is my code for triggering the pad.

void OnTriggerEnter2D(Collider2D others)
{
    if(others.gameObject.name== "JumpPad"){
        Debug.Log(rb.velocity.y);
    }
    if (others.gameObject.name == "JumpPad" && rb.velocity.y<0)
    {
        rb.velocity = new Vector2(rb.velocity.x, PadJumpingPower);
    }
}

and this is my character control script

if (IsGrounded())
        {
            Jump = false;
        }
        else
        {
            Jump = true;
        }
        animator.SetFloat("speed", Mathf.Abs(horizontal));
        animator.SetBool("Jumping", Jump);
        horizontal = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
            Jump = true;
        }

        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
        }

        Flip();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }

    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

    private void Flip()
    {
        if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
        {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }

    }


来源: stackexchange

问:
Instagram embed doesn't work as it should
On IG you can click the three dots on any post, then choose embed. Let's use it in an html file and it should show the post BUT
It shows this window instead of the content.
here it is
The text means: view the post on instagram

Here is an example:

```<code><blockquote class="instagram-media" data-instgrm-captioned data-instgrm-permalink="https://www.instagram.com/p/ChEnCIirK-L/?utm_source=ig_embed&utm_campaign=loading" data-instgrm-version="14" style=" background:#FFF; border:0; border-radius:3px; box-shadow:0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15); margin: 1px; max-width:540px; min-width:326px; padding:0; width:99.375%; width:-webkit-calc(100% - 2px); width:calc(100% - 2px);"><div style="padding:16px;"> <a href="https://www.instagram.com/p/ChEnCIirK-L/?utm_source=ig_embed&utm_campaign=loading" style=" background:#FFFFFF; line-height:0; padding:0 0; text-align:center; text-decoration:none; width:100%;" target="_blank"> <div style=" display: flex; flex-direction: row; align-items: center;"> <div style="background-color: #F4F4F4; border-radius: 50%; flex-grow: 0; height: 40px; margin-right: 14px; width: 40px;"></div> <div style="display: flex; flex-direction: column; flex-grow: 1; justify-content: center;"> <div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; margin-bottom: 6px; width: 100px;"></div> <div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; width: 60px;"></div></div></div><div style="padding: 19% 0;"></div> <div style="display:block; height:50px; margin:0 auto 12px; width:50px;"><svg width="50px" height="50px" viewBox="0 0 60 60" version="1.1" xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink"><g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g transform="translate(-511.000000, -20.000000)" fill="#000000"><g><path d="M556.869,30.41 C554.814,30.41 553.148,32.076 553.148,34.131 C553.148,36.186 554.814,37.852 556.869,37.852 C558.924,37.852 560.59,36.186 560.59,34.131 C560.59,32.076 558.924,30.41 556.869,30.41 M541,60.657 C535.114,60.657 530.342,55.887 530.342,50 C530.342,44.114 535.114,39.342 541,39.342 C546.887,39.342 551.658,44.114 551.658,50 C551.658,55.887 546.887,60.657 541,60.657 M541,33.886 C532.1,33.886 524.886,41.1 524.886,50 C524.886,58.899 532.1,66.113 541,66.113 C549.9,66.113 557.115,58.899 557.115,50 C557.115,41.1 549.9,33.886 541,33.886 M565.378,62.101 C565.244,65.022 564.756,66.606 564.346,67.663 C563.803,69.06 563.154,70.057 562.106,71.106 C561.058,72.155 560.06,72.803 558.662,73.347 C557.607,73.757 556.021,74.244 553.102,74.378 C549.944,74.521 548.997,74.552 541,74.552 C533.003,74.552 532.056,74.521 528.898,74.378 C525.979,74.244 524.393,73.757 523.338,73.347 C521.94,72.803 520.942,72.155 519.894,71.106 C518.846,70.057 518.197,69.06 517.654,67.663 C517.244,66.606 516.755,65.022 516.623,62.101 C516.479,58.943 516.448,57.996 516.448,50 C516.448,42.003 516.479,41.056 516.623,37.899 C516.755,34.978 517.244,33.391 517.654,32.338 C518.197,30.938 518.846,29.942 519.894,28.894 C520.942,27.846 521.94,27.196 523.338,26.654 C524.393,26.244 525.979,25.756 528.898,25.623 C532.057,25.479 533.004,25.448 541,25.448 C548.997,25.448 549.943,25.479 553.102,25.623 C556.021,25.756 557.607,26.244 558.662,26.654 C560.06,27.196 561.058,27.846 562.106,28.894 C563.154,29.942 563.803,30.938 564.346,32.338 C564.756,33.391 565.244,34.978 565.378,37.899 C565.522,41.056 565.552,42.003 565.552,50 C565.552,57.996 565.522,58.943 565.378,62.101 M570.82,37.631 C570.674,34.438 570.167,32.258 569.425,30.349 C568.659,28.377 567.633,26.702 565.965,25.035 C564.297,23.368 562.623,22.342 560.652,21.575 C558.743,20.834 556.562,20.326 553.369,20.18 C550.169,20.033 549.148,20 541,20 C532.853,20 531.831,20.033 528.631,20.18 C525.438,20.326 523.257,20.834 521.349,21.575 C519.376,22.342 517.703,23.368 516.035,25.035 C514.368,26.702 513.342,28.377 512.574,30.349 C511.834,32.258 511.326,34.438 511.181,37.631 C511.035,40.831 511,41.851 511,50 C511,58.147 511.035,59.17 511.181,62.369 C511.326,65.562 511.834,67.743 512.574,69.651 C513.342,71.625 514.368,73.296 516.035,74.965 C517.703,76.634 519.376,77.658 521.349,78.425 C523.257,79.167 525.438,79.673 528.631,79.82 C531.831,79.965 532.853,80.001 541,80.001 C549.148,80.001 550.169,79.965 553.369,79.82 C556.562,79.673 558.743,79.167 560.652,78.425 C562.623,77.658 564.297,76.634 565.965,74.965 C567.633,73.296 568.659,71.625 569.425,69.651 C570.167,67.743 570.674,65.562 570.82,62.369 C570.966,59.17 571,58.147 571,50 C571,41.851 570.966,40.831 570.82,37.631"></path></g></g></g></svg></div><div style="padding-top: 8px;"> <div style=" color:#3897f0; font-family:Arial,sans-serif; font-size:14px; font-style:normal; font-weight:550; line-height:18px;">A bejegyzés megtekintése az Instagramon</div></div><div style="padding: 12.5% 0;"></div> <div style="display: flex; flex-direction: row; margin-bottom: 14px; align-items: center;"><div> <div style="background-color: #F4F4F4; border-radius: 50%; height: 12.5px; width: 12.5px; transform: translateX(0px) translateY(7px);"></div> <div style="background-color: #F4F4F4; height: 12.5px; transform: rotate(-45deg) translateX(3px) translateY(1px); width: 12.5px; flex-grow: 0; margin-right: 14px; margin-left: 2px;"></div> <div style="background-color: #F4F4F4; border-radius: 50%; height: 12.5px; width: 12.5px; transform: translateX(9px) translateY(-18px);"></div></div><div style="margin-left: 8px;"> <div style=" background-color: #F4F4F4; border-radius: 50%; flex-grow: 0; height: 20px; width: 20px;"></div> <div style=" width: 0; height: 0; border-top: 2px solid transparent; border-left: 6px solid #f4f4f4; border-bottom: 2px solid transparent; transform: translateX(16px) translateY(-4px) rotate(30deg)"></div></div><div style="margin-left: auto;"> <div style=" width: 0px; border-top: 8px solid #F4F4F4; border-right: 8px solid transparent; transform: translateY(16px);"></div> <div style=" background-color: #F4F4F4; flex-grow: 0; height: 12px; width: 16px; transform: translateY(-4px);"></div> <div style=" width: 0; height: 0; border-top: 8px solid #F4F4F4; border-left: 8px solid transparent; transform: translateY(-4px) translateX(8px);"></div></div></div> <div style="display: flex; flex-direction: column; flex-grow: 1; justify-content: center; margin-bottom: 24px;"> <div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; margin-bottom: 6px; width: 224px;"></div> <div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; width: 144px;"></div></div></a><p style=" color:#c9c8cd; font-family:Arial,sans-serif; font-size:14px; line-height:17px; margin-bottom:0; margin-top:8px; overflow:hidden; padding:8px 0 7px; text-align:center; text-overflow:ellipsis; white-space:nowrap;"><a href="https://www.instagram.com/p/ChEnCIirK-L/?utm_source=ig_embed&utm_campaign=loading" style=" color:#c9c8cd; font-family:Arial,sans-serif; font-size:14px; font-style:normal; font-weight:normal; line-height:17px; text-decoration:none;" target="_blank">RAVASZ (@vasvarypix) által megosztott bejegyzés</a></p></div></blockquote> <script async src="//www.instagram.com/embed.js"></script>
</code>```

Already tried https in the script tag.
Tried on azure static website, localhost, and on apache(university's server) with php.
On the latter it worked for 3minutes then all of a sudden it doesn't. I don't know how it can be.

ContentLicense: CC BY-SA 4.0

Body:
On IG you can click the three dots on any post, then choose embed. Let's use it in an html file and it should show the post BUT
It shows this window instead of the content.
here it is
The text means: view the post on instagram

Here is an example:

<svg width="50px" height="50px" viewBox="0 0 60 60" version="1.1" xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink"><g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g transform="translate(-511.000000, -20.000000)" fill="#000000"><g><path d="M556.869,30.41 C554.814,30.41 553.148,32.076 553.148,34.131 C553.148,36.186 554.814,37.852 556.869,37.852 C558.924,37.852 560.59,36.186 560.59,34.131 C560.59,32.076 558.924,30.41 556.869,30.41 M541,60.657 C535.114,60.657 530.342,55.887 530.342,50 C530.342,44.114 535.114,39.342 541,39.342 C546.887,39.342 551.658,44.114 551.658,50 C551.658,55.887 546.887,60.657 541,60.657 M541,33.886 C532.1,33.886 524.886,41.1 524.886,50 C524.886,58.899 532.1,66.113 541,66.113 C549.9,66.113 557.115,58.899 557.115,50 C557.115,41.1 549.9,33.886 541,33.886 M565.378,62.101 C565.244,65.022 564.756,66.606 564.346,67.663 C563.803,69.06 563.154,70.057 562.106,71.106 C561.058,72.155 560.06,72.803 558.662,73.347 C557.607,73.757 556.021,74.244 553.102,74.378 C549.944,74.521 548.997,74.552 541,74.552 C533.003,74.552 532.056,74.521 528.898,74.378 C525.979,74.244 524.393,73.757 523.338,73.347 C521.94,72.803 520.942,72.155 519.894,71.106 C518.846,70.057 518.197,69.06 517.654,67.663 C517.244,66.606 516.755,65.022 516.623,62.101 C516.479,58.943 516.448,57.996 516.448,50 C516.448,42.003 516.479,41.056 516.623,37.899 C516.755,34.978 517.244,33.391 517.654,32.338 C518.197,30.938 518.846,29.942 519.894,28.894 C520.942,27.846 521.94,27.196 523.338,26.654 C524.393,26.244 525.979,25.756 528.898,25.623 C532.057,25.479 533.004,25.448 541,25.448 C548.997,25.448 549.943,25.479 553.102,25.623 C556.021,25.756 557.607,26.244 558.662,26.654 C560.06,27.196 561.058,27.846 562.106,28.894 C563.154,29.942 563.803,30.938 564.346,32.338 C564.756,33.391 565.244,34.978 565.378,37.899 C565.522,41.056 565.552,42.003 565.552,50 C565.552,57.996 565.522,58.943 565.378,62.101 M570.82,37.631 C570.674,34.438 570.167,32.258 569.425,30.349 C568.659,28.377 567.633,26.702 565.965,25.035 C564.297,23.368 562.623,22.342 560.652,21.575 C558.743,20.834 556.562,20.326 553.369,20.18 C550.169,20.033 549.148,20 541,20 C532.853,20 531.831,20.033 528.631,20.18 C525.438,20.326 523.257,20.834 521.349,21.575 C519.376,22.342 517.703,23.368 516.035,25.035 C514.368,26.702 513.342,28.377 512.574,30.349 C511.834,32.258 511.326,34.438 511.181,37.631 C511.035,40.831 511,41.851 511,50 C511,58.147 511.035,59.17 511.181,62.369 C511.326,65.562 511.834,67.743 512.574,69.651 C513.342,71.625 514.368,73.296 516.035,74.965 C517.703,76.634 519.376,77.658 521.349,78.425 C523.257,79.167 525.438,79.673 528.631,79.82 C531.831,79.965 532.853,80.001 541,80.001 C549.148,80.001 550.169,79.965 553.369,79.82 C556.562,79.673 558.743,79.167 560.652,78.425 C562.623,77.658 564.297,76.634 565.965,74.965 C567.633,73.296 568.659,71.625 569.425,69.651 C570.167,67.743 570.674,65.562 570.82,62.369 C570.966,59.17 571,58.147 571,50 C571,41.851 570.966,40.831 570.82,37.631"></path></g></g></g></svg>

A bejegyzés megtekintése az Instagramon

RAVASZ (@vasvarypix) által megosztott bejegyzés

Already tried https in the script tag.
Tried on azure static website, localhost, and on apache(university's server) with php.
On the latter it worked for 3minutes then all of a sudden it doesn't. I don't know how it can be.


问:
get request failing when when I pass in randomly generated headers in python
Rather than manually specifying headers for my user_agents manually when sending a get request I'm trying to build a function that allows me to input correctly formed randomised headers.

I'm able to generate the headers and pass them across to my get request but I only ever return an exception. What am I doing wrong?

```<code>from bs4 import BeautifulSoup
import random
import requests
import logging

USER_AGENT_SCRAPER_BASE_URL = 'http://www.useragentstring.com/pages/useragentstring.php?name='
POPULAR_BROWSERS = ['Chrome', 'Firefox', 'Mozilla', 'Safari', 'Opera', 'Opera Mini', 'Edge', 'Internet Explorer']

def get_user_agent_strings_for_this_browser(browser):
    url = USER_AGENT_SCRAPER_BASE_URL + browser
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    user_agent_links = soup.find('div', {'id': 'liste'}).findAll('a')[:20]
    return [str(user_agent.text) for user_agent in user_agent_links]

def get_user_agents():
    user_agents = []
    for browser in POPULAR_BROWSERS:
        user_agents.extend(get_user_agent_strings_for_this_browser(browser))
    return user_agents[3:] # Remove the first 3 Google Header texts from Chrome's user agents

def http_client(random_user_agent):
    session = requests.Session()
    session.headers.update(
        {
        "User-Agent": random_user_agent
        }
    )
    return session

def make_request(session, proxy, baseurl: str, asin: str):
    try:
        response = session.get(baseurl + asin, proxies={"http": proxy, "https": proxy})
    except requests.RequestException:
        logging.warning(f"HTTP Error for {asin}")
        return
    if response.status_code == 200:
        return response, asin

def main():
    # Generate User-Agents
    proxy_user_agents = get_user_agents()
    # Randomly select an User-Agent from the collected user-agent strings
    random_user_agent = random.choice(proxy_user_agents)

    session = http_client(random_user_agent)

    proxy   = '51.79.50.22:9300'
    baseurl = 'https://www.amazon.co.uk/dp/'
    asin    = 'B00014FBTU'

    html = make_request(session, proxy, baseurl, asin)
    if html is None:
        logging.info("passing due to make_request error")
    else:
        print("success")

if __name__ == '__main__':
    main()
</code>```

Body:
Rather than manually specifying headers for my user_agents manually when sending a get request I'm trying to build a function that allows me to input correctly formed randomised headers.

I'm able to generate the headers and pass them across to my get request but I only ever return an exception. What am I doing wrong?

from bs4 import BeautifulSoup
import random
import requests
import logging

USER_AGENT_SCRAPER_BASE_URL = 'http://www.useragentstring.com/pages/useragentstring.php?name='
POPULAR_BROWSERS = ['Chrome', 'Firefox', 'Mozilla', 'Safari', 'Opera', 'Opera Mini', 'Edge', 'Internet Explorer']

def get_user_agent_strings_for_this_browser(browser):
    url = USER_AGENT_SCRAPER_BASE_URL + browser
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    user_agent_links = soup.find('div', {'id': 'liste'}).findAll('a')[:20]
    return [str(user_agent.text) for user_agent in user_agent_links]

def get_user_agents():
    user_agents = []
    for browser in POPULAR_BROWSERS:
        user_agents.extend(get_user_agent_strings_for_this_browser(browser))
    return user_agents[3:] # Remove the first 3 Google Header texts from Chrome's user agents

def http_client(random_user_agent):
    session = requests.Session()
    session.headers.update(
        {
        "User-Agent": random_user_agent
        }
    )
    return session

def make_request(session, proxy, baseurl: str, asin: str):
    try:
        response = session.get(baseurl + asin, proxies={"http": proxy, "https": proxy})
    except requests.RequestException:
        logging.warning(f"HTTP Error for {asin}")
        return
    if response.status_code == 200:
        return response, asin

def main():
    # Generate User-Agents
    proxy_user_agents = get_user_agents()
    # Randomly select an User-Agent from the collected user-agent strings
    random_user_agent = random.choice(proxy_user_agents)

    session = http_client(random_user_agent)

    proxy   = '51.79.50.22:9300'
    baseurl = 'https://www.amazon.co.uk/dp/'
    asin    = 'B00014FBTU'

    html = make_request(session, proxy, baseurl, asin)
    if html is None:
        logging.info("passing due to make_request error")
    else:
        print("success")

if __name__ == '__main__':
    main()


问:
OpenCV over WSL: select() timeout, usb usb1: Not yet implemented
When I try to run OpenCV over WSL using the usbipd_win library and a recompiled kernel (enabled UVC support), I get the error message [ WARN:0@30.423] global cap_v4l.cpp:1119 tryIoctl VIDEOIO(V4L2:/dev/video0): select() timeout.
dmesg:

```<code>usb usb1: Not yet implemented
usb usb1: Not yet implemented
... repeated "Not yet implemented" and "callbacks suppressed lines"
usb usb1: Not yet implemented
usb usb1: Not yet implemented
usb usb1: Not yet implemented
usb usb1: Not yet implemented
usb usb1: Not yet implemented
vhci_hcd: unlink->seqnum 26060
vhci_hcd: the urb (seqnum 26060) was already given back
vhci_hcd: unlink->seqnum 26065
vhci_hcd: the urb (seqnum 26065) was already given back
uvcvideo 1-1:1.1: Failed to resubmit video URB (-1).
vhci_hcd: unlink->seqnum 26067
vhci_hcd: the urb (seqnum 26067) was already given back
vhci_hcd: unlink->seqnum 26071
vhci_hcd: the urb (seqnum 26071) was already given back
vhci_hcd: unlink->seqnum 26073
vhci_hcd: the urb (seqnum 26073) was already given back
</code>```

uname -a:
Linux LAPTOP-0KQUO0A2 5.15.83.1-microsoft-standard-WSL2+ #1 SMP ...

Body:
When I try to run OpenCV over WSL using the usbipd_win library and a recompiled kernel (enabled UVC support), I get the error message [ WARN:0@30.423] global cap_v4l.cpp:1119 tryIoctl VIDEOIO(V4L2:/dev/video0): select() timeout.
dmesg:

usb usb1: Not yet implemented
usb usb1: Not yet implemented
... repeated "Not yet implemented" and "callbacks suppressed lines"
usb usb1: Not yet implemented
usb usb1: Not yet implemented
usb usb1: Not yet implemented
usb usb1: Not yet implemented
usb usb1: Not yet implemented
vhci_hcd: unlink->seqnum 26060
vhci_hcd: the urb (seqnum 26060) was already given back
vhci_hcd: unlink->seqnum 26065
vhci_hcd: the urb (seqnum 26065) was already given back
uvcvideo 1-1:1.1: Failed to resubmit video URB (-1).
vhci_hcd: unlink->seqnum 26067
vhci_hcd: the urb (seqnum 26067) was already given back
vhci_hcd: unlink->seqnum 26071
vhci_hcd: the urb (seqnum 26071) was already given back
vhci_hcd: unlink->seqnum 26073
vhci_hcd: the urb (seqnum 26073) was already given back

uname -a:
Linux LAPTOP-0KQUO0A2 5.15.83.1-microsoft-standard-WSL2+ #1 SMP ...


问:
how can i create a list from the lines read from a file in python with proper indexing
here I am reading data from a file IPmarks.txt which contains roll no and marks in different assignments of a student in the format
Rollno1,m1,m2,m3....... eg:- 2021264,10,20,50,100
Rollno2,m1,m2,m3....... eg:- 2021265,9,11,39,97

I want to read these lines from the file and create a list containing all the elements with indexing 0,1,2..... and so on
at index 0 - Rollno1, at index 1 - m1 and so on

I have tried the below code but the problem is that it contains the elements in a list but when i do print(grade[0])it prints 2021264,10,20,50,100(first line of file) and print(grade[0][0]) prints 2(first character of rollno1) instead of complete Rollno1 - 2021264

the question should be solved without importing any modules, should be done simply by file i/o

```<code>f = open("C:\\Users\\Administrator\\python\\IPmarks.txt","r")
grades = [x.strip() for x in f.readlines()]
print(grades[0])

</code>```

Body:
here I am reading data from a file IPmarks.txt which contains roll no and marks in different assignments of a student in the format
Rollno1,m1,m2,m3....... eg:- 2021264,10,20,50,100
Rollno2,m1,m2,m3....... eg:- 2021265,9,11,39,97

I want to read these lines from the file and create a list containing all the elements with indexing 0,1,2..... and so on
at index 0 - Rollno1, at index 1 - m1 and so on

I have tried the below code but the problem is that it contains the elements in a list but when i do print(grade[0])it prints 2021264,10,20,50,100(first line of file) and print(grade[0][0]) prints 2(first character of rollno1) instead of complete Rollno1 - 2021264

the question should be solved without importing any modules, should be done simply by file i/o

f = open("C:\\Users\\Administrator\\python\\IPmarks.txt","r")
grades = [x.strip() for x in f.readlines()]
print(grades[0])


问:
Problems with mongodb, toggle on/off code, Discord.js
```<code>const client = require("../../index");
const { ChatInputCommandInteraction, Discord } = require('discord.js');
const db = require("../../models/salvage/command");
const { loadCommands } = require("../../Handlers/commandHandler");
const schema = require('../../models/salvage/command')

module.exports = {
    name: "interactionCreate1",
    /**
     *
     * @param {ChatInputCommandInteraction} interaction
     */
        async execute(interaction, client, guild) {
        if(!interaction.isChatInputCommand()) return;
        const command = client.commands.get(interaction.commandName);

        const check = await db.findOne({ Guild: guild.message.id })
            if(check) {
                if(check.Cmds.includes(interaction.commandName)) return interaction.reply({content: "Comando desactivado!"})
                command.execute(interaction, client);
            } else {
                command.execute(interaction, client);
            }

        }
   }

</code>```

I have finished with the toggle on/off code (activate deactivate commands), but I have a problem, when deactivating a command it only sends a message that it deactivated but it is not like that, since if I put it again it sends it to me again, try everything, see in forums, youtube and nothing. I have the MongoDB connected to my bot perfectly, I really don't know what to do and I hope you can help me, thanks.

Body:
const client = require("../../index");
const { ChatInputCommandInteraction, Discord } = require('discord.js');
const db = require("../../models/salvage/command");
const { loadCommands } = require("../../Handlers/commandHandler");
const schema = require('../../models/salvage/command')

module.exports = {
    name: "interactionCreate1",
    /**
     *
     * @param {ChatInputCommandInteraction} interaction
     */
        async execute(interaction, client, guild) {
        if(!interaction.isChatInputCommand()) return;
        const command = client.commands.get(interaction.commandName);

        const check = await db.findOne({ Guild: guild.message.id })
            if(check) {
                if(check.Cmds.includes(interaction.commandName)) return interaction.reply({content: "Comando desactivado!"})
                command.execute(interaction, client);
            } else {
                command.execute(interaction, client);
            }

        }
   }

I have finished with the toggle on/off code (activate deactivate commands), but I have a problem, when deactivating a command it only sends a message that it deactivated but it is not like that, since if I put it again it sends it to me again, try everything, see in forums, youtube and nothing. I have the MongoDB connected to my bot perfectly, I really don't know what to do and I hope you can help me, thanks.


问:
Cannot find 'CLKComplicationTemplateExtraLargeCircularView' in scope
Hi so I'm building an iOS SwiftUI WatchKit App and I'm getting this error trying to build out
a complication

```<code>/*

Abstract:

 ComplicationController for Complication UI
*/
import Foundation
import SwiftUI
import ClockKit

class ComplicationController: NSObject, CLKComplicationDataSource {
    // MARK: - Complication Configuration

    func getComplicationDescriptors(handler: @escaping ([CLKComplicationDescriptor]) -> Void) {
        let descriptors = [
            CLKComplicationDescriptor(identifier: "complication", displayName: "PushUps", supportedFamilies: CLKComplicationFamily.allCases)
            // Multiple complication support can be added here with more descriptors
        ]

        print("getComplicationDescriptors")

        // Call the handler with the currently supported complication descriptors
        handler(descriptors)
    }

    func handleSharedComplicationDescriptors(_ complicationDescriptors: [CLKComplicationDescriptor]) {
        // Do any necessary work to support these newly shared complication descriptors
        print("handleSharedComplicationDescriptors")
    }

    // MARK: - Timeline Configuration

    func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
        // Call the handler with the last entry date you can currently provide or nil if you can't support future timelines
        print("getTimelineEndDate")
        handler(nil)
    }

    func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
        // Call the handler with your desired behavior when the device is locked
        print("getPrivacyBehavior")

        handler(.showOnLockScreen)
    }

    // MARK: - Timeline Population

    func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
        // Call the handler with the current timeline entry
        print("getCurrentTimelineEntry")
        handler(nil)
    }

    func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int,
                            withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
        // Call the handler with the timeline entries after the given date
        print("getTimelineEntries")
        handler(nil)
    }

    // MARK: - Sample Templates

    func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
        // This method will be called once per supported complication, and the results will be cached
        print("getLocalizableSampleTemplate")
        handler(nil)
    }

}

struct ComplicationView: View {
    @Environment(\.complicationRenderingMode) var renderingMode

    var body: some View {
        ZStack {

            if renderingMode == .fullColor {
                Circle()
                    .fill(Color.purple)
            } else {
                Circle()
                    .fill(LinearGradient(
                            gradient: Gradient(
                                colors: [Color.white.opacity(0.3),
                                         Color.white.opacity(1.0)]),
                            startPoint: .top,
                            endPoint: .bottom))
            }

            Image("coffee_template")
                .renderingMode(.template)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .foregroundColor(.yellow)
                .complicationForeground()
        }
    }
}

struct CompilcationController_Preview: PreviewProvider {
    static var previews: some View {
        Group {
            CLKComplicationTemplateExtraLargeCircularView(ComplicationView()).previewContext(faceColor: .red)
        }
    }
}
</code>```

Not sure what I'm missing import wise, perhaps something from CLK, I'll update with results.

I was trying to update the watch complication with a view, referencing Apple Docs:

https://developer.apple.com/documentation/clockkit/building_complications_with_swiftui

Body:
Hi so I'm building an iOS SwiftUI WatchKit App and I'm getting this error trying to build out
a complication

/*

Abstract:

 ComplicationController for Complication UI
*/
import Foundation
import SwiftUI
import ClockKit

class ComplicationController: NSObject, CLKComplicationDataSource {
    // MARK: - Complication Configuration

    func getComplicationDescriptors(handler: @escaping ([CLKComplicationDescriptor]) -> Void) {
        let descriptors = [
            CLKComplicationDescriptor(identifier: "complication", displayName: "PushUps", supportedFamilies: CLKComplicationFamily.allCases)
            // Multiple complication support can be added here with more descriptors
        ]

        print("getComplicationDescriptors")

        // Call the handler with the currently supported complication descriptors
        handler(descriptors)
    }

    func handleSharedComplicationDescriptors(_ complicationDescriptors: [CLKComplicationDescriptor]) {
        // Do any necessary work to support these newly shared complication descriptors
        print("handleSharedComplicationDescriptors")
    }

    // MARK: - Timeline Configuration

    func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
        // Call the handler with the last entry date you can currently provide or nil if you can't support future timelines
        print("getTimelineEndDate")
        handler(nil)
    }

    func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
        // Call the handler with your desired behavior when the device is locked
        print("getPrivacyBehavior")

        handler(.showOnLockScreen)
    }

    // MARK: - Timeline Population

    func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
        // Call the handler with the current timeline entry
        print("getCurrentTimelineEntry")
        handler(nil)
    }

    func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int,
                            withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
        // Call the handler with the timeline entries after the given date
        print("getTimelineEntries")
        handler(nil)
    }

    // MARK: - Sample Templates

    func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
        // This method will be called once per supported complication, and the results will be cached
        print("getLocalizableSampleTemplate")
        handler(nil)
    }

}

struct ComplicationView: View {
    @Environment(\.complicationRenderingMode) var renderingMode

    var body: some View {
        ZStack {

            if renderingMode == .fullColor {
                Circle()
                    .fill(Color.purple)
            } else {
                Circle()
                    .fill(LinearGradient(
                            gradient: Gradient(
                                colors: [Color.white.opacity(0.3),
                                         Color.white.opacity(1.0)]),
                            startPoint: .top,
                            endPoint: .bottom))
            }

            Image("coffee_template")
                .renderingMode(.template)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .foregroundColor(.yellow)
                .complicationForeground()
        }
    }
}

struct CompilcationController_Preview: PreviewProvider {
    static var previews: some View {
        Group {
            CLKComplicationTemplateExtraLargeCircularView(ComplicationView()).previewContext(faceColor: .red)
        }
    }
}

Not sure what I'm missing import wise, perhaps something from CLK, I'll update with results.

I was trying to update the watch complication with a view, referencing Apple Docs:

https://developer.apple.com/documentation/clockkit/building_complications_with_swiftui


问:
What can I do to fix my AWS CDK installation?
I may of somehow corrupted my AWS CDK system package. When attempting to cdk synth or cdk list I am getting the following traceback:

$ cdk list
Traceback (most recent call last):
  File "app.py", line 4, in <module>
    import aws_cdk as cdk
  File "/path/to/project/.venv/lib/python3.8/site-packages/aws_cdk/__init__.py", line 1285, in <module>
    from .cloud_assembly_schema import (
ImportError: cannot import name 'AssetManifestOptions' from 'aws_cdk.cloud_assembly_schema' (/path/to/project/.venv/lib/python3.8/site-packages/aws_cdk/cloud_assembly_schema/__init__.py)

Subprocess exited with error 1
```
<p>My .venv packages are as such:</p>
<pre class="lang-bash prettyprint-override"><code>$ pip3 freeze | grep aws
aws-cdk-lib==2.59.0
aws-cdk.asset-awscli-v1==2.2.49
aws-cdk.asset-kubectl-v20==2.1.1
aws-cdk.asset-node-proxy-agent-v5==2.0.38
aws-cdk.assets==1.187.0
aws-cdk.aws-cloudwatch==1.187.0
aws-cdk.aws-ec2==1.187.0
aws-cdk.aws-events==1.187.0
aws-cdk.aws-iam==1.187.0
aws-cdk.aws-kms==1.187.0
aws-cdk.aws-logs==1.187.0
aws-cdk.aws-networkfirewall==1.187.0
aws-cdk.aws-s3==1.187.0
aws-cdk.aws-s3-assets==1.187.0
aws-cdk.aws-ssm==1.187.0
aws-cdk.cloud-assembly-schema==1.187.0
aws-cdk.core==1.187.0
aws-cdk.cx-api==1.187.0
aws-cdk.region-info==1.187.0
</code>```

My system wide packages are as such:

user@host:$ deactivate
user@host:$ pip3 freeze | grep aws
user@host:$
```
<p>The difference between the last working state and today was that I tried to initialize another CDK project in a different directory. After initialization the other CDK project I began to face the same problem.</p>
<pre class="lang-bash prettyprint-override"><code>$ cdk --version
2.59.0 (build b24095d)
</code>```

Body:
I may of somehow corrupted my AWS CDK system package. When attempting to cdk synth or cdk list I am getting the following traceback:

$ cdk list
Traceback (most recent call last):
  File "app.py", line 4, in <module>
    import aws_cdk as cdk
  File "/path/to/project/.venv/lib/python3.8/site-packages/aws_cdk/__init__.py", line 1285, in <module>
    from .cloud_assembly_schema import (
ImportError: cannot import name 'AssetManifestOptions' from 'aws_cdk.cloud_assembly_schema' (/path/to/project/.venv/lib/python3.8/site-packages/aws_cdk/cloud_assembly_schema/__init__.py)

Subprocess exited with error 1

My .venv packages are as such:

$ pip3 freeze | grep aws
aws-cdk-lib==2.59.0
aws-cdk.asset-awscli-v1==2.2.49
aws-cdk.asset-kubectl-v20==2.1.1
aws-cdk.asset-node-proxy-agent-v5==2.0.38
aws-cdk.assets==1.187.0
aws-cdk.aws-cloudwatch==1.187.0
aws-cdk.aws-ec2==1.187.0
aws-cdk.aws-events==1.187.0
aws-cdk.aws-iam==1.187.0
aws-cdk.aws-kms==1.187.0
aws-cdk.aws-logs==1.187.0
aws-cdk.aws-networkfirewall==1.187.0
aws-cdk.aws-s3==1.187.0
aws-cdk.aws-s3-assets==1.187.0
aws-cdk.aws-ssm==1.187.0
aws-cdk.cloud-assembly-schema==1.187.0
aws-cdk.core==1.187.0
aws-cdk.cx-api==1.187.0
aws-cdk.region-info==1.187.0

My system wide packages are as such:

user@host:$ deactivate
user@host:$ pip3 freeze | grep aws
user@host:$

The difference between the last working state and today was that I tried to initialize another CDK project in a different directory. After initialization the other CDK project I began to face the same problem.

$ cdk --version
2.59.0 (build b24095d)


问:
Extract data from Word File in Python
I want to extract the following word file data using Python in such a way that the subject and body are stored in separate variables. The text 'subject' and 'body' should be excluded. For body, there should be a space after 'Hi (name)', and then comes the actual para and after that a space followed by salutation. The word file looks like this:

So I have performed this:

```<code>doc = docx.Document("sample email.docx")
all_paras = doc.paragraphs
subjectPara = doc.paragraphs[0].text
subjectIndex = subjectPara.find(":")
Subject = subjectPara[subjectIndex + 1 : -1].strip()
print(Subject)
</code>```

But the output for this is:

```<code>Introducing: “TikTok 4 Realtors” Packag
</code>```

It is excluding the last letter 'e' for some reason and I have no idea why.

Another problem is when I am doing the following for body:

```<code>doc = docx.Document("sample email.docx")
body = ""
all_paras = doc.paragraphs
for para in all_paras:
  if para != all_paras[0] and para.text.strip() != "Body:":
    body = body + '\n' + para.text
print(body.lstrip())
</code>```

And the result that I am getting is as follows:

```<code>Hi (name),
Please take a look at our new website: TikTok4Realtors.com.
Best Regards,
James O.
CEO/Founder
</code>```

The problem here is with the spaces that I require.

Title: Extract data from Word File in Python

Body:
I want to extract the following word file data using Python in such a way that the subject and body are stored in separate variables. The text 'subject' and 'body' should be excluded. For body, there should be a space after 'Hi (name)', and then comes the actual para and after that a space followed by salutation. The word file looks like this:

So I have performed this:

doc = docx.Document("sample email.docx")
all_paras = doc.paragraphs
subjectPara = doc.paragraphs[0].text
subjectIndex = subjectPara.find(":")
Subject = subjectPara[subjectIndex + 1 : -1].strip()
print(Subject)

But the output for this is:

Introducing: “TikTok 4 Realtors” Packag

It is excluding the last letter 'e' for some reason and I have no idea why.

Another problem is when I am doing the following for body:

doc = docx.Document("sample email.docx")
body = ""
all_paras = doc.paragraphs
for para in all_paras:
  if para != all_paras[0] and para.text.strip() != "Body:":
    body = body + '\n' + para.text
print(body.lstrip())

And the result that I am getting is as follows:

Hi (name),
Please take a look at our new website: TikTok4Realtors.com.
Best Regards,
James O.
CEO/Founder

The problem here is with the spaces that I require.


问:
error: ushort format requires 0 <= number <= (0x7fff * 2 + 1)
I'm trying

```<code>waveform, sample_rate = plot_audio(filename)
ipd.Audio(waveform.numpy(), rate=sample_rate)
</code>```

but getting below error

error: ushort format requires 0 <= number <= (0x7fff * 2 + 1)

what does this error mean?

Body:
I'm trying

waveform, sample_rate = plot_audio(filename)
ipd.Audio(waveform.numpy(), rate=sample_rate)

but getting below error

error: ushort format requires 0 <= number <= (0x7fff * 2 + 1)

what does this error mean?


问:
matplolib ticks latex bold with python 3.10
I am struggling with matplotlib and latex font.
I would like to have all in bold and in latex style. I have, consequently done as follows:

```<code>import matplotlib
import pandas as pd
import matplotlib.pyplot as plt

plt.rc('font', family='serif',size=32)
matplotlib.rc('text', usetex=True)
matplotlib.rc('legend', fontsize=32)
matplotlib.rcParams['text.latex.preamble'] = r"\usepackage{bm} \usepackage{amsmath}"

fig, ax = plt.subplots(figsize=(22,18))
</code>```

This is however the result:

I have tried some options, but all seem referring to old matplolib version. I had a look to the official matpltlib page here but I can not understand how to set the bold option.
What do you think about?

Body:
I am struggling with matplotlib and latex font.
I would like to have all in bold and in latex style. I have, consequently done as follows:

import matplotlib
import pandas as pd
import matplotlib.pyplot as plt

plt.rc('font', family='serif',size=32)
matplotlib.rc('text', usetex=True)
matplotlib.rc('legend', fontsize=32)
matplotlib.rcParams['text.latex.preamble'] = r"\usepackage{bm} \usepackage{amsmath}"

fig, ax = plt.subplots(figsize=(22,18))

This is however the result:

I have tried some options, but all seem referring to old matplolib version. I had a look to the official matpltlib page here but I can not understand how to set the bold option.
What do you think about?


问:
Mongoose adding todays date in schema
I try to add todays date in the schema, and no luck when sending it in POSTMAN.

Model:

```<code>import mongoose from "mongoose";

   function getDate(): string {
const now = new Date();
const fullDate = now.toDateString();
return fullDate;
   }

  export interface IAccountOperationModel extends mongoose.Document {
accountNumber: string;
operationType: object;
date: Date;
     }

export const AccountOperationSchema = new mongoose.Schema<IAccountOperationModel>({
accountNumber: {
    type: String,
    required: [true, "Missing account number"],
},
operationType: {
    withdrawl: {
        type: String,
        date: { type: Date, default: getDate() }
    },
    deposit: {
        type: String,
    },
    loan: {
        type: String,
    }
}
   }, {
versionKey: false
   });

      export const AccountOperationModel = mongoose.model<IAccountOperationModel>
     ("AccountOperationModel", AccountOperationSchema, "account-operations");
</code>```

Controller:

```<code>import express, { Request, Response, NextFunction } from "express";
import { AccountOperationModel } from "../4-models/account-operation-model";
import logic from "../5-logic/logic";

 const router = express.Router();

 // GET http://localhost:3001/api/accounts/:accountId
 router.get("/accounts/:accountId", async (request: Request, response: Response, next:
 NextFunction) => {
try {
    const accountId = request.params.accountId;
    const account = await logic.getAllOperations(accountId);
    response.json(account);
}
catch (err: any) {
    next(err);
}
});

 // POST http://localhost:3001/api/accounts
  router.post("/accounts", async (request: Request, response: Response, next:
 NextFunction) =>
 {
try {
    const account = new AccountOperationModel(request.body);
    const addedAccount = await logic.addAccountOperation(account);
    response.status(201).json(addedAccount);
}
catch (err: any) {
    next(err);
}
 });

export default router;
</code>```

Tried to use timestamps but it's not adding it to every withdraw or deposit but to whole object.
I need to add it to any operation type.
Tried with the function as added, tried another few ways but still no luck.
I know its better to add the date in the backend rather than frontend.

Title: Mongoose adding todays date in schema

Body:
I try to add todays date in the schema, and no luck when sending it in POSTMAN.

Model:

import mongoose from "mongoose";

   function getDate(): string {
const now = new Date();
const fullDate = now.toDateString();
return fullDate;
   }

  export interface IAccountOperationModel extends mongoose.Document {
accountNumber: string;
operationType: object;
date: Date;
     }

export const AccountOperationSchema = new mongoose.Schema<IAccountOperationModel>({
accountNumber: {
    type: String,
    required: [true, "Missing account number"],
},
operationType: {
    withdrawl: {
        type: String,
        date: { type: Date, default: getDate() }
    },
    deposit: {
        type: String,
    },
    loan: {
        type: String,
    }
}
   }, {
versionKey: false
   });

      export const AccountOperationModel = mongoose.model<IAccountOperationModel>
     ("AccountOperationModel", AccountOperationSchema, "account-operations");

Controller:

import express, { Request, Response, NextFunction } from "express";
import { AccountOperationModel } from "../4-models/account-operation-model";
import logic from "../5-logic/logic";

 const router = express.Router();

 // GET http://localhost:3001/api/accounts/:accountId
 router.get("/accounts/:accountId", async (request: Request, response: Response, next:
 NextFunction) => {
try {
    const accountId = request.params.accountId;
    const account = await logic.getAllOperations(accountId);
    response.json(account);
}
catch (err: any) {
    next(err);
}
});

 // POST http://localhost:3001/api/accounts
  router.post("/accounts", async (request: Request, response: Response, next:
 NextFunction) =>
 {
try {
    const account = new AccountOperationModel(request.body);
    const addedAccount = await logic.addAccountOperation(account);
    response.status(201).json(addedAccount);
}
catch (err: any) {
    next(err);
}
 });

export default router;

Tried to use timestamps but it's not adding it to every withdraw or deposit but to whole object.
I need to add it to any operation type.
Tried with the function as added, tried another few ways but still no luck.
I know its better to add the date in the backend rather than frontend.


问:
From Screen Recording on Notebook to Instagram Reels and TikTok
I am trying to record my website contruction using a time lapse effect and then uploading in Reels on instagram.

But, I am not a technological girl and I need help:

I am screen recording my notebook screen. How do I edit this video in which i in mp4 format to match the entire screen in a smartphone, because I need to post on Reels and Tiktok?

How can I do this from notebook screen record video to instagram reels and tik tok?

Any help and tips would be amazing.


问:
How to add two css variables and assign it to another variable
I have a scenario in which I need to add values(in pixels) and assign them to another variable and reuse this new variable in CSS.

Expected: width and height should use variable values of --width and --height respectively

But currently, the expected behavior is not observed. ( run the code snippet to see this )

.div {
  --a: 200px;
  --b: 100px;

  --width: calc(var(--a)+var(--b));
  --height: calc(var(--a)-var(--b));

  width: var(--width);
  height: var(--height);

  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div">Styles are not being applied on me. I need to be more taller and wider according to CSS. </div></code>```

Body:
I have a scenario in which I need to add values(in pixels) and assign them to another variable and reuse this new variable in CSS.

Expected: width and height should use variable values of --width and --height respectively

But currently, the expected behavior is not observed. ( run the code snippet to see this )

.div {
  --a: 200px;
  --b: 100px;

  --width: calc(var(--a)+var(--b));
  --height: calc(var(--a)-var(--b));

  width: var(--width);
  height: var(--height);

  background-color: green;
}

Styles are not being applied on me. I need to be more taller and wider according to CSS.


问:
3D pipe drawing in Python/Matlab
I'm working on this paper in which I'm simulating Vibration of Pipe Elbows with FEM, originally I made this in Matlab but then I migrated to Python.

Basically my data is stored in nodes, like this, where I have the coordinates of the node on the centerline of the pipe and the coordinates of the centerline of the cross-section.

I would like to use these data to make a smooth surface plot like this other one from this paper. But I'm not really sure about what function of Matplotlib I could use to work this out.

Somebody has an idea for this?

Title: 3D pipe drawing in Python/Matlab


问:
Passport only redirect "failureRedirect: '/login?fail=true'"
I'm using Passport js local strategy but I can't redirect from my admin page. it always fails even if the login and password are correct, below is the auth.js and login.js code

login.js

```<code>router.get('/', (req, res, next) =>{
    if (req.query.fail){
        res.render('admin/login', {layout: 'admin.hbs', message: "Usuario e/ou Senha invalidos"});
    }else{
        res.render('admin/login', {layout: 'admin.hbs', message: null});
    }

})

router.post('/',
  passport.authenticate('local', { failureRedirect: '/login?fail=true' }),
  function(req, res) {
    res.redirect('/admin');
  });

</code>```

auth.js

```<code>
const users = [{
    _id: 123,
    username: "adm",
    password: hashedPassword
}];

console.log(users);

module.exports = function(passport){
    function findUser(username){
        return users.find(item => item.username === username);
    }

    function findUserById(id){
        return users.find(item => item._id === id);
    }

    passport.serializeUser((user, done) => {
        done(null, user._id);
    });

    passport.deserializeUser((id, done) => {
        try {
            const user = findUserById(id);
                done(null, user);
        } catch (err) {
            console.log(err);
            return done(err, null)
        }
    });

    passport.use(new localStrategy({
        usernameField: 'username',
        passwordField: 'password',
    },
    (username, password, done) => {
        try{
            const user = findUser(username).then(user);
            if(!user) return done(null, false);

            const isValid = bcrypt.compare(password, user.password);
                if(!isValid) return done(null, false);
                return done(null, user);
        }
        catch(err){
            console.log(err);
            return done(err, false)

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

I don't know why it's not working, I wanted help getting into the admin page

Body:
I'm using Passport js local strategy but I can't redirect from my admin page. it always fails even if the login and password are correct, below is the auth.js and login.js code

login.js

router.get('/', (req, res, next) =>{
    if (req.query.fail){
        res.render('admin/login', {layout: 'admin.hbs', message: "Usuario e/ou Senha invalidos"});
    }else{
        res.render('admin/login', {layout: 'admin.hbs', message: null});
    }

})

router.post('/',
  passport.authenticate('local', { failureRedirect: '/login?fail=true' }),
  function(req, res) {
    res.redirect('/admin');
  });

auth.js

const users = [{
    _id: 123,
    username: "adm",
    password: hashedPassword
}];

console.log(users);

module.exports = function(passport){
    function findUser(username){
        return users.find(item => item.username === username);
    }

    function findUserById(id){
        return users.find(item => item._id === id);
    }

    passport.serializeUser((user, done) => {
        done(null, user._id);
    });

    passport.deserializeUser((id, done) => {
        try {
            const user = findUserById(id);
                done(null, user);
        } catch (err) {
            console.log(err);
            return done(err, null)
        }
    });

    passport.use(new localStrategy({
        usernameField: 'username',
        passwordField: 'password',
    },
    (username, password, done) => {
        try{
            const user = findUser(username).then(user);
            if(!user) return done(null, false);

            const isValid = bcrypt.compare(password, user.password);
                if(!isValid) return done(null, false);
                return done(null, user);
        }
        catch(err){
            console.log(err);
            return done(err, false)

}}));
}

I don't know why it's not working, I wanted help getting into the admin page


问:
Failed to find data adapter that can handle input: <class 'NoneType'>, <class 'NoneType'> validation_generator
I have been trying to create model to classify a set of images into 10 classes. I am using CNN to do the same. I am stuck with the above error and I am not able to proceed further. Please help me out. I think the problem is with the validation_generator. But I tried everything possible and I am not able to fix it.

The code that I have written:

```<code>import tensorflow as tf
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageEnhance
import tensorflow.keras as keras
train_path = "/Users/user/Desktop/train"
test_path = "/Users/user/Desktop/val"
model = tf.keras.models.Sequential([
    # Note the input shape is the desired size of the image 256x256 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(256, 256, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The third convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fourth convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.5),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

# Print the model summary
model.summary()

# Set the training parameters
model.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

from keras_preprocessing.image import ImageDataGenerator

TRAINING_DIR = train_path
training_datagen = ImageDataGenerator(
      rescale = 1./255,
      rotation_range=10,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0,
      zoom_range=0.2,
      horizontal_flip=False,
      fill_mode='nearest')

VALIDATION_DIR = test_path
validation_datagen = ImageDataGenerator(rescale = 1./255)

train_generator = training_datagen.flow_from_directory(
    TRAINING_DIR,
    target_size=(256,256),
    class_mode='categorical',
  batch_size=64
)

validation_generator = validation_datagen.flow_from_directory(
    VALIDATION_DIR,
    target_size=(256,256),
    class_mode='categorical',
  batch_size=64
)

# the error raises here
history = model.fit(epochs=25, validation_data = validation_generator, verbose = 1, validation_steps=3)

</code>```

Body:
I have been trying to create model to classify a set of images into 10 classes. I am using CNN to do the same. I am stuck with the above error and I am not able to proceed further. Please help me out. I think the problem is with the validation_generator. But I tried everything possible and I am not able to fix it.

The code that I have written:

import tensorflow as tf
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageEnhance
import tensorflow.keras as keras
train_path = "/Users/user/Desktop/train"
test_path = "/Users/user/Desktop/val"
model = tf.keras.models.Sequential([
    # Note the input shape is the desired size of the image 256x256 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(256, 256, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The third convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fourth convolution
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dropout(0.5),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

# Print the model summary
model.summary()

# Set the training parameters
model.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

from keras_preprocessing.image import ImageDataGenerator

TRAINING_DIR = train_path
training_datagen = ImageDataGenerator(
      rescale = 1./255,
      rotation_range=10,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0,
      zoom_range=0.2,
      horizontal_flip=False,
      fill_mode='nearest')

VALIDATION_DIR = test_path
validation_datagen = ImageDataGenerator(rescale = 1./255)

train_generator = training_datagen.flow_from_directory(
    TRAINING_DIR,
    target_size=(256,256),
    class_mode='categorical',
  batch_size=64
)

validation_generator = validation_datagen.flow_from_directory(
    VALIDATION_DIR,
    target_size=(256,256),
    class_mode='categorical',
  batch_size=64
)

# the error raises here
history = model.fit(epochs=25, validation_data = validation_generator, verbose = 1, validation_steps=3)


问:
error launching a robotframework script [OSERROR 216] error
I have a problem when launching my robotframework file. This is an [OSERROR 216] error. The browser didn't even open. The browser didn't even open.
the error message is

OSError: [WinError 216] This version of %1 is not compatible with the version of Windows currently running. Check your computer's system information, then contact the software editor.
the software editor

My robotframework script is supposed to open a browser and then close it


问:
NetSuite OAuth 2.0 for Website what Flow Authentication to use?
I am upgrading an older OAuth 1.0 TBA setup to OAuth 2.0 without the TBA.

I have on the Sandbox the Client Credentials Flow working. This setup will not work on the production, since the web users are not logged in on NetSuite or NetSuite clients. The refresh token currently expires every seven days, I can’t create a backend script that somehow opens a Session on NetSuite (with my credentials logging into NetSuite), redirects the URL, and gets a code parameter value so I can finally generate a new refresh token. That seems extreme and not secure.

Is there something I am missing on the whole token refresh?

That brings me to another question. NetSuite is a bit confusing to me. If I want to try out the OAuth 2.0 Client Credentials Flow, can I just create a new Integration application? Set up a new code base structure without crashing the one that I currently have working.


问:
How can I avoid quotes in useDelimeter() method?
I have a file and I need to get objects from it. File example:

```<code>"Dude1", 17, student
Dude2, 23, worker
"Dude, Dude", 11, student
</code>```

What delimeter I need to use to avoid quotation marks and don't split sting in it?

It would be perfect to get this as a result for this example:

```<code>Object1:
name: Dude1
age: 17
work: student

Object2:
name: Dude2
age: 23
work: worker

Object3:
name: Dude, Dude
age: 11
work: student
</code>```

I know how to get objects from a file. I understand that I need to use regex in delimiter, but I don't understand what exactly it should be like

Body:
I have a file and I need to get objects from it. File example:

"Dude1", 17, student
Dude2, 23, worker
"Dude, Dude", 11, student

What delimeter I need to use to avoid quotation marks and don't split sting in it?

It would be perfect to get this as a result for this example:

Object1:
name: Dude1
age: 17
work: student

Object2:
name: Dude2
age: 23
work: worker

Object3:
name: Dude, Dude
age: 11
work: student

I know how to get objects from a file. I understand that I need to use regex in delimiter, but I don't understand what exactly it should be like


问:
Problem with implementation of capsule layer for image segmentation
I want to use the following capsule layer class for implementing the image segmentation:

```<code>class ConvCapsuleLayer(layers.Layer):
    def __init__(self, kernel_size, num_capsule, num_atoms, strides=1, padding='same', routings=3,
                 kernel_initializer='he_normal', **kwargs):
        super(ConvCapsuleLayer, self).__init__(**kwargs)
        self.kernel_size = kernel_size
        self.num_capsule = num_capsule
        self.num_atoms = num_atoms
        self.strides = strides
        self.padding = padding
        self.routings = routings
        self.kernel_initializer = initializers.get(kernel_initializer)

    def build(self, input_shape):
        assert len(input_shape) == 5, "The input Tensor should have shape=[None, input_height, input_width," \
                                      " input_num_capsule, input_num_atoms]"
        self.input_height = input_shape[1]
        self.input_width = input_shape[2]
        self.input_num_capsule = input_shape[3]
        self.input_num_atoms = input_shape[4]

        # Transform matrix
        self.W = self.add_weight(shape=[self.kernel_size, self.kernel_size,
                                 self.input_num_atoms, self.num_capsule * self.num_atoms],
                                 initializer=self.kernel_initializer,
                                 name='W')

        self.b = self.add_weight(shape=[1, 1, self.num_capsule, self.num_atoms],
                                 initializer=initializers.constant(0.1),
                                 name='b')

        self.built = True

    def call(self, input_tensor, training=None):

        input_transposed = tf.transpose(input_tensor, [3, 0, 1, 2, 4])
        input_shape = K.shape(input_transposed)
        input_tensor_reshaped = K.reshape(input_transposed, [
            input_shape[0] * input_shape[1], self.input_height, self.input_width, self.input_num_atoms])
        input_tensor_reshaped.set_shape((None, self.input_height, self.input_width, self.input_num_atoms))

        conv = K.conv2d(input_tensor_reshaped, self.W, (self.strides, self.strides),
                        padding=self.padding, data_format='channels_last')

        votes_shape = K.shape(conv)
        _, conv_height, conv_width, _ = conv.get_shape()

        votes = K.reshape(conv, [input_shape[1], input_shape[0], votes_shape[1], votes_shape[2],
                                 self.num_capsule, self.num_atoms])
        votes.set_shape((None, self.input_num_capsule, conv_height.value, conv_width.value,
                         self.num_capsule, self.num_atoms))

        logit_shape = K.stack([
            input_shape[1], input_shape[0], votes_shape[1], votes_shape[2], self.num_capsule])
        biases_replicated = K.tile(self.b, [conv_height.value, conv_width.value, 1, 1])

        activations = update_routing(
            votes=votes,
            biases=biases_replicated,
            logit_shape=logit_shape,
            num_dims=6,
            input_dim=self.input_num_capsule,
            output_dim=self.num_capsule,
            num_routing=self.routings)

        return activations

    def compute_output_shape(self, input_shape):
        space = input_shape[1:-2]
        new_space = []
        for i in range(len(space)):
            new_dim = conv_output_length(
                space[i],
                self.kernel_size,
                padding=self.padding,
                stride=self.strides,
                dilation=1)
            new_space.append(new_dim)

        return (input_shape[0],) + tuple(new_space) + (self.num_capsule, self.num_atoms)

    def get_config(self):
        config = {
            'kernel_size': self.kernel_size,
            'num_capsule': self.num_capsule,
            'num_atoms': self.num_atoms,
            'strides': self.strides,
            'padding': self.padding,
            'routings': self.routings,
            'kernel_initializer': initializers.serialize(self.kernel_initializer)
        }
        base_config = super(ConvCapsuleLayer, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))
</code>```

This is the main code, in which the output of the first convolutional layer is reshaped and introduced to the capsule layer (ConvCapsuleLayer).

```<code>input_shape = (512, 512, 3)
x = layers.Input(shape= input_shape)
conv1 = layers.Conv2D(filters=16, kernel_size=5, strides=1, padding='same', activation='relu', name='conv1')(x)

_, H, W, C = conv1.get_shape()  # _, 512, 512, 16
conv1_reshaped = layers.Reshape((H, W, 1, C))(conv1) # (?, 512, 512, 1, 16)

primary_caps = ConvCapsuleLayer(kernel_size=5, num_capsule=2, num_atoms=16, strides=2, padding='same',
                                routings=1, name='primarycaps')(conv1_reshaped)
</code>```

After running the code the following error occurs in the last layer:

```<code>Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-c4a69eb08460> in <module>
      7
      8 primary_caps = ConvCapsuleLayer(kernel_size=5, num_capsule=2, num_atoms=16, strides=2, padding='same',
----> 9                                 routings=1, name='primarycaps')(conv1_reshaped)
     10

c:\Users\Microsoft\anaconda3\envs\tf-gpu1\lib\site-packages\keras\engine\base_layer.py in __call__(self, inputs, **kwargs)
    461                                          'You can build it manually via: '
    462                                          '`layer.build(batch_input_shape)`')
--> 463                 self.build(unpack_singleton(input_shapes))
    464                 self.built = True
    465

d:\My_Codes\my_segcaps\capsule_layers.py in build(self, input_shape)
    114                                  self.input_num_atoms, self.num_capsule * self.num_atoms],
    115                                  initializer=self.kernel_initializer,
--> 116                                  name='W')
    117
    118         self.b = self.add_weight(shape=[1, 1, self.num_capsule, self.num_atoms],

c:\Users\Microsoft\anaconda3\envs\tf-gpu1\lib\site-packages\keras\engine\base_layer.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint)
    277         if dtype is None:
    278             dtype = self.dtype
...
--> 556                     "please use // instead".format(type(other).__name__))
    557
    558   def __mod__(self, other):

TypeError: unsupported operand type(s) for /: 'float' and 'Dimension', please use // instead
</code>```

How can I solve the problem?

Body:
I want to use the following capsule layer class for implementing the image segmentation:

class ConvCapsuleLayer(layers.Layer):
    def __init__(self, kernel_size, num_capsule, num_atoms, strides=1, padding='same', routings=3,
                 kernel_initializer='he_normal', **kwargs):
        super(ConvCapsuleLayer, self).__init__(**kwargs)
        self.kernel_size = kernel_size
        self.num_capsule = num_capsule
        self.num_atoms = num_atoms
        self.strides = strides
        self.padding = padding
        self.routings = routings
        self.kernel_initializer = initializers.get(kernel_initializer)

    def build(self, input_shape):
        assert len(input_shape) == 5, "The input Tensor should have shape=[None, input_height, input_width," \
                                      " input_num_capsule, input_num_atoms]"
        self.input_height = input_shape[1]
        self.input_width = input_shape[2]
        self.input_num_capsule = input_shape[3]
        self.input_num_atoms = input_shape[4]

        # Transform matrix
        self.W = self.add_weight(shape=[self.kernel_size, self.kernel_size,
                                 self.input_num_atoms, self.num_capsule * self.num_atoms],
                                 initializer=self.kernel_initializer,
                                 name='W')

        self.b = self.add_weight(shape=[1, 1, self.num_capsule, self.num_atoms],
                                 initializer=initializers.constant(0.1),
                                 name='b')

        self.built = True

    def call(self, input_tensor, training=None):

        input_transposed = tf.transpose(input_tensor, [3, 0, 1, 2, 4])
        input_shape = K.shape(input_transposed)
        input_tensor_reshaped = K.reshape(input_transposed, [
            input_shape[0] * input_shape[1], self.input_height, self.input_width, self.input_num_atoms])
        input_tensor_reshaped.set_shape((None, self.input_height, self.input_width, self.input_num_atoms))

        conv = K.conv2d(input_tensor_reshaped, self.W, (self.strides, self.strides),
                        padding=self.padding, data_format='channels_last')

        votes_shape = K.shape(conv)
        _, conv_height, conv_width, _ = conv.get_shape()

        votes = K.reshape(conv, [input_shape[1], input_shape[0], votes_shape[1], votes_shape[2],
                                 self.num_capsule, self.num_atoms])
        votes.set_shape((None, self.input_num_capsule, conv_height.value, conv_width.value,
                         self.num_capsule, self.num_atoms))

        logit_shape = K.stack([
            input_shape[1], input_shape[0], votes_shape[1], votes_shape[2], self.num_capsule])
        biases_replicated = K.tile(self.b, [conv_height.value, conv_width.value, 1, 1])

        activations = update_routing(
            votes=votes,
            biases=biases_replicated,
            logit_shape=logit_shape,
            num_dims=6,
            input_dim=self.input_num_capsule,
            output_dim=self.num_capsule,
            num_routing=self.routings)

        return activations

    def compute_output_shape(self, input_shape):
        space = input_shape[1:-2]
        new_space = []
        for i in range(len(space)):
            new_dim = conv_output_length(
                space[i],
                self.kernel_size,
                padding=self.padding,
                stride=self.strides,
                dilation=1)
            new_space.append(new_dim)

        return (input_shape[0],) + tuple(new_space) + (self.num_capsule, self.num_atoms)

    def get_config(self):
        config = {
            'kernel_size': self.kernel_size,
            'num_capsule': self.num_capsule,
            'num_atoms': self.num_atoms,
            'strides': self.strides,
            'padding': self.padding,
            'routings': self.routings,
            'kernel_initializer': initializers.serialize(self.kernel_initializer)
        }
        base_config = super(ConvCapsuleLayer, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

This is the main code, in which the output of the first convolutional layer is reshaped and introduced to the capsule layer (ConvCapsuleLayer).

input_shape = (512, 512, 3)
x = layers.Input(shape= input_shape)
conv1 = layers.Conv2D(filters=16, kernel_size=5, strides=1, padding='same', activation='relu', name='conv1')(x)

_, H, W, C = conv1.get_shape()  # _, 512, 512, 16
conv1_reshaped = layers.Reshape((H, W, 1, C))(conv1) # (?, 512, 512, 1, 16)

primary_caps = ConvCapsuleLayer(kernel_size=5, num_capsule=2, num_atoms=16, strides=2, padding='same',
                                routings=1, name='primarycaps')(conv1_reshaped)

After running the code the following error occurs in the last layer:

Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-c4a69eb08460> in <module>
      7
      8 primary_caps = ConvCapsuleLayer(kernel_size=5, num_capsule=2, num_atoms=16, strides=2, padding='same',
----> 9                                 routings=1, name='primarycaps')(conv1_reshaped)
     10

c:\Users\Microsoft\anaconda3\envs\tf-gpu1\lib\site-packages\keras\engine\base_layer.py in __call__(self, inputs, **kwargs)
    461                                          'You can build it manually via: '
    462                                          '`layer.build(batch_input_shape)`')
--> 463                 self.build(unpack_singleton(input_shapes))
    464                 self.built = True
    465

d:\My_Codes\my_segcaps\capsule_layers.py in build(self, input_shape)
    114                                  self.input_num_atoms, self.num_capsule * self.num_atoms],
    115                                  initializer=self.kernel_initializer,
--> 116                                  name='W')
    117
    118         self.b = self.add_weight(shape=[1, 1, self.num_capsule, self.num_atoms],

c:\Users\Microsoft\anaconda3\envs\tf-gpu1\lib\site-packages\keras\engine\base_layer.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint)
    277         if dtype is None:
    278             dtype = self.dtype
...
--> 556                     "please use // instead".format(type(other).__name__))
    557
    558   def __mod__(self, other):

TypeError: unsupported operand type(s) for /: 'float' and 'Dimension', please use // instead

How can I solve the problem?


问:
Measure quantity of substructure by scale length in map
Given a grayscale map with features at different scales, I would like an approximate measure of how much substructure exists in the map given different radii.

As a toy model, I generated this map with a few peaks modeled by Gaussians of multiple variances, as seen in the image. I am looking for a way to quantify the amount of substructure in the map by radii, that would ideally produce a graph of map height (sum of value of pixels) vs radius, with peaks at radii approximately corresponding to the width of the Gaussians.

The real map is complex, yet visual inspection reveals the presence of substructure at certain scales.

Any ideas or suggestions would be greatly appreciated.

I have tried morphological operations, such as opening followed by white tophat using a disk, to isolate features within a certain scale. I repeated the operation for different scales and summed the result. It seems to work sometimes, for example when there is minimal overlap among the features.

I have also tried to measure the scale of substructures using spectral analysis. It works well enough when the substructure is distributed by a repeated pattern, such as sinusoidal wave. But for the toy model above, the results are hard to interpret.


问:
Access full Next.js errors in production deployment
I'm debugging a tricky issue that only occurs with a Next.js project when in production/deployed to Vercel. Minification is interfering in my ability to debug the issue since issues are reported as:

```<code>Uncaught Error: Minified React error #425; visit
https://reactjs.org/docs/error-decoder.html?invariant=425 for the
full message or use the non-minified dev environment for full
errors and additional helpful warnings.
</code>```

How can I access the full errors and "additional helpful warnings" in production?

Is it possible for builds to be done in development mode instead? Setting the build command as NODE_ENV=development next build doesn't seem to work, nor does setting the NODE_ENV env variable to development  in Vercel

Alternatively, is it possible to disable minification on production builds?

Setting Webpack to optimization: { minimize: false } causes the build to output a log indicating Production code optimization has been disabled in your project, however the above "Minified React error" message still appear.

Body:
I'm debugging a tricky issue that only occurs with a Next.js project when in production/deployed to Vercel. Minification is interfering in my ability to debug the issue since issues are reported as:

Uncaught Error: Minified React error #425; visit
https://reactjs.org/docs/error-decoder.html?invariant=425 for the
full message or use the non-minified dev environment for full
errors and additional helpful warnings.

How can I access the full errors and "additional helpful warnings" in production?

Is it possible for builds to be done in development mode instead? Setting the build command as NODE_ENV=development next build doesn't seem to work, nor does setting the NODE_ENV env variable to development  in Vercel

Alternatively, is it possible to disable minification on production builds?

Setting Webpack to optimization: { minimize: false } causes the build to output a log indicating Production code optimization has been disabled in your project, however the above "Minified React error" message still appear.


问:
Deprecated: Return type of WPSC_Purchase_Log_Notes::current() should either be compatible with Iterator::current(): mixed
The above depreciation notice is displayed after upgrading to PHP 8.1 relating to the code below:

enter code here

```<code> public function next() {
    $this->fetch();
    return next( $this->data );
}
</code>```

Can supress this by adding #[\ReturnTypeWillChange] but would rather solve / change the code without using the above method.
Any ideas on how we can change this code to be PHP 8.1 + compatible. ?

Body:
The above depreciation notice is displayed after upgrading to PHP 8.1 relating to the code below:

enter code here

 public function next() {
    $this->fetch();
    return next( $this->data );
}

Can supress this by adding #[\ReturnTypeWillChange] but would rather solve / change the code without using the above method.
Any ideas on how we can change this code to be PHP 8.1 + compatible. ?


问:
Confused about reverse URL in testing mode
In my test file, there is one class with :

```<code>INGREDIENTS_URL = reverse("recipe:ingredient-list")

    def setUp(self):
        self.client = APIClient()

    def test_Auth_required(self):
        res = self.client.get(INGREDIENTS_URL)
</code>```

I have one recipe app, but there are no "recipe-list" anywhere else.

Ingredient endpoint is defined with a router in the view.py :

```<code>from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('ingredients', views.IngredientViewSet)
</code>```

And the serializer.py

```<code>class IngredientSerializer(serializers.ModelSerializer):

    class Meta:
        model = Ingredient
        fields = ['id', 'name']
        read_only_fields = ['id']
</code>```

So I wonder how the reverse is working in this case

EDIT 1
I guess the reverse("recipe:ingredient-list") it related with viewsets.ModelViewSet and would inherit of my views.py :

```<code>class IngredientViewSet(mixins.ListModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.DestroyModelMixin,
                        viewsets.GenericViewSet):
</code>```

Body:
In my test file, there is one class with :

INGREDIENTS_URL = reverse("recipe:ingredient-list")

    def setUp(self):
        self.client = APIClient()

    def test_Auth_required(self):
        res = self.client.get(INGREDIENTS_URL)

I have one recipe app, but there are no "recipe-list" anywhere else.

Ingredient endpoint is defined with a router in the view.py :

from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('ingredients', views.IngredientViewSet)

And the serializer.py

class IngredientSerializer(serializers.ModelSerializer):

    class Meta:
        model = Ingredient
        fields = ['id', 'name']
        read_only_fields = ['id']

So I wonder how the reverse is working in this case

EDIT 1
I guess the reverse("recipe:ingredient-list") it related with viewsets.ModelViewSet and would inherit of my views.py :

class IngredientViewSet(mixins.ListModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.DestroyModelMixin,
                        viewsets.GenericViewSet):


问:
Trying to create the CSV files and the "label_map.pbtxt" file from xml files in colab
I'm using this code to create csv file:

```<code>def xml_to_csv(path):
  classes_names = []
  xml_list = []

  for xml_file in glob.glob(path + '/*.xml'):
    tree = ET.parse(xml_file)
    root = tree.getroot()
    for member in root.findall('object'):
      classes_names.append(member[0].text)
      value = (root.find('filename').text  ,
               int(root.find('size')[0].text),
               int(root.find('size')[1].text),
               member[0].text,
               int(member[4][0].text),
               int(member[4][1].text),
               int(member[4][2].text),
               int(member[4][3].text))
      xml_list.append(value)
  column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
  xml_df = pd.DataFrame(xml_list, columns=column_name)
  classes_names = list(set(classes_names))
  classes_names.sort()
  return xml_df, classes_names

for label_path in ['train_labels', 'test_labels']:
  image_path = os.path.join(os.getcwd(), label_path)
  xml_df, classes = xml_to_csv(label_path)
  xml_df.to_csv(f'{label_path}.csv', index=None)
  print(f'Successfully converted {label_path} xml to csv.')

label_map_path = os.path.join("label_map.pbtxt")
pbtxt_content = ""

for i, class_name in enumerate(classes):
    pbtxt_content = (
        pbtxt_content
        + "item {{\n    id: {0}\n    name: '{1}'\n}}\n\n".format(i + 1, class_name)
    )
pbtxt_content = pbtxt_content.strip()
with open(label_map_path, "w") as f:
    f.write(pbtxt_content)
    print('Successfully created label_map.pbtxt ')
</code>```

When I use this code I'm get this error:

My xml files starts like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<version>5.1.1</version>
<flags></flags>
<shapes>
    <array>
        <label>implant</label>
        <points>
            <array>400.18181818181813</array>
            <array>246.72727272727272</array>
        </points>
        <points>
            <array>389.6363636363636</array>
            <array>259.8181818181818</array>
        </points>
        <points>
            <array>390.0</array>
            <array>264.54545454545456</array>
        </points>

</code>```

I do not see any junk in line 3, column 0? I assume there must be another reason for the error.
When I labeled my images the data is stored as json file so I used an online converter to change it to xml file, here is the link to that online converter https://www.oxygenxml.com/xml_editor/xml_json_converter.html

I'm doing all this in google colab, Please help me with a detailed explanation, Thank you

Body:
I'm using this code to create csv file:

def xml_to_csv(path):
  classes_names = []
  xml_list = []

  for xml_file in glob.glob(path + '/*.xml'):
    tree = ET.parse(xml_file)
    root = tree.getroot()
    for member in root.findall('object'):
      classes_names.append(member[0].text)
      value = (root.find('filename').text  ,
               int(root.find('size')[0].text),
               int(root.find('size')[1].text),
               member[0].text,
               int(member[4][0].text),
               int(member[4][1].text),
               int(member[4][2].text),
               int(member[4][3].text))
      xml_list.append(value)
  column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
  xml_df = pd.DataFrame(xml_list, columns=column_name)
  classes_names = list(set(classes_names))
  classes_names.sort()
  return xml_df, classes_names

for label_path in ['train_labels', 'test_labels']:
  image_path = os.path.join(os.getcwd(), label_path)
  xml_df, classes = xml_to_csv(label_path)
  xml_df.to_csv(f'{label_path}.csv', index=None)
  print(f'Successfully converted {label_path} xml to csv.')

label_map_path = os.path.join("label_map.pbtxt")
pbtxt_content = ""

for i, class_name in enumerate(classes):
    pbtxt_content = (
        pbtxt_content
        + "item {{\n    id: {0}\n    name: '{1}'\n}}\n\n".format(i + 1, class_name)
    )
pbtxt_content = pbtxt_content.strip()
with open(label_map_path, "w") as f:
    f.write(pbtxt_content)
    print('Successfully created label_map.pbtxt ')

When I use this code I'm get this error:

My xml files starts like this:

<?xml version="1.0" encoding="UTF-8"?>
<version>5.1.1</version>
<flags></flags>
<shapes>
    <array>
        implant
        <points>
            <array>400.18181818181813</array>
            <array>246.72727272727272</array>
        </points>
        <points>
            <array>389.6363636363636</array>
            <array>259.8181818181818</array>
        </points>
        <points>
            <array>390.0</array>
            <array>264.54545454545456</array>
        </points>

I do not see any junk in line 3, column 0? I assume there must be another reason for the error.
When I labeled my images the data is stored as json file so I used an online converter to change it to xml file, here is the link to that online converter https://www.oxygenxml.com/xml_editor/xml_json_converter.html

I'm doing all this in google colab, Please help me with a detailed explanation, Thank you


问:
How can I add data into Room database in a manner where it is appended to the top row
Image for reference

I am facing a situation whenever I add a new article into the database it will add the new article to the bottom of the RecyclerView, how can I implement it in such a way that it updates the top row instead?

Is it something got to do with the Adapter or do I have to tweak the Doa?

Room Database Implementation

```<code>**//ViewModel**
fun saveArticle(article: Article) = viewModelScope.launch {
        newsRepository.upsert(article)
    }

**
//NewsRepository**
suspend fun upsert(article: Article) = db.getArticleDao().upsert(article)

**//Implementation of the Database**
@Database(
    entities = [Article::class],
    version = 1
)

@TypeConverters(Converters::class)
abstract class ArticleDatabase : RoomDatabase() {

    abstract fun getArticleDao(): ArticleDao

    companion object {
        @Volatile
        private var instance: ArticleDatabase? = null
        private val LOCK = Any()

        operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
            instance ?: createDatabase(context).also { instance = it }
        }
        private fun createDatabase(context: Context) =
            Room.databaseBuilder(
                context.applicationContext,
                ArticleDatabase::class.java,
                "article_db.db"
            ).build()
    }
}

**//DOA**
@Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(article: Article): Long //returns the id's of the article

**//Entity**
@Entity(
    tableName = "articles", indices = [Index(value = ["url","title"], unique = true)]
)
@Parcelize
data class Article(
    @PrimaryKey(autoGenerate = true)
    var id: Int? =null,
    val author: String?,
    val description: String?,
    val source: Source?,
    val title: String?,
    val url: String?,
    val urlToImage: String?,
    val publishedAt: String?,
    val content: String?
): Parcelable {
    override fun hashCode(): Int {
        var result = id.hashCode()
        if(url.isNullOrEmpty()){
            result = 31 * result + url.hashCode()
        }
        return result
    }
}
</code>```

Expecting the top row to be updated instead of the bottom row, the Room Database docs did not talk much about changing the way the article is inserted, tried to reference other people's work, couldn't find the solution

Body:
Image for reference

I am facing a situation whenever I add a new article into the database it will add the new article to the bottom of the RecyclerView, how can I implement it in such a way that it updates the top row instead?

Is it something got to do with the Adapter or do I have to tweak the Doa?

Room Database Implementation

**//ViewModel**
fun saveArticle(article: Article) = viewModelScope.launch {
        newsRepository.upsert(article)
    }

**
//NewsRepository**
suspend fun upsert(article: Article) = db.getArticleDao().upsert(article)

**//Implementation of the Database**
@Database(
    entities = [Article::class],
    version = 1
)

@TypeConverters(Converters::class)
abstract class ArticleDatabase : RoomDatabase() {

    abstract fun getArticleDao(): ArticleDao

    companion object {
        @Volatile
        private var instance: ArticleDatabase? = null
        private val LOCK = Any()

        operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
            instance ?: createDatabase(context).also { instance = it }
        }
        private fun createDatabase(context: Context) =
            Room.databaseBuilder(
                context.applicationContext,
                ArticleDatabase::class.java,
                "article_db.db"
            ).build()
    }
}

**//DOA**
@Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(article: Article): Long //returns the id's of the article

**//Entity**
@Entity(
    tableName = "articles", indices = [Index(value = ["url","title"], unique = true)]
)
@Parcelize
data class Article(
    @PrimaryKey(autoGenerate = true)
    var id: Int? =null,
    val author: String?,
    val description: String?,
    val source: Source?,
    val title: String?,
    val url: String?,
    val urlToImage: String?,
    val publishedAt: String?,
    val content: String?
): Parcelable {
    override fun hashCode(): Int {
        var result = id.hashCode()
        if(url.isNullOrEmpty()){
            result = 31 * result + url.hashCode()
        }
        return result
    }
}

Expecting the top row to be updated instead of the bottom row, the Room Database docs did not talk much about changing the way the article is inserted, tried to reference other people's work, couldn't find the solution


问:
how to exchange an image in a word document identified by tag?
When I go to the options in Word and activate "Developer tools" then it is possible to give placeholder images a special tag.

I want to exchange a placeholder image, identified by tag, with Openxml, but I couldn't find any references or tutorials.

Appreciate any help


问:
VB.Net Connection string over draytek tunneling vpn
I am doing a VB.NET application, using SQL server as my database. SQL sever is located on other network connected via draytek VPN Matcher, Can you please recommend, what is the best connection string to connect to SQL Server from windows form application using oledb

Thanks to all

I tried using the IP directly with port 1433. I could connect through SSMS but not by the VB.Net application. I tried the SSMS it connects, but my appliction do not connect. It gives Error, server is not available any more.