问:
Created python package script not appearing to be installed
I'm on MacOSX (12.0.1) and with Python 3.9. I want to create a simple python package for personal use. Upon creating the package using python setup.py install, almost everything works: I can import the package when using python, etc. However, I've tried to follow every tutorial online to create an associated executable script. I.e., a command that I can execute from the shell that contains some functionality from the package I made. However, nothing has worked.

My setup.py code:

```<code>from setuptools import setup

setup(name='my_package',
      version='1.0.0',
      description='heeheehoohoo',
      author='Me',
      author_email='me@me',
      url='me.com',
      packages=['my_package'],
      entry_points={
          'console_scripts': ['mypkg=my_package:run']},
      install_requires=['cairosvg',
                        'selenium',
                        'PyPDF2',
      ],
      include_package_data=True,
      zip_safe=False
     )
</code>```

And under my_package/__init__.py I have:

```<code>from . mine import main

def run():
    import argparse

    parser = argparse.ArgumentParser(prog = 'eeeeeee', description = 'eeeeee')

    parser.add_argument('eeeeee', help = 'eeeeeee')

    args = parser.parse_args()

    print(f'eeeee ...')
    main(args.eeeeeee)
    print(f'Success!')
</code>```

Everything gets installed, yet for some reason when I try to execute $ mypkg, I get zsh: command not found: mypkg. From python, I can import the function and directly try to execute run(). And strangest of all, each tutorial I have seen that has done anything like this can execute the commands without a problem once they'd executed python setup.py install.

Thank you!

Setting pip to the respective version of python and using pip install . instead of python setup.py install did the trick. However, it's still strange that python setup.py install does not work...

Body:
I'm on MacOSX (12.0.1) and with Python 3.9. I want to create a simple python package for personal use. Upon creating the package using python setup.py install, almost everything works: I can import the package when using python, etc. However, I've tried to follow every tutorial online to create an associated executable script. I.e., a command that I can execute from the shell that contains some functionality from the package I made. However, nothing has worked.

My setup.py code:

from setuptools import setup

setup(name='my_package',
      version='1.0.0',
      description='heeheehoohoo',
      author='Me',
      author_email='me@me',
      url='me.com',
      packages=['my_package'],
      entry_points={
          'console_scripts': ['mypkg=my_package:run']},
      install_requires=['cairosvg',
                        'selenium',
                        'PyPDF2',
      ],
      include_package_data=True,
      zip_safe=False
     )

And under my_package/__init__.py I have:

from . mine import main

def run():
    import argparse

    parser = argparse.ArgumentParser(prog = 'eeeeeee', description = 'eeeeee')

    parser.add_argument('eeeeee', help = 'eeeeeee')

    args = parser.parse_args()

    print(f'eeeee ...')
    main(args.eeeeeee)
    print(f'Success!')

Everything gets installed, yet for some reason when I try to execute $ mypkg, I get zsh: command not found: mypkg. From python, I can import the function and directly try to execute run(). And strangest of all, each tutorial I have seen that has done anything like this can execute the commands without a problem once they'd executed python setup.py install.

Thank you!

Setting pip to the respective version of python and using pip install . instead of python setup.py install did the trick. However, it's still strange that python setup.py install does not work...


来源: stackexchange

问:
script label make my jsp does not work to populate combobox
I used this code https://github.com/Java-Hub18/Servlet-JSP/tree/master/AjaxDropDownTest/web to populate a combobox based in another combobox, but in the second file when i add  at the end of file, the script stop working. I made test putting only  without any code.

When i remove that  label the code start working. I remove  in the second file and app works. I don't understand why the code run using  in the first file but not when i put in the second file

ContentLicense: CC BY-SA 4.0


问:
sending mail after adding attachment code in ajax form submission not working
im trying to send email with attachment using ajax, if dont use attachment code email is send successfully, but when i add attachment code then nothing happens no error nothing at all.

```<code>`<form enctype="multipart/form-data" id="first_form" method="POST" class="get-contact-form" action="get-quote.php">
    <div class="row g-3">
    <div class="col-sm-6">
    <div class="form-floating">
    <input type="hidden" class="form-control" id="spam" name="spam" placeholder="Spam:" value="<?php echo $silk; ?>">
    <p class='response' id="spam_error"></p>
    </div>
    </div>
    <div class="col-sm-6">
    <div class="form-floating">
    <input type="hidden" class="form-control" id="blank" name="blank" placeholder="blank:" value="">
    <p class='response' id="blank_error"></p>
    </div>
    </div>
    <div class="col-sm-6">
    <div class="form-floating">
    <input type="text" name="name" class="form-control" id="gname" placeholder="Gurdian Name">
    <label for="gname">Your Name</label>
    <p class='response' id="name_error"></p>
    </div>
    </div>
    <div class="col-sm-6">
    <div class="form-floating">
    <input type="email" name="email" class="form-control" id="gmail" placeholder="Gurdian Email">
    <label for="gmail">Your Email</label>
    <p class='response' id="email_error"></p>
    </div>
    </div>
    <div class="col-sm-6">
    <div class="form-floating">
    <input type="text" name="phone" class="form-control" id="cname" placeholder="Child Name">
    <label for="cname">Your Phone</label>
    <p class='response' id="phone_error"></p>
    </div>
    </div>
    <div class="col-sm-6">
    <div class="form-floating">
    <input type="text" name="address" class="form-control"  placeholder="Child Age">
    <label for="cage">Address</label>
    <p class='response' id="address_error"></p>
    </div>
    </div>
    <div class="col-sm-6">
    <div class="form-floating">
    <input type="text" name="subject" class="form-control" id="cage" placeholder="Child Age">
    <label for="cage">Subject</label>
    <p class='response' id="subject_error"></p>
    </div>
    </div>
    <div class="col-sm-6">
    <div class="form-floating">
    <input type="text" name="services" class="form-control" id="cage" placeholder="Child Age">
    <label for="cage">Service Type</label>
    <p class='response' id="services_error"></p>
    </div>
    </div>
    <div class="col-sm-12">
    <div class="form-floating">
    <input type="file" name="my_file" class="form-control" id="my_case_file" placeholder="Child Age">
    <p class='response' id="my_file_error"></p>
    </div>
    </div>
    <div class="col-12">
    <div class="form-floating">
    <textarea class="form-control" name="message" placeholder="Leave a message here" id="message"     style="height: 80px"></textarea>
    <label for="message">Message</label>
    <p class='response' id="message_error"></p>
    </div>
    </div>
    <div class="col-12">
    <button class="btn secondary-bg text-white  py-3 px-5" name="submit" type="submit">Get A Free Quote</button>
    </div>
    </div>
    </form>`
</code>```

php code for sending mail, when i add attachement code for sending image through mail following code doesnt send mail... but if remove attachment code form following code the form works percetly with ajax submission

session_start();
$floor = $_SESSION['token'];

```<code>    $errorsbag = [];
    $count_errors = 0;

    $post = [];
    $errors = [];

    // List of the words you want to block
    $spam_words =
        ["http", "www", ".com","@",".mx", ".org",
        ".net", ".co.uk",
        ".jp", ".ch", ".info", ".me",
        ".mobi", ".us", ".biz", ".ca",
        ".ws", ".ag",".com.co", ".net.co",
        ".com.ag", ".net.ag", ".it", ".fr",
        ".tv", ".am", ".asia", ".at", ".be",
        ".cc", ".de","dollars",
        "payment", "website", "games", "toys", "poker",
        "cheap", "href","nude","cam","penis","pills",
        "sale","cheapest", "script",'Mod', 'Owner',
        'Mawd', 'M0d', '0wner','090','080','081','070','
        091','0-','+','80','81','70','91','dot','f*ck',
        'bitch','ww','cum','hacker','money','Buy','Order',
        'Meet singles','Near you','Near you','Additional income',
        'Be your own boss','Robot, '<','>'
        ];

        function is_blank($value) {
            return !isset($value) || trim($value) === '';
        }

    // post method form processing
    if($_SERVER['REQUEST_METHOD'] == 'POST'){

        $post = array_map('trim',$_POST);

        // validate inputs

        if($post['name'] === '')
        {
            $errors['name'] = "Name is required.";
        }

        if($post['email'] === '')
        {
            $errors['email'] = "Email is required.";
        }
        else if(!filter_var($post['email'], FILTER_VALIDATE_EMAIL))
        {
            $errors['email'] = "Email format is not valid.";
        }

        if($post['phone'] === '')
        {
            $errors['phone'] = "Phone is required.";
        }

        if($post['address'] === '')
        {
            $errors['address'] = "Address is required.";
        }

        if($post['subject'] === '')
        {
            $errors['subject'] = "Subject is required.";
        }

        if($post['services'] === '')
        {
            $errors['services'] = "Services is required.";
        }

        if($post['message'] === '')
        {
            $errors['message'] = "Message is required.";
        }

        $comment = $post['message']; // This should be coming from a post request
        $comment_str = (string)$comment;

        $new_input = str_replace(' ', '', strtolower($comment_str));

        if(!is_blank($comment)){
            foreach($spam_words as $item) {
                if (strpos($new_input, strtolower($item)) !== false) {
                    $errorsbag[] = $item;
                }
            }
        }

        $count_errors = count($errorsbag);

        if ($count_errors >= 1) {
            $errors['message'] = "";
        }

        if($post['spam'] !== $floor){
            $errors['spam'] = "";
        }elseif($post['blank'] !== ''){
            $errors['blank'] = "";
        }elseif($count_errors >= 1){
            $errors['message'] = "";
        }

        // if no errors, use the form data
        if(empty($errors)){
            $name     = contact_input($post['name']);
            $email    = contact_input($post['email']);
            $phone    = contact_input($post['phone']);
            $address  = contact_input($post['address']);
            $subject  = contact_input($post['subject']);
            $services = contact_input($post['services']);
            $message  = contact_input($post['message']);

            $info =
            '<table  border="1" cellspacing="0" width="60%" cellpadding="10px">
                <tr style="height: 21px;">
                  <td colspan="2" bgcolor="#dddfe2 " align="center" style="font-family: Verdana, Geneva, sans-serif; font-size: 14px; color: #000; height: 21px;"><b>Mail From Client: '.$name.'</b></td>
                </tr>
                <tr>
                    <td>Name:</td>
                    <td>'.$name.'</td>
                </tr>
                <tr>
                    <td>Email:</td>
                    <td>'.$email.'</td>
                </tr>
                <tr>
                    <td>Phone:</td>
                    <td>'.$phone.'</td>
                </tr>
                <tr>
                    <td>Services:</td>
                    <td>'.$services.'</td>
                </tr>
                <tr>
                    <td>Message:</td>
                    <td>'.$message.'</td>
                </tr>
            </table>';

            //Get uploaded file data
            $file_tmp_name    = $_FILES['my_file']['tmp_name'];
            $file_name        = $_FILES['my_file']['name'];
            $file_size        = $_FILES['my_file']['size'];
            $file_type        = $_FILES['my_file']['type'];
            $file_error       = $_FILES['my_file']['error'];

            $handle = fopen($file_tmp_name, "r");
            $content = fread($handle, $file_size);
            fclose($handle);
            $encoded_content = chunk_split(base64_encode($content));
            $boundary = md5("random");

            //header
            $headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version
            $headers .= "From:".$email."\r\n"; // Sender Email
            $headers .= "Content-Type: multipart/mixed;"; // Defining Content-Type
            $headers .= "boundary = $boundary\r\n"; //Defining the Boundary

            //plain text
            $body = "--$boundary\r\n";
            $body .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
            $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
            $body .= chunk_split(base64_encode($info));

            //attachment
            $body .= "--$boundary\r\n";
            $body .="Content-Type: $file_type; name=".$file_name."\r\n";
            $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
            $body .="Content-Transfer-Encoding: base64\r\n";
            $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
            $body .= $encoded_content;

            $subject = "Mail From Client";
            $mailTo = "satish.innovstudio@gmail.com";
            mail($mailTo, $subject, $body,$headers);
        }

        $response = [];

            if(empty($errors) || $post['spam'] !== $floor || $post['blank'] !== '' || $count_errors >= 1){
                $response['success_message'] = "Thank you for your message!<br>We'll get back to you as soon as We can.";
            }
            else{
                foreach($errors as $key=>$value)
                {
                    $response[$key.'_error'] = $value;
                }
            }
        echo json_encode($response);
    }

    function contact_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }`
</code>```

Body:
im trying to send email with attachment using ajax, if dont use attachment code email is send successfully, but when i add attachment code then nothing happens no error nothing at all.

`<form enctype="multipart/form-data" id="first_form" method="POST" class="get-contact-form" action="get-quote.php">

    <input type="hidden" class="form-control" id="spam" name="spam" placeholder="Spam:" value="<?php echo $silk; ?>">

    <input type="hidden" class="form-control" id="blank" name="blank" placeholder="blank:" value="">

    <input type="text" name="name" class="form-control" id="gname" placeholder="Gurdian Name">
    Your Name

    <input type="email" name="email" class="form-control" id="gmail" placeholder="Gurdian Email">
    Your Email

    <input type="text" name="phone" class="form-control" id="cname" placeholder="Child Name">
    Your Phone

    <input type="text" name="address" class="form-control"  placeholder="Child Age">
    Address

    <input type="text" name="subject" class="form-control" id="cage" placeholder="Child Age">
    Subject

    <input type="text" name="services" class="form-control" id="cage" placeholder="Child Age">
    Service Type

    <input type="file" name="my_file" class="form-control" id="my_case_file" placeholder="Child Age">

    <textarea class="form-control" name="message" placeholder="Leave a message here" id="message"     style="height: 80px"></textarea>
    Message

    <button class="btn secondary-bg text-white  py-3 px-5" name="submit" type="submit">Get A Free Quote</button>

    </form>`

php code for sending mail, when i add attachement code for sending image through mail following code doesnt send mail... but if remove attachment code form following code the form works percetly with ajax submission

session_start();
$floor = $_SESSION['token'];

    $errorsbag = [];
    $count_errors = 0;

    $post = [];
    $errors = [];

    // List of the words you want to block
    $spam_words =
        ["http", "www", ".com","@",".mx", ".org",
        ".net", ".co.uk",
        ".jp", ".ch", ".info", ".me",
        ".mobi", ".us", ".biz", ".ca",
        ".ws", ".ag",".com.co", ".net.co",
        ".com.ag", ".net.ag", ".it", ".fr",
        ".tv", ".am", ".asia", ".at", ".be",
        ".cc", ".de","dollars",
        "payment", "website", "games", "toys", "poker",
        "cheap", "href","nude","cam","penis","pills",
        "sale","cheapest", "script",'Mod', 'Owner',
        'Mawd', 'M0d', '0wner','090','080','081','070','
        091','0-','+','80','81','70','91','dot','f*ck',
        'bitch','ww','cum','hacker','money','Buy','Order',
        'Meet singles','Near you','Near you','Additional income',
        'Be your own boss','Robot, '<','>'
        ];

        function is_blank($value) {
            return !isset($value) || trim($value) === '';
        }

    // post method form processing
    if($_SERVER['REQUEST_METHOD'] == 'POST'){

        $post = array_map('trim',$_POST);

        // validate inputs

        if($post['name'] === '')
        {
            $errors['name'] = "Name is required.";
        }

        if($post['email'] === '')
        {
            $errors['email'] = "Email is required.";
        }
        else if(!filter_var($post['email'], FILTER_VALIDATE_EMAIL))
        {
            $errors['email'] = "Email format is not valid.";
        }

        if($post['phone'] === '')
        {
            $errors['phone'] = "Phone is required.";
        }

        if($post['address'] === '')
        {
            $errors['address'] = "Address is required.";
        }

        if($post['subject'] === '')
        {
            $errors['subject'] = "Subject is required.";
        }

        if($post['services'] === '')
        {
            $errors['services'] = "Services is required.";
        }

        if($post['message'] === '')
        {
            $errors['message'] = "Message is required.";
        }

        $comment = $post['message']; // This should be coming from a post request
        $comment_str = (string)$comment;

        $new_input = str_replace(' ', '', strtolower($comment_str));

        if(!is_blank($comment)){
            foreach($spam_words as $item) {
                if (strpos($new_input, strtolower($item)) !== false) {
                    $errorsbag[] = $item;
                }
            }
        }

        $count_errors = count($errorsbag);

        if ($count_errors >= 1) {
            $errors['message'] = "";
        }

        if($post['spam'] !== $floor){
            $errors['spam'] = "";
        }elseif($post['blank'] !== ''){
            $errors['blank'] = "";
        }elseif($count_errors >= 1){
            $errors['message'] = "";
        }

        // if no errors, use the form data
        if(empty($errors)){
            $name     = contact_input($post['name']);
            $email    = contact_input($post['email']);
            $phone    = contact_input($post['phone']);
            $address  = contact_input($post['address']);
            $subject  = contact_input($post['subject']);
            $services = contact_input($post['services']);
            $message  = contact_input($post['message']);

            $info =
            '

                  Mail From Client: '.$name.'

                    Name:
                    '.$name.'

                    Email:
                    '.$email.'

                    Phone:
                    '.$phone.'

                    Services:
                    '.$services.'

                    Message:
                    '.$message.'

';

            //Get uploaded file data
            $file_tmp_name    = $_FILES['my_file']['tmp_name'];
            $file_name        = $_FILES['my_file']['name'];
            $file_size        = $_FILES['my_file']['size'];
            $file_type        = $_FILES['my_file']['type'];
            $file_error       = $_FILES['my_file']['error'];

            $handle = fopen($file_tmp_name, "r");
            $content = fread($handle, $file_size);
            fclose($handle);
            $encoded_content = chunk_split(base64_encode($content));
            $boundary = md5("random");

            //header
            $headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version
            $headers .= "From:".$email."\r\n"; // Sender Email
            $headers .= "Content-Type: multipart/mixed;"; // Defining Content-Type
            $headers .= "boundary = $boundary\r\n"; //Defining the Boundary

            //plain text
            $body = "--$boundary\r\n";
            $body .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
            $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
            $body .= chunk_split(base64_encode($info));

            //attachment
            $body .= "--$boundary\r\n";
            $body .="Content-Type: $file_type; name=".$file_name."\r\n";
            $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
            $body .="Content-Transfer-Encoding: base64\r\n";
            $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
            $body .= $encoded_content;

            $subject = "Mail From Client";
            $mailTo = "satish.innovstudio@gmail.com";
            mail($mailTo, $subject, $body,$headers);
        }

        $response = [];

            if(empty($errors) || $post['spam'] !== $floor || $post['blank'] !== '' || $count_errors >= 1){
                $response['success_message'] = "Thank you for your message!
We'll get back to you as soon as We can.";
            }
            else{
                foreach($errors as $key=>$value)
                {
                    $response[$key.'_error'] = $value;
                }
            }
        echo json_encode($response);
    }

    function contact_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }`


问:
Using Apache mod_rewrite to detect and redirect Nmap scans
Nmap is used by all color of hats to scan systems.  Nmap scans are also very detectable.  There is an upcoming pen-test and I want to have some fun with the testers who I'm sure will use Nmap to initially scan the servers.  I want to add some mod_rewrite rules to identify the scan requests and then redirect them to someplace else (Google for example but maybe with a colorful message attached).

Here are the Nmap requests that I see in the log.

```<code>"OPTIONS / HTTP/1.0"
"GET /nice%20ports%2C/Tri%6Eity.txt%2ebak HTTP/1.0"
"OPTIONS / RTSP/1.0"
"HELP"
"\x16\x03"
"\x03"
"\x16\x03"
""
"\x01default\n"
"0\x84"
"OPTIONS sip:nm SIP/2.0"
"GET /server-status HTTP/1.1"
"GET /nmaplowercheck1673484909 HTTP/1.1"
"POST /sdk HTTP/1.1"
</code>```

Problem is I'm not sure how to create conditions for all of them (OPTION and POST for example).  I've tried the following for the simple GET requests but they don't seem to work.

```<code>RewriteCond %{REQUEST_URI} ^/nice%20ports%2C/Tri%6Eity.txt%2ebak$ [NC]
RewriteCond %{REQUEST_URI} ^/server-status$ [NC]
RewriteRule ^(.*)$ https://www.google.com/ [R=301,NC,L]
</code>```

How can I detect the provided scan URIs and then redirect to a new address?

Body:
Nmap is used by all color of hats to scan systems.  Nmap scans are also very detectable.  There is an upcoming pen-test and I want to have some fun with the testers who I'm sure will use Nmap to initially scan the servers.  I want to add some mod_rewrite rules to identify the scan requests and then redirect them to someplace else (Google for example but maybe with a colorful message attached).

Here are the Nmap requests that I see in the log.

"OPTIONS / HTTP/1.0"
"GET /nice%20ports%2C/Tri%6Eity.txt%2ebak HTTP/1.0"
"OPTIONS / RTSP/1.0"
"HELP"
"\x16\x03"
"\x03"
"\x16\x03"
""
"\x01default\n"
"0\x84"
"OPTIONS sip:nm SIP/2.0"
"GET /server-status HTTP/1.1"
"GET /nmaplowercheck1673484909 HTTP/1.1"
"POST /sdk HTTP/1.1"

Problem is I'm not sure how to create conditions for all of them (OPTION and POST for example).  I've tried the following for the simple GET requests but they don't seem to work.

RewriteCond %{REQUEST_URI} ^/nice%20ports%2C/Tri%6Eity.txt%2ebak$ [NC]
RewriteCond %{REQUEST_URI} ^/server-status$ [NC]
RewriteRule ^(.*)$ https://www.google.com/ [R=301,NC,L]

How can I detect the provided scan URIs and then redirect to a new address?


问:
Remove scrollbar from pdf image in HTML RMarkdown document
I can't figure out why pdf images I'm inserting into my HTML RMarkdown document are appearing inside of itty bitty scroll boxes with both vertical and horizontal scrollbars. This doesn't happen if I convert the same image to .png

The pdf image appears this way if inserted like so:

```<code>```{r, echo=FALSE, eval = TRUE}
knitr::include_graphics("image.pdf")
```
</code>```

or like so:

```<code>![](image.pdf)
</code>```

I have an option set to include scroll bars in my code chunks, but if I remove it and re-knit the document the itty bitty image scroll box remains so this is not causing the problem (and is the only non-default setting):

```<code>```{css, echo=FALSE}
pre code, pre, code {
  white-space: pre !important;
  overflow-x: scroll !important;
  word-break: keep-all !important;
  word-wrap: initial !important;
}
```
</code>```

Changing the option out.width = '100%' is resizing the scrollbox a bit but not removing it. Note that the pdf image is 6 x 2.5 inches, so not unreasonably large or anything. Any ideas to make my inserted pdf image not be in a scroll box at all? Thanks!

Body:
I can't figure out why pdf images I'm inserting into my HTML RMarkdown document are appearing inside of itty bitty scroll boxes with both vertical and horizontal scrollbars. This doesn't happen if I convert the same image to .png

The pdf image appears this way if inserted like so:

```{r, echo=FALSE, eval = TRUE}
knitr::include_graphics("image.pdf")
```

or like so:

![](image.pdf)

I have an option set to include scroll bars in my code chunks, but if I remove it and re-knit the document the itty bitty image scroll box remains so this is not causing the problem (and is the only non-default setting):

```{css, echo=FALSE}
pre code, pre, code {
  white-space: pre !important;
  overflow-x: scroll !important;
  word-break: keep-all !important;
  word-wrap: initial !important;
}
```

Changing the option out.width = '100%' is resizing the scrollbox a bit but not removing it. Note that the pdf image is 6 x 2.5 inches, so not unreasonably large or anything. Any ideas to make my inserted pdf image not be in a scroll box at all? Thanks!


问:
Python dataprep package seems to break pip-compile due to conflicting dependencies
I used the dataprep package in a jupyter notebook, installing via !pip install dataprep recently and it installed smoothly.

Now I'm tidying up some of that work and am using a venv, but pip-compile keeps crashing and I seem to have isolated dataprep as the cause. A minimal reproducible example below:

Given a test_requirements.in file which contains only a single line: dataprep

...Running pip-compile test_requirements.in --verbose --output-file test_requirements.txt yields the following error:

```<code>Could not find a version that matches executing<0.9.0,>=0.8.3,>=1.2.0 (from varname==0.8.3->dataprep==0.4.5->-r test_requirements.in (line 1))
Tried: 0.1.0, 0.1.1, 0.1.2, 0.1.3, 0.2.0, 0.3.0, 0.3.1, 0.3.2, 0.3.3, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.4.4, 0.5.0, 0.5.2, 0.5.3, 0.5.3, 0.5.4, 0.5.4, 0.6.0, 0.6.0, 0.7.0, 0.7.0, 0.8.0, 0.8.0, 0.8.1, 0.8.1, 0.8.2, 0.8.2, 0.8.3, 0.8.3, 0.9.0, 0.9.0, 0.9.1, 0.9.1, 0.10.0, 0.10.0, 1.0.0, 1.0.0, 1.1.0, 1.1.0, 1.1.1, 1.1.1, 1.2.0, 1.2.0
There are incompatible versions in the resolved dependencies:
  executing<0.9.0,>=0.8.3 (from varname==0.8.3->dataprep==0.4.5->-r test_requirements.in (line 1))
  executing>=1.2.0 (from stack-data==0.6.2->ipython==8.8.0->ipywidgets==7.7.2->dataprep==0.4.5->-r test_requirements.in (line 1))
</code>```

I might be reading this wrong but it seems to be saying that one of dataprep's dependencies requires a version of the executing package between 0.8.3 and 0.9, but another of dataprep's dependencies requires a version of the executing package >=1.2. Is there any way to resolve this apparent contradiction with pip-compile?

Body:
I used the dataprep package in a jupyter notebook, installing via !pip install dataprep recently and it installed smoothly.

Now I'm tidying up some of that work and am using a venv, but pip-compile keeps crashing and I seem to have isolated dataprep as the cause. A minimal reproducible example below:

Given a test_requirements.in file which contains only a single line: dataprep

...Running pip-compile test_requirements.in --verbose --output-file test_requirements.txt yields the following error:

Could not find a version that matches executing<0.9.0,>=0.8.3,>=1.2.0 (from varname==0.8.3->dataprep==0.4.5->-r test_requirements.in (line 1))
Tried: 0.1.0, 0.1.1, 0.1.2, 0.1.3, 0.2.0, 0.3.0, 0.3.1, 0.3.2, 0.3.3, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.4.4, 0.5.0, 0.5.2, 0.5.3, 0.5.3, 0.5.4, 0.5.4, 0.6.0, 0.6.0, 0.7.0, 0.7.0, 0.8.0, 0.8.0, 0.8.1, 0.8.1, 0.8.2, 0.8.2, 0.8.3, 0.8.3, 0.9.0, 0.9.0, 0.9.1, 0.9.1, 0.10.0, 0.10.0, 1.0.0, 1.0.0, 1.1.0, 1.1.0, 1.1.1, 1.1.1, 1.2.0, 1.2.0
There are incompatible versions in the resolved dependencies:
  executing<0.9.0,>=0.8.3 (from varname==0.8.3->dataprep==0.4.5->-r test_requirements.in (line 1))
  executing>=1.2.0 (from stack-data==0.6.2->ipython==8.8.0->ipywidgets==7.7.2->dataprep==0.4.5->-r test_requirements.in (line 1))

I might be reading this wrong but it seems to be saying that one of dataprep's dependencies requires a version of the executing package between 0.8.3 and 0.9, but another of dataprep's dependencies requires a version of the executing package >=1.2. Is there any way to resolve this apparent contradiction with pip-compile?


问:
Emscripten missing epoll.h when compiling grpc library to wasm(Webassembly)
I'm going to convert a c++ project that needs to use the grpc library to wasm using Emscripten. As far as I know, the grpc source code needs to be compiled using Emscripten to get the library.

By the way, I want to compile grpc lib for standalone wasm binary and run it using runtime(for example, wasmtime).

The error below has been resolved and can go to Update2.

But there was an error when compiling the grpc source code:

```<code>[  7%] Linking CXX static library libabsl_bad_variant_access.a
[  7%] Built target bad_variant_access
[  7%] Building CXX object CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o
In file included from /home/xxx/grpc_wasm/grpc/src/core/lib/gpr/alloc.cc:19:
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:451:2: error: "Could not auto-detect platform"
#error "Could not auto-detect platform"
 ^
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:474:2: warning: "GPR_PLATFORM_STRING not auto-detected" [-W#warnings]
#warning "GPR_PLATFORM_STRING not auto-detected"
 ^
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:541:2: error: Must define exactly one of GPR_GCC_ATOMIC, GPR_GCC_SYNC, GPR_WINDOWS_ATOMIC
#error Must define exactly one of GPR_GCC_ATOMIC, GPR_GCC_SYNC, GPR_WINDOWS_ATOMIC
 ^
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:545:2: error: Must define exactly one of GPR_ARCH_32, GPR_ARCH_64
#error Must define exactly one of GPR_ARCH_32, GPR_ARCH_64
 ^
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:551:2: error: Must define exactly one of GPR_CPU_LINUX, GPR_CPU_POSIX, GPR_WINDOWS, GPR_CPU_IPHONE, GPR_CPU_CUSTOM
#error Must define exactly one of GPR_CPU_LINUX, GPR_CPU_POSIX, GPR_WINDOWS, GPR_CPU_IPHONE, GPR_CPU_CUSTOM
 ^
1 warning and 4 errors generated.
em++: error: '/home/xxx/emsdk/upstream/bin/clang++ -target wasm32-unknown-emscripten -fignore-exceptions -fvisibility=default -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mlm -disable-lsr -DEMSCRIPTEN -I/home/xxx/emsdk/upstream/emscripten/cache/sysroot/include/SDL --sysroot=/home/xxx/emsdk/upstream/emscripten/cache/sysroot -Xclang -iwithsysroot/include/compat -I/home/xxx/grpcasm/grpc/third_party/re2 -I/home/xxx/grpc_wasm/grpc/third_party/zlib -I/home/xxx/grpc_wasm/grpc/include -I/home/xxx/grpc_wasm/grpc -I/home/xxx/grpc_wasm/grpc/third_party/address_sorting/include -I/home/xxx/grpc_wasm/grpc/cmake/build/third_party/re2 -I/home/xxx/grpc_wasm/grpc/third_party/boringssl-with-bazel/src/include -I/home/xxx/grpc_wasm/grpc/src/core/ext/upb-generated -I/home/xxx/grpc_wasm/grpc/src/core/e/upbdefs-generated -I/home/xxx/grpc_wasm/grpc/third_party/upb -I/home/xxx/grpc_wasm/grpc/third_party/xxhash -I/home/xxx/grpc_wasm/grpc/cmake/build/third_party/zlib -I/home/xxx/grpc_wasm/grpc/third_party/abil-cpp -fPIC -std=c++14 -MD -MT CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o -MF CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o.d -c /home/xxx/grpc_wasm/grpc/src/core/lib/gpr/alloc.cc -o CMakeFiles/gpr.d/src/core/lib/gpr/alloc.cc.o' failed (returned 1)
make[2]: *** [CMakeFiles/gpr.dir/build.make:77: CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:1046: CMakeFiles/gpr.dir/all] Error 2
make: *** [Makefile:156: all] Error 2
emmake: error: 'make' failed (returned 2)

</code>```

I export GRPC_CROSS_COMPILATION=true and GRPC_CROSS_AROPTS=cr --target=wasm32-wasi but it didn't seem to work.

Update:

Noticed a warning:

```<code>CMake Warning at third_party/abseil-cpp/absl/copts/AbseilConfigureCopts.cmake:70 (message):
  Value of CMAKE_SYSTEM_PROCESSOR (x86) is unknown and cannot be used to set
  ABSL_RANDOM_RANDEN_COPTS
Call Stack (most recent call first):
  third_party/abseil-cpp/CMake/AbseilHelpers.cmake:18 (include)
  third_party/abseil-cpp/CMakeLists.txt:81 (include)
</code>```

So I set the platform parameter for Emscripten cmake: -DEMSCRIPTEN_SYSTEM_PROCESSOR=x86_64 but it doesn't seem to work.

Cmake command parameter is:

```<code>emcmake cmake ../..
-DCMAKE_INSTALL_PREFIX=/home/xxx/grpc_wasm/grpc/mylib
-DEMSCRIPTEN_SYSTEM_PROCESSOR=x86_64
-DCMAKE_CXX_FLAGS=-mrelaxed-simd
-DCMAKE_C_FLAGS=-mrelaxed-simd
-DCMAKE_BUILD_TYPE=Relese
-DgRPC_PROTOBUF_PROVIDER=package
-DProtobuf_INCLUDE_DIR=/home/xxx/protobuf_wasm/protobuf_src/src
-DProtobuf_LIBRARIES=/home/xxx/protobuf_wasm/protobuf_src/src/.libs
-DProtobuf_PROTOC_LIBRARY:/home/xxx/protobuf_wasm/protobuf_src/src/.libs
</code>```

Since I have already compiled the protobuf lib using Emscripten, I specify the lib and include directory of libprotobuf manually.

Update2:

About the error: "Could not auto-detect platform", I add #define __linux__ 1 in grpc/include/grpc/support/port_platform.h.

After that, I went through another error: emscripten libc lacks of epoll.h (details and what I have done can be found in here).

I created epoll.h and eventfd.h in emsdk include/sys directory, although the compilation of grpc is successful and got libgrpc.a, I got error of undefined symbol in the link phase as expected (also here). This is because the libc doesn't have the defination of functions in epoll.h and eventfd.h.

It turns out that the Emscripten libc doesn't support epoll system call, and I faild to recompile the libc (also here) to support that.

Anyone has any idea on how to solve the epoll problem? Appreciate any reply and suggestions. Thanks!

Body:
I'm going to convert a c++ project that needs to use the grpc library to wasm using Emscripten. As far as I know, the grpc source code needs to be compiled using Emscripten to get the library.

By the way, I want to compile grpc lib for standalone wasm binary and run it using runtime(for example, wasmtime).

The error below has been resolved and can go to Update2.

But there was an error when compiling the grpc source code:

[  7%] Linking CXX static library libabsl_bad_variant_access.a
[  7%] Built target bad_variant_access
[  7%] Building CXX object CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o
In file included from /home/xxx/grpc_wasm/grpc/src/core/lib/gpr/alloc.cc:19:
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:451:2: error: "Could not auto-detect platform"
#error "Could not auto-detect platform"
 ^
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:474:2: warning: "GPR_PLATFORM_STRING not auto-detected" [-W#warnings]
#warning "GPR_PLATFORM_STRING not auto-detected"
 ^
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:541:2: error: Must define exactly one of GPR_GCC_ATOMIC, GPR_GCC_SYNC, GPR_WINDOWS_ATOMIC
#error Must define exactly one of GPR_GCC_ATOMIC, GPR_GCC_SYNC, GPR_WINDOWS_ATOMIC
 ^
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:545:2: error: Must define exactly one of GPR_ARCH_32, GPR_ARCH_64
#error Must define exactly one of GPR_ARCH_32, GPR_ARCH_64
 ^
/home/xxx/grpc_wasm/grpc/include/grpc/support/port_platform.h:551:2: error: Must define exactly one of GPR_CPU_LINUX, GPR_CPU_POSIX, GPR_WINDOWS, GPR_CPU_IPHONE, GPR_CPU_CUSTOM
#error Must define exactly one of GPR_CPU_LINUX, GPR_CPU_POSIX, GPR_WINDOWS, GPR_CPU_IPHONE, GPR_CPU_CUSTOM
 ^
1 warning and 4 errors generated.
em++: error: '/home/xxx/emsdk/upstream/bin/clang++ -target wasm32-unknown-emscripten -fignore-exceptions -fvisibility=default -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mlm -disable-lsr -DEMSCRIPTEN -I/home/xxx/emsdk/upstream/emscripten/cache/sysroot/include/SDL --sysroot=/home/xxx/emsdk/upstream/emscripten/cache/sysroot -Xclang -iwithsysroot/include/compat -I/home/xxx/grpcasm/grpc/third_party/re2 -I/home/xxx/grpc_wasm/grpc/third_party/zlib -I/home/xxx/grpc_wasm/grpc/include -I/home/xxx/grpc_wasm/grpc -I/home/xxx/grpc_wasm/grpc/third_party/address_sorting/include -I/home/xxx/grpc_wasm/grpc/cmake/build/third_party/re2 -I/home/xxx/grpc_wasm/grpc/third_party/boringssl-with-bazel/src/include -I/home/xxx/grpc_wasm/grpc/src/core/ext/upb-generated -I/home/xxx/grpc_wasm/grpc/src/core/e/upbdefs-generated -I/home/xxx/grpc_wasm/grpc/third_party/upb -I/home/xxx/grpc_wasm/grpc/third_party/xxhash -I/home/xxx/grpc_wasm/grpc/cmake/build/third_party/zlib -I/home/xxx/grpc_wasm/grpc/third_party/abil-cpp -fPIC -std=c++14 -MD -MT CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o -MF CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o.d -c /home/xxx/grpc_wasm/grpc/src/core/lib/gpr/alloc.cc -o CMakeFiles/gpr.d/src/core/lib/gpr/alloc.cc.o' failed (returned 1)
make[2]: *** [CMakeFiles/gpr.dir/build.make:77: CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:1046: CMakeFiles/gpr.dir/all] Error 2
make: *** [Makefile:156: all] Error 2
emmake: error: 'make' failed (returned 2)

I export GRPC_CROSS_COMPILATION=true and GRPC_CROSS_AROPTS=cr --target=wasm32-wasi but it didn't seem to work.

Update:

Noticed a warning:

CMake Warning at third_party/abseil-cpp/absl/copts/AbseilConfigureCopts.cmake:70 (message):
  Value of CMAKE_SYSTEM_PROCESSOR (x86) is unknown and cannot be used to set
  ABSL_RANDOM_RANDEN_COPTS
Call Stack (most recent call first):
  third_party/abseil-cpp/CMake/AbseilHelpers.cmake:18 (include)
  third_party/abseil-cpp/CMakeLists.txt:81 (include)

So I set the platform parameter for Emscripten cmake: -DEMSCRIPTEN_SYSTEM_PROCESSOR=x86_64 but it doesn't seem to work.

Cmake command parameter is:

emcmake cmake ../..
-DCMAKE_INSTALL_PREFIX=/home/xxx/grpc_wasm/grpc/mylib
-DEMSCRIPTEN_SYSTEM_PROCESSOR=x86_64
-DCMAKE_CXX_FLAGS=-mrelaxed-simd
-DCMAKE_C_FLAGS=-mrelaxed-simd
-DCMAKE_BUILD_TYPE=Relese
-DgRPC_PROTOBUF_PROVIDER=package
-DProtobuf_INCLUDE_DIR=/home/xxx/protobuf_wasm/protobuf_src/src
-DProtobuf_LIBRARIES=/home/xxx/protobuf_wasm/protobuf_src/src/.libs
-DProtobuf_PROTOC_LIBRARY:/home/xxx/protobuf_wasm/protobuf_src/src/.libs

Since I have already compiled the protobuf lib using Emscripten, I specify the lib and include directory of libprotobuf manually.

Update2:

About the error: "Could not auto-detect platform", I add #define __linux__ 1 in grpc/include/grpc/support/port_platform.h.

After that, I went through another error: emscripten libc lacks of epoll.h (details and what I have done can be found in here).

I created epoll.h and eventfd.h in emsdk include/sys directory, although the compilation of grpc is successful and got libgrpc.a, I got error of undefined symbol in the link phase as expected (also here). This is because the libc doesn't have the defination of functions in epoll.h and eventfd.h.

It turns out that the Emscripten libc doesn't support epoll system call, and I faild to recompile the libc (also here) to support that.

Anyone has any idea on how to solve the epoll problem? Appreciate any reply and suggestions. Thanks!


问:
Center collection view cells in 1 column via custom UICollectionViewFlowLayout
I have a screen with UICollectionView. This is layout of my screen in portrait:

|     cell1     |

|     cell2     |

|     cell3     |

|     cell4     |

|     cell5     |

Now when I rotate device to landscape here is how it looks.

| cell1    cell2     |

| cell3    cell4     |

| cell5              |

The problem is that I need cells to stay in 1 column and have specific width and this is something I cannot achieve.
The collection view is using IGListKit for layout and self-sizing cells like in IGListKit example project, due to this and specific project structure I have to use custom subclass of UICollectionViewFlowLayout for any custom layout as I cannot override delegates. As soon as I increase the width of cell they align properly in 1 column. However, it seems that because cell width takes such small amount of space it automatically makes 2 columns in collection view. How do I keep one column after rotation while still having desired cell width using custom UICollectionViewFlowLayout?


问:
How does a browser (or other HTTP client) know the size of a chunked HTTP response before it has finished downloading?
I'm teaching myself how to make a rudimentary HTTP server, and I've recently learned about Transfer-Encoding: chunked. I understand that each chunk reports its own size, but all of the documentation I can find seems to indicate that Content-Length on the initial response is only useful for a standard response body, and is ignored for chunked content, making it effectively impossible for a client to know the size of a chunked response body until it's finished.

However, nearly every file I've ever downloaded in my time on the internet has somehow reported its size to the browser ahead of time, so it's clearly not only possible, but common, to the point where it's odd not to.

Is this (non-standard?) behavior common HTTP clients implement, reading the Content-Length (or some other) header as an indicator of total chunked length, or something else entirely?


问:
I can not open the pdf file downloaded from the website
I use my requests to scrap a PDF file from a website. The file appears, but it can not be open. Here is my code:

```<code>url="https://dl.acm.org/doi/pdf/10.1145/3397271.3401063"
html=requests.get(url)
path=Mypath
with open(path, 'wb') as f:
    f.write(html.content)
</code>```

And when I try to open the PDF file, I get an error:

We can't open this file. Something went wrong.

I think there is something wrong with the downloaded file?

Body:
I use my requests to scrap a PDF file from a website. The file appears, but it can not be open. Here is my code:

url="https://dl.acm.org/doi/pdf/10.1145/3397271.3401063"
html=requests.get(url)
path=Mypath
with open(path, 'wb') as f:
    f.write(html.content)

And when I try to open the PDF file, I get an error:

We can't open this file. Something went wrong.

I think there is something wrong with the downloaded file?


问:
JShell: Scanner nextLine() NoSuchElementException when using /open
When using JShell's /open command to open a Java file and run code, user input does not work with Scanner. It will always throw a NoSuchElementException when it reaches the nextLine() method. Does anyone know why this is, and is there a fix/workaround that I am misssing?

Steps to reproduce:

Create a Java file with the following code (for example, test.java):

Scanner scanner = new Scanner(System.in)
String input = scanner.nextLine();
```

Open JShell

Run /open test.java

I have already looked at this answer but using the --execution local did not solve my issue. Calling jshell --execution local and then /open test.java gets a little closer where the program does halt for user input, but then the shell seems to freeze and I cannot type anything. Calling jshell --execution local test.java does seem to work, but after running the file it keeps you in JShell (where the /open command will not work), and it's really inconvenient to have to keep exiting out of JShell to rerun a file. The alternative is having each script end with System.exit(0);, but I don't really understand why something as fundamental as user input appears to be so bugged.

I am using OpenJDK version 17.0.5.

Normally this wouldn't be that big of a deal, but I was hoping to use JShell as a teaching tool...but these input issues/inconveniences are concerning me. Any help is greatly appreciated!

Body:
When using JShell's /open command to open a Java file and run code, user input does not work with Scanner. It will always throw a NoSuchElementException when it reaches the nextLine() method. Does anyone know why this is, and is there a fix/workaround that I am misssing?

Steps to reproduce:

Create a Java file with the following code (for example, test.java):

Scanner scanner = new Scanner(System.in)
String input = scanner.nextLine();

Open JShell

Run /open test.java

I have already looked at this answer but using the --execution local did not solve my issue. Calling jshell --execution local and then /open test.java gets a little closer where the program does halt for user input, but then the shell seems to freeze and I cannot type anything. Calling jshell --execution local test.java does seem to work, but after running the file it keeps you in JShell (where the /open command will not work), and it's really inconvenient to have to keep exiting out of JShell to rerun a file. The alternative is having each script end with System.exit(0);, but I don't really understand why something as fundamental as user input appears to be so bugged.

I am using OpenJDK version 17.0.5.

Normally this wouldn't be that big of a deal, but I was hoping to use JShell as a teaching tool...but these input issues/inconveniences are concerning me. Any help is greatly appreciated!


问:
Keras can't pickle _thread.RLock Custom Layer
I cannot save this model. I inspected the serializability but cannot figure out how to pass the Input layers outputs to the custom layer such that it is serializable so I can save it. Any clues would be great!

```<code>def norm_boxes_graph(boxes, shape):
        """Converts boxes from pixel coordinates to normalized coordinates.
        boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
        shape: [..., (height, width)] in pixels

        Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
        coordinates it's inside the box.

        Returns:
            [..., (y1, x1, y2, x2)] in normalized coordinates
        """
        h, w = tf.split(tf.cast(shape, tf.float32), 2)
        scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
        shift = tf.constant([0., 0., 1., 1.])
        fin = tf.divide(boxes - shift, scale)
        return fin

def get_shape_image(input_image_):
    shape_= tf.shape(input_image_)
    return shape_[1:3]

class GtBoxesLayer(tf.keras.layers.Layer):
    def __init__(self, input_image_=tf.compat.v1.placeholder(tf.float32, shape=[1280, 4]), \

        self.input_image=input_image_
        self.input_image_shape = get_shape_image(tf.Variable(input_image_, trainable=False))

    def call(self, input=tf.Variable(tf.ones(shape=[1280, 4]), dtype=tf.float32)):

        self.norm_boxes_graph_ = norm_boxes_graph(input, self.input_image_shape)
        self._x = {
                 'input_image_':self.input_image, #input
                  } #takes us around the deep_copy error

        return self.norm_boxes_graph_

    def get_config(self):
        config = super(GtBoxesLayer, self).get_config()
        config.update(**self._x)
        return config

    @classmethod
    def from_config(cls, config):
        return cls(**config)

</code>```

The model:

```<code>tf.compat.v1.disable_eager_execution()
input_gt_boxes = keras.layers.Input(
        shape=[None, 4], name="input_gt_boxes", dtype=tf.float32)

input_image = keras.layers.Input(
        shape=[None, None, 3], name="input_image")

gt_boxes = GtBoxesLayer(input_image_=input_image, \
             name='lambda_get_norm_boxes')(input_gt_boxes)

output_ = keras.layers.Dense(1, name='output')(gt_boxes)

model_test_gt_layer = tf.keras.models.Model([input_gt_boxes, input_image],
                                            [output_],
                                            name="m")
</code>```

Running the model

```<code>print("GT layer", model_test_gt_layer.layers[1].get_config())
model_test_gt_layer.compile(tf.keras.optimizers.SGD(), loss='mse')
model_test_gt_layer.summary()
inspect_serializability(tf.keras.layers.serialize(model_test_gt_layer.layers[1]), name="test")

</code>```

Results are:

```<code>GT layer {'name': 'lambda_get_norm_boxes', 'trainable': True, 'dtype': 'float32', 'input_image_': <tf.Tensor 'input_image_4:0' shape=(None, None, None, 3) dtype=float32>}
Model: "m"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_gt_boxes (InputLayer)     [(None, None, 4)]    0
__________________________________________________________________________________________________
lambda_get_norm_boxes (GtBoxesL (None, None, 4)      0           input_gt_boxes[0][0]
__________________________________________________________________________________________________
input_image (InputLayer)        [(None, None, None,  0
__________________________________________________________________________________________________
output (Dense)                  (None, None, 1)      5           lambda_get_norm_boxes[0][0]
==================================================================================================
Total params: 5
Trainable params: 5
Non-trainable params: 0
__________________________________________________________________________________________________

</code>```

Checking Serializability of {'class_name': 'GtBoxesLayer', 'config': {'name': 'lambda_get_norm_boxes', 'trainable': True, 'dtype': 'float32', 'input_image_': <tf.Tensor 'input_image_3:0' shape=(None, None, None, 3) dtype=float32>}}

!!! FAIL serialization: can't pickle thread.RLock objects
WARNING: Did not find non-serializable object in {'class_name': 'GtBoxesLayer', 'config': {'name': 'lambda_get_norm_boxes', 'trainable': True, 'dtype': 'float32', 'input_image': <tf.Tensor 'input_image_3:0' shape=(None, None, None, 3) dtype=float32>}}. This may be an oversight.

Variable:

```<code>FailTuple(test [obj={'class_name': 'GtBoxesLayer', 'config': {'name': 'lambda_get_norm_boxes', 'trainable': True, 'dtype': 'float32', 'input_image_': <tf.Tensor 'input_image_3:0' shape=(None, None, None, 3) dtype=float32>}}, parent=None])
</code>```

was found to be non-serializable. There may be multiple other undetected variables that were non-serializable.
Consider either removing the instantiation/imports of these variables or moving the instantiation into the scope of the function/class.

Error

```<code>model_test_gt_layer.save("../models/my_model_test_constlayer.h5")
</code>```

TypeError: can't pickle _thread.RLock objects

Body:
I cannot save this model. I inspected the serializability but cannot figure out how to pass the Input layers outputs to the custom layer such that it is serializable so I can save it. Any clues would be great!

def norm_boxes_graph(boxes, shape):
        """Converts boxes from pixel coordinates to normalized coordinates.
        boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
        shape: [..., (height, width)] in pixels

        Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
        coordinates it's inside the box.

        Returns:
            [..., (y1, x1, y2, x2)] in normalized coordinates
        """
        h, w = tf.split(tf.cast(shape, tf.float32), 2)
        scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
        shift = tf.constant([0., 0., 1., 1.])
        fin = tf.divide(boxes - shift, scale)
        return fin

def get_shape_image(input_image_):
    shape_= tf.shape(input_image_)
    return shape_[1:3]

class GtBoxesLayer(tf.keras.layers.Layer):
    def __init__(self, input_image_=tf.compat.v1.placeholder(tf.float32, shape=[1280, 4]), \

        self.input_image=input_image_
        self.input_image_shape = get_shape_image(tf.Variable(input_image_, trainable=False))

    def call(self, input=tf.Variable(tf.ones(shape=[1280, 4]), dtype=tf.float32)):

        self.norm_boxes_graph_ = norm_boxes_graph(input, self.input_image_shape)
        self._x = {
                 'input_image_':self.input_image, #input
                  } #takes us around the deep_copy error

        return self.norm_boxes_graph_

    def get_config(self):
        config = super(GtBoxesLayer, self).get_config()
        config.update(**self._x)
        return config

    @classmethod
    def from_config(cls, config):
        return cls(**config)

The model:

tf.compat.v1.disable_eager_execution()
input_gt_boxes = keras.layers.Input(
        shape=[None, 4], name="input_gt_boxes", dtype=tf.float32)

input_image = keras.layers.Input(
        shape=[None, None, 3], name="input_image")

gt_boxes = GtBoxesLayer(input_image_=input_image, \
             name='lambda_get_norm_boxes')(input_gt_boxes)

output_ = keras.layers.Dense(1, name='output')(gt_boxes)

model_test_gt_layer = tf.keras.models.Model([input_gt_boxes, input_image],
                                            [output_],
                                            name="m")

Running the model

print("GT layer", model_test_gt_layer.layers[1].get_config())
model_test_gt_layer.compile(tf.keras.optimizers.SGD(), loss='mse')
model_test_gt_layer.summary()
inspect_serializability(tf.keras.layers.serialize(model_test_gt_layer.layers[1]), name="test")

Results are:

GT layer {'name': 'lambda_get_norm_boxes', 'trainable': True, 'dtype': 'float32', 'input_image_': <tf.Tensor 'input_image_4:0' shape=(None, None, None, 3) dtype=float32>}
Model: "m"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_gt_boxes (InputLayer)     [(None, None, 4)]    0
__________________________________________________________________________________________________
lambda_get_norm_boxes (GtBoxesL (None, None, 4)      0           input_gt_boxes[0][0]
__________________________________________________________________________________________________
input_image (InputLayer)        [(None, None, None,  0
__________________________________________________________________________________________________
output (Dense)                  (None, None, 1)      5           lambda_get_norm_boxes[0][0]
==================================================================================================
Total params: 5
Trainable params: 5
Non-trainable params: 0
__________________________________________________________________________________________________

Checking Serializability of {'class_name': 'GtBoxesLayer', 'config': {'name': 'lambda_get_norm_boxes', 'trainable': True, 'dtype': 'float32', 'input_image_': <tf.Tensor 'input_image_3:0' shape=(None, None, None, 3) dtype=float32>}}

!!! FAIL serialization: can't pickle thread.RLock objects
WARNING: Did not find non-serializable object in {'class_name': 'GtBoxesLayer', 'config': {'name': 'lambda_get_norm_boxes', 'trainable': True, 'dtype': 'float32', 'input_image': <tf.Tensor 'input_image_3:0' shape=(None, None, None, 3) dtype=float32>}}. This may be an oversight.

Variable:

FailTuple(test [obj={'class_name': 'GtBoxesLayer', 'config': {'name': 'lambda_get_norm_boxes', 'trainable': True, 'dtype': 'float32', 'input_image_': <tf.Tensor 'input_image_3:0' shape=(None, None, None, 3) dtype=float32>}}, parent=None])

was found to be non-serializable. There may be multiple other undetected variables that were non-serializable.
Consider either removing the instantiation/imports of these variables or moving the instantiation into the scope of the function/class.

Error

model_test_gt_layer.save("../models/my_model_test_constlayer.h5")

TypeError: can't pickle _thread.RLock objects


问:
MUX API timeframe
Is there a way to get the data in the timeframe > 30 days? It seems the maximum range I can get is 35 days, more than that it would raise an error.
Has anyone do something similar before?</p>

Title: MUX API timeframe


问:
Elimination of need to retrain models in "Shaply Sampling Values"
While reading the paper "A Unified Approach to Interpreting Model
Predictions" by Lundberg and Lee (https://proceedings.neurips.cc/paper/2017/file/8a20a8621978632d76c43dfd28b67767-Paper.pdf), on page 3 I see:

Shapley sampling values are meant to explain any model by: (1) applying sampling approximations
to Equation 4, and (2) approximating the effect of removing a variable from the model by integrating
over samples from the training dataset. This eliminates the need to retrain the model and allows fewer
than pow(2,|F|) differences to be computed. Since the explanation model form of Shapley sampling values
is the same as that for Shapley regression values, it is also an additive feature attribution method.

My question is: how does sampling from the training dataset eliminate the need to retrain models? It is not obvious to me and I cannot think of a mathematical proof. Any reference or explanation would be greatly appreciated. My internet searches have been unsuccessful. Thank you.


问:
SwiftUI Charts Issue
I'm having an issue with SwiftUI charts and was wondering if anyone knows of a solution or has also run into this. I've been trying to plot data for my app and the X axis does not show the dates and the Y axis only has axis marks 0-9. So, I tried to make another file instance to check what's going on. This is what I have

```<code>
import Charts
import SwiftUI

struct Exercise: Identifiable {
    let id = UUID()
    var dateCompleted: Date
    var reps: Int
}

struct ContentView: View {

    private var exerciseMaxRepsArray: [Exercise] = []

    init() { // init dummy data
        for i in 0 ..< 20 {
            let date = Calendar.current.date(byAdding: .day, value: i, to: .now) ?? .now
            let rep = Int.random(in: 1...20)
            exerciseMaxRepsArray.append(
                Exercise(dateCompleted: date, reps: rep)
            )
        }
    }

    var body: some View {

        GroupBox(label: Text("Daily Max Reps")) {
            Chart(exerciseMaxRepsArray) { e in
                LineMark(x: .value("Date", e.dateCompleted, unit: .day),
                         y: .value("Reps", e.reps)
                ) }
            .chartYAxisLabel(position: .trailing, alignment: .center) {
                Text("Reps")
            }
            .chartXAxisLabel(position: .bottom, alignment: .center) {
                Text("Date")

            }
            }
    }
    }
}

</code>```

And this is the result:

I've checked and the issue is not the frame. Has anyone else had this issue or have any clue what could be going on here?

Title: SwiftUI Charts Issue

Body:
I'm having an issue with SwiftUI charts and was wondering if anyone knows of a solution or has also run into this. I've been trying to plot data for my app and the X axis does not show the dates and the Y axis only has axis marks 0-9. So, I tried to make another file instance to check what's going on. This is what I have

import Charts
import SwiftUI

struct Exercise: Identifiable {
    let id = UUID()
    var dateCompleted: Date
    var reps: Int
}

struct ContentView: View {

    private var exerciseMaxRepsArray: [Exercise] = []

    init() { // init dummy data
        for i in 0 ..< 20 {
            let date = Calendar.current.date(byAdding: .day, value: i, to: .now) ?? .now
            let rep = Int.random(in: 1...20)
            exerciseMaxRepsArray.append(
                Exercise(dateCompleted: date, reps: rep)
            )
        }
    }

    var body: some View {

        GroupBox(label: Text("Daily Max Reps")) {
            Chart(exerciseMaxRepsArray) { e in
                LineMark(x: .value("Date", e.dateCompleted, unit: .day),
                         y: .value("Reps", e.reps)
                ) }
            .chartYAxisLabel(position: .trailing, alignment: .center) {
                Text("Reps")
            }
            .chartXAxisLabel(position: .bottom, alignment: .center) {
                Text("Date")

            }
            }
    }
    }
}

And this is the result:

I've checked and the issue is not the frame. Has anyone else had this issue or have any clue what could be going on here?


问:
Using PutsReq to test a post & response and getting 'SyntaxError: Unexpected token e in JSON at position'
Working on an Angular app (golf handicap generator) and following along with a Pluralsight video to implement a form and using Http and he is using PutsReq as a way to just test the post and response.  When I follow everything I am getting the above syntax error but unsure why.  All I am trying to do is send 2 different numbers.  Here is my code

Service Component

```<code>  postUserRoundsForm(userRounds: UserHandicapRounds) : Observable<any> {
    return this.http.post("https://putsreq.com/ZmOvG1coGYa174oig3r1", userRounds);
  }
</code>```

Template Component

```<code>  onSubmit(form: NgForm) {
    console.log('in onSubmit: ', form.valid)
    this.dataService.postUserRoundsForm(this.userHandicapRounds).subscribe({
      next: (v) => console.log('Donzo: ', v),
      error: (e) => console.log('Errorrr: ', e),
      complete: () => console.log('complete: sends NOTHING')
    })
  }
</code>```

HTML

```<code><form #handicapCalcForm="ngForm" (ngSubmit)="onSubmit(handicapCalcForm)">
</code>```

I also checked the network tab in chrome and saw the payload is coming back with the correct data.  I also tried re-serving the app and a different browser and that didn't help either.

I'm fairly new to HTTP and trying to learn more about it but haven't been able to find a reason as to why this isn't working, I would think it should

Body:
Working on an Angular app (golf handicap generator) and following along with a Pluralsight video to implement a form and using Http and he is using PutsReq as a way to just test the post and response.  When I follow everything I am getting the above syntax error but unsure why.  All I am trying to do is send 2 different numbers.  Here is my code

Service Component

  postUserRoundsForm(userRounds: UserHandicapRounds) : Observable<any> {
    return this.http.post("https://putsreq.com/ZmOvG1coGYa174oig3r1", userRounds);
  }

Template Component

  onSubmit(form: NgForm) {
    console.log('in onSubmit: ', form.valid)
    this.dataService.postUserRoundsForm(this.userHandicapRounds).subscribe({
      next: (v) => console.log('Donzo: ', v),
      error: (e) => console.log('Errorrr: ', e),
      complete: () => console.log('complete: sends NOTHING')
    })
  }

HTML

<form #handicapCalcForm="ngForm" (ngSubmit)="onSubmit(handicapCalcForm)">

I also checked the network tab in chrome and saw the payload is coming back with the correct data.  I also tried re-serving the app and a different browser and that didn't help either.

I'm fairly new to HTTP and trying to learn more about it but haven't been able to find a reason as to why this isn't working, I would think it should


问:
Is it possible to control each "JOB" in MySql (MariaDB)?
I'm curious.
ORACLE allows you to operate with JOB's BROKEN.
I wonder if MYSQL can control JOB (EVENT) individually like ORALCE.

EX ) ORACLE
enter image description here

MySql ???


问:
The express server is called to localhost:5001, but not 192.168.219.111
index.js is below .

import { https } from 'firebase-functions';
import express from "express";

import houseRoute from './src/houseRouter.js';

import userRoute from '../src/userRouter.js';

export const house = https.onRequest(houseRoute);

export const user = https.onRequest(userRoute);

houseRouter.js is below

import express from "express"
import request from 'request'
import {xml2json} from './common/common.js'
import {db, serviceKey} from './common/constant.js'

const router = express.Router();

router.post('/houseList', function(req, res, next){

let body = req.body;
getHouseList(res, body);

});

I don't know why I can't call with IP
Experts. please Help me

I try below

import { https } from 'firebase-functions';
import express from "express";
import houseRoute from './src/houseRouter.js';
import userRoute from './src/userRouter.js';

const app = express();
app.listen(5001, "0.0.0.0");

export const api = https.onRequest(app);
export const house = https.onRequest(houseRoute);
export const user = https.onRequest(userRoute);

but I still couldn't call with IP


问:
Error with qwik-lottie animations on page deployment: "Uncaught ReferenceError: document is not defined"
I'm getting this error at the end of cloudflare pages's deploy while using qwik-lottie to render animations in a Qwik project (build and deployment works fine if the use of qwik-lottie is removed):

```<code>15:53:23.426
15:53:23.429    ✨ Success! Uploaded 0 files (126 already uploaded) (0.54 sec)
15:53:23.430
15:53:23.735    ✨ Upload complete!
15:53:25.551    Success: Assets published!
15:53:26.510    Error: Failed to publish your Function. Got error: Uncaught ReferenceError: document is not defined
  at worker.mjs:6315:11 in createTag
  at worker.mjs:7376:26
  at worker.mjs:7383:12
  at worker.mjs:7562:10
  at worker.mjs:6296:26 in lottie2
  at worker.mjs:6297:8
  at worker.mjs:21393:7 in ../node_modules/qwik-lottie/lib/index.qwik.mjs
  at worker.mjs:16:59 in __init
  at worker.mjs:112844:5 in ../server/entry.cloudflare-pages.js
  at worker.mjs:16:59 in __init

</code>```

I know this happens because qwik uses ssr and qwik-lottie refers to document obtaining undefined... are there any workarounds? I've seen nextjs has dynamic imports for these type of issues. Is there something similar for Qwik?

Heres's some of the code:

```<code>  <div id='animation-section' class=' h-full w-full lg:mb-[0px]'>
    <QwikLottie options={logoAnimation.options} />
  </div>
</code>```

Body:
I'm getting this error at the end of cloudflare pages's deploy while using qwik-lottie to render animations in a Qwik project (build and deployment works fine if the use of qwik-lottie is removed):

15:53:23.426
15:53:23.429    ✨ Success! Uploaded 0 files (126 already uploaded) (0.54 sec)
15:53:23.430
15:53:23.735    ✨ Upload complete!
15:53:25.551    Success: Assets published!
15:53:26.510    Error: Failed to publish your Function. Got error: Uncaught ReferenceError: document is not defined
  at worker.mjs:6315:11 in createTag
  at worker.mjs:7376:26
  at worker.mjs:7383:12
  at worker.mjs:7562:10
  at worker.mjs:6296:26 in lottie2
  at worker.mjs:6297:8
  at worker.mjs:21393:7 in ../node_modules/qwik-lottie/lib/index.qwik.mjs
  at worker.mjs:16:59 in __init
  at worker.mjs:112844:5 in ../server/entry.cloudflare-pages.js
  at worker.mjs:16:59 in __init

I know this happens because qwik uses ssr and qwik-lottie refers to document obtaining undefined... are there any workarounds? I've seen nextjs has dynamic imports for these type of issues. Is there something similar for Qwik?

Heres's some of the code:

    <QwikLottie options={logoAnimation.options} />


问:
Handle multiple resultset from THEN Statement in postgresql
```<code>SELECT
    CASE WHEN a.text IS NOT NULL THEN a.text
         WHEN a.number IS NOT NULL THEN a.number::text
         WHEN a.id IS NOT NULL THEN (Select b.text from table_two b
Join table_one a ON b.id = a.id where b.place = 'city' AND a.roll = '20' )
         ELSE NULL
    END
FROM
    table_one a

WHERE
    a.roll = '20';
</code>```

above query returns error as

ERROR:  more than one row returned by a subquery used as an expression

Is there any way to handle the multiple rows returned from subquery. Expecting multiple resultset from THEN statement

```<code>SELECT
    CASE WHEN a.text IS NOT NULL THEN a.text
         WHEN a.number IS NOT NULL THEN a.number::text
         WHEN a.id IS NOT NULL THEN a.id IN (Select b.text from table_two b
Join table_one a ON b.id = a.id where b.place = 'city' AND a.roll = '20' )
         ELSE NULL
    END
FROM
    table_one a

WHERE
    a.roll = '20';
</code>```

If I try to handle multiple result using IN, then I get error

"ERROR:  operator does not exist: integer = character varying

because a.id is integer and sub query returns string results

Body:
SELECT
    CASE WHEN a.text IS NOT NULL THEN a.text
         WHEN a.number IS NOT NULL THEN a.number::text
         WHEN a.id IS NOT NULL THEN (Select b.text from table_two b
Join table_one a ON b.id = a.id where b.place = 'city' AND a.roll = '20' )
         ELSE NULL
    END
FROM
    table_one a

WHERE
    a.roll = '20';

above query returns error as

ERROR:  more than one row returned by a subquery used as an expression

Is there any way to handle the multiple rows returned from subquery. Expecting multiple resultset from THEN statement

SELECT
    CASE WHEN a.text IS NOT NULL THEN a.text
         WHEN a.number IS NOT NULL THEN a.number::text
         WHEN a.id IS NOT NULL THEN a.id IN (Select b.text from table_two b
Join table_one a ON b.id = a.id where b.place = 'city' AND a.roll = '20' )
         ELSE NULL
    END
FROM
    table_one a

WHERE
    a.roll = '20';

If I try to handle multiple result using IN, then I get error

"ERROR:  operator does not exist: integer = character varying

because a.id is integer and sub query returns string results


问:
Retrieving Android Built-In Serial Number in Xamarin Forms
Does anyone knows how to retrieve Serial Number of android in C# Xamarin Forms?

I am developing for Android Version 11 and found out that some coding are not working as it is only compatible for below Android Version 11.

If I write below code, I can get the Unique ID but I just want the Serial Number from the device so that the users can know what device.

```<code>[assembly: Xamarin.Forms.Dependency(typeof(AndroidDevice))]

public class AndroidDevice : IAndroidDevice
{
    public string GetID()
    {
        return Android.Provider.Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);
    }
}
</code>```

How to retrieve that serial number?

Body:
Does anyone knows how to retrieve Serial Number of android in C# Xamarin Forms?

I am developing for Android Version 11 and found out that some coding are not working as it is only compatible for below Android Version 11.

If I write below code, I can get the Unique ID but I just want the Serial Number from the device so that the users can know what device.

[assembly: Xamarin.Forms.Dependency(typeof(AndroidDevice))]

public class AndroidDevice : IAndroidDevice
{
    public string GetID()
    {
        return Android.Provider.Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);
    }
}

How to retrieve that serial number?


问:
How can I get an HTML table to update with the change in a python list of list value?
I'm trying to make a site that updates an information table as the variable the info is from updates. Right now I have a python list of lists containing everything I want displayed, and through flask an HTML table iterates through each list in the list of lists, and creates a table for them. For the sake of this question I have simplified it to a simple table of people and their information.

For the sake of information I should say that the data variable from table.py is pulling it's information from on online API and the amount of information is scaled up by a large margin. Which is why I used Jinja to iterate through each item so I could avoid writing out each row in the table manually.

here is the code

table.py

```<code>headers = ['Name', 'Occupation', 'Age']
data = [['Jake', 'Teacher', '45'],['Sheila', 'Doctor', '34']]
</code>```

pages.py

```<code>from flask import Blueprint, render_template
from table import *

pages = Blueprint(__name__, 'pages')

@pages.route('/')
def table():
    return render_template('table.html', headers=headers, data=data)
</code>```

table.html

```<code><!DOCTYPE html>
<html>
    <body>
        <table border='5' cellpadding='6' cellspacing='0' align="center">
            <tr>
                {% for item in headers %}
                <th>{{ item }}</th>
                {% endfor %}
            </tr>
            {% for row in data %}
            <tr>
                {%for cell in row%}
                <td>{{cell}}</td>
                {%endfor%}
                </tr>
            {% endfor %}
        </table>
    </body>
</html>
</code>```

Let's say for the sake of my example Jake turned 46 and the data variable was adjusted to account for that.
The issue I have with this code right now is when that change is made the table won't update unless the flask server is restarted. I know this is because the code written in HTML for the table is essentially writing out each item instead of displaying the value of each list but my question is does anyone know how I would be able to make the list display the variable value so it will always be adjusted for changes? Is it possible with another framework like Django or a different language like php? Anything would help really.

TLDR: I want my HTML table to update when a value in the data list of lists changes without having to restart the flask server entirely. Does anyone know a way this could be done?

Body:
I'm trying to make a site that updates an information table as the variable the info is from updates. Right now I have a python list of lists containing everything I want displayed, and through flask an HTML table iterates through each list in the list of lists, and creates a table for them. For the sake of this question I have simplified it to a simple table of people and their information.

For the sake of information I should say that the data variable from table.py is pulling it's information from on online API and the amount of information is scaled up by a large margin. Which is why I used Jinja to iterate through each item so I could avoid writing out each row in the table manually.

here is the code

table.py

headers = ['Name', 'Occupation', 'Age']
data = [['Jake', 'Teacher', '45'],['Sheila', 'Doctor', '34']]

pages.py

from flask import Blueprint, render_template
from table import *

pages = Blueprint(__name__, 'pages')

@pages.route('/')
def table():
    return render_template('table.html', headers=headers, data=data)

table.html

<!DOCTYPE html>

                {% for item in headers %}
                {{ item }}
                {% endfor %}

            {% for row in data %}

                {%for cell in row%}
                {{cell}}
                {%endfor%}

            {% endfor %}

Let's say for the sake of my example Jake turned 46 and the data variable was adjusted to account for that.
The issue I have with this code right now is when that change is made the table won't update unless the flask server is restarted. I know this is because the code written in HTML for the table is essentially writing out each item instead of displaying the value of each list but my question is does anyone know how I would be able to make the list display the variable value so it will always be adjusted for changes? Is it possible with another framework like Django or a different language like php? Anything would help really.

TLDR: I want my HTML table to update when a value in the data list of lists changes without having to restart the flask server entirely. Does anyone know a way this could be done?


问:
How to generate multiple files in sequence with data in sequence?
I have to create 50 files in sequence labelled r01.inp to r50.inp and in each file I need this text in sequence as well.

#!/bin/bash
abc2 r01.inp > r01.log

I am trying to generate multiple files and the data inside it to also be in a sequence i.e. file r01.inp has "abc2 r01.inp > r01.log" while the next file r02.inp has "abc2 r02.inp > r02.log" in it and so on.

I know that by using echo and touch I can create the 50 files but all of them has same data and I still have to manually change "r01.inp > r01.log" in each of the files to match the file name.

I am expecting a single script which would generate multiple files with each file having their own respective data.


问:
how to properly add multiple SurfaceView objects to ConstraintLayout on finger press
My program now draws an oval at the touch of a finger and moves it along with the finger.
I want to add a multi-tap so that without releasing the first oval, pressing with the second finger will add the next one.

How my code works now:
Here I create 20 ovals:

```<code>var ovalsViews = Array(20) { OvalsView(this) }
</code>```

In the function MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN (here I put my finger on the screen) I add ovals from the ovals table to the layout (ConstraintLayout):

```<code>layout.addView(ovalsViews[ID])
</code>```

In the MotionEvent.ACTION_MOVE function (here I move my finger on the screen) I change the coordinates of each oval that I hold with my finger:

```<code>ovalsViews[ID]._top = motionEvent.getY(ID)
ovalsViews[ID]._left = motionEvent.getX(ID)
</code>```

And finally, in the function MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP (here I release my finger from the screen) I want to remove the oval that I am holding with my finger:

```<code>layout.removeView(ovalsViews[ID])
</code>```

Now my program is working strangely, when I click once everything works ok, but the next clicks do not add new ovals. Also, when I release the first finger, the oval disappears and in order to get an oval for the first time, now you will need to hit it twice, then three, and so on. What am I doing wrong?

Here is the whole code:

```<code>package com.example.lab10

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.DisplayMetrics
import android.util.Log
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.WindowManager
import androidx.constraintlayout.widget.ConstraintLayout

class TaskSevenNEW : AppCompatActivity() {
    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_task_seven_new)

        title = "Task#7 NEW"

        val layout = findViewById<ConstraintLayout>(R.id.layout_7_NEW)

        var ovalsViews = Array(20) { OvalsView(this) }

        layout.setOnTouchListener(View.OnTouchListener { view, motionEvent ->
            when (motionEvent.getActionMasked()) {
                MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
                    Log.d("touchInfo", "down")

                    val ID: Int = motionEvent.getPointerId(motionEvent.getActionIndex())
                    Log.d("touchInfo", "down ID: " + ID)

                    layout.addView(ovalsViews[ID])
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.d("touchInfo", "move")

                    var idx = 0
                    while (idx < motionEvent.pointerCount) {
                        val ID: Int = motionEvent.getPointerId(idx) // pobranie unikalnego id dla każdego dotyku
                        idx++

                        Log.d("touchInfo", "move ID: " + ID)

                        ovalsViews[ID]._top = motionEvent.getY(ID)
                        ovalsViews[ID]._left = motionEvent.getX(ID)
                    }
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
                    Log.d("touchInfo", "up")

                    val ID: Int = motionEvent.getPointerId(motionEvent.getActionIndex())
                    Log.d("touchInfo", "up ID: " + ID)

                    layout.removeView(ovalsViews[ID])
                }
                else -> Log.d("touchInfo", "unhandled")
            }
            return@OnTouchListener true
        })

    }

    private class OvalsView(context: Context) : SurfaceView(context), SurfaceHolder.Callback {
        private val mSurfaceHolder: SurfaceHolder
        private val mPainter = Paint()
        private var mDrawingThread: Thread? = null
        private val mDisplay = DisplayMetrics()
        private var mDisplayWidth: Int
        private var mDisplayHeight: Int
        private var mRotation = 0f

        private var running = true

        var _top: Float = 0f
        var _left: Float = 0f

        init {
            val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            wm.defaultDisplay.getMetrics(mDisplay)
            mDisplayWidth = mDisplay.widthPixels
            mDisplayHeight = mDisplay.heightPixels
            mPainter.isAntiAlias = true
            mPainter.color = Color.RED
            mSurfaceHolder = holder
            mSurfaceHolder.addCallback(this)
        }

        private fun animateOvals(): Boolean {
            mRotation += 1
            return true
        }

        private fun drawWheel(canvas: Canvas) {
            canvas.drawColor(Color.WHITE)
//            canvas.rotate(mRotation, mDisplayWidth / 2f, mDisplayHeight / 2f)

            //drawOval(float left, float top, float right, float bottom, @NonNull Paint paint)

//            canvas.drawOval(mDisplayWidth/2f - 100f/2f - 100f, mDisplayHeight/2 + 100f/2f,
//                mDisplayWidth/2f + 100f/2f + 100f, mDisplayHeight/2f - 100/2f, mPainter)

            if (_top > 0f && _left > 0f)
                canvas.drawOval(_left, _top, _left + 200f, _top + 350f, mPainter)
        }

        override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
            mDisplayWidth = w
            mDisplayHeight = h
            super.onSizeChanged(w, h, oldw, oldh)
        }

        override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        }

        override fun surfaceDestroyed(holder: SurfaceHolder) {
            if (mDrawingThread != null) {
                mDrawingThread!!.interrupt()
                running = false
                mDrawingThread!!.join()
                Log.e("qqq", "Thread done")
            }
        }

        override fun surfaceCreated(holder: SurfaceHolder) {

            mDrawingThread = Thread(Runnable {

                var frameStartTime = System.nanoTime();
                var frameTime: Long = 0
                var canvas: Canvas? = null
                while (!Thread.currentThread().isInterrupted && animateOvals() && running) {

                    canvas = mSurfaceHolder.lockCanvas()
                    if (canvas != null) {
                        drawWheel(canvas)
                        mSurfaceHolder.unlockCanvasAndPost(canvas)
                    }

                    frameTime = (System.nanoTime() - frameStartTime) / 1000000
                    if (frameTime < MAX_FRAME_TIME) // faster than the max fps - limit the FPS
                    {
                        try {
                            Thread.sleep(MAX_FRAME_TIME - frameTime)
                        } catch (e: InterruptedException) {
                            // ignore
                        }
                    }
                }
            })
            mDrawingThread!!.start()
        }
    }
}
</code>```

Body:
My program now draws an oval at the touch of a finger and moves it along with the finger.
I want to add a multi-tap so that without releasing the first oval, pressing with the second finger will add the next one.

How my code works now:
Here I create 20 ovals:

var ovalsViews = Array(20) { OvalsView(this) }

In the function MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN (here I put my finger on the screen) I add ovals from the ovals table to the layout (ConstraintLayout):

layout.addView(ovalsViews[ID])

In the MotionEvent.ACTION_MOVE function (here I move my finger on the screen) I change the coordinates of each oval that I hold with my finger:

ovalsViews[ID]._top = motionEvent.getY(ID)
ovalsViews[ID]._left = motionEvent.getX(ID)

And finally, in the function MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP (here I release my finger from the screen) I want to remove the oval that I am holding with my finger:

layout.removeView(ovalsViews[ID])

Now my program is working strangely, when I click once everything works ok, but the next clicks do not add new ovals. Also, when I release the first finger, the oval disappears and in order to get an oval for the first time, now you will need to hit it twice, then three, and so on. What am I doing wrong?

Here is the whole code:

package com.example.lab10

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.DisplayMetrics
import android.util.Log
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.WindowManager
import androidx.constraintlayout.widget.ConstraintLayout

class TaskSevenNEW : AppCompatActivity() {
    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_task_seven_new)

        title = "Task#7 NEW"

        val layout = findViewById<ConstraintLayout>(R.id.layout_7_NEW)

        var ovalsViews = Array(20) { OvalsView(this) }

        layout.setOnTouchListener(View.OnTouchListener { view, motionEvent ->
            when (motionEvent.getActionMasked()) {
                MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
                    Log.d("touchInfo", "down")

                    val ID: Int = motionEvent.getPointerId(motionEvent.getActionIndex())
                    Log.d("touchInfo", "down ID: " + ID)

                    layout.addView(ovalsViews[ID])
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.d("touchInfo", "move")

                    var idx = 0
                    while (idx < motionEvent.pointerCount) {
                        val ID: Int = motionEvent.getPointerId(idx) // pobranie unikalnego id dla każdego dotyku
                        idx++

                        Log.d("touchInfo", "move ID: " + ID)

                        ovalsViews[ID]._top = motionEvent.getY(ID)
                        ovalsViews[ID]._left = motionEvent.getX(ID)
                    }
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
                    Log.d("touchInfo", "up")

                    val ID: Int = motionEvent.getPointerId(motionEvent.getActionIndex())
                    Log.d("touchInfo", "up ID: " + ID)

                    layout.removeView(ovalsViews[ID])
                }
                else -> Log.d("touchInfo", "unhandled")
            }
            return@OnTouchListener true
        })

    }

    private class OvalsView(context: Context) : SurfaceView(context), SurfaceHolder.Callback {
        private val mSurfaceHolder: SurfaceHolder
        private val mPainter = Paint()
        private var mDrawingThread: Thread? = null
        private val mDisplay = DisplayMetrics()
        private var mDisplayWidth: Int
        private var mDisplayHeight: Int
        private var mRotation = 0f

        private var running = true

        var _top: Float = 0f
        var _left: Float = 0f

        init {
            val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            wm.defaultDisplay.getMetrics(mDisplay)
            mDisplayWidth = mDisplay.widthPixels
            mDisplayHeight = mDisplay.heightPixels
            mPainter.isAntiAlias = true
            mPainter.color = Color.RED
            mSurfaceHolder = holder
            mSurfaceHolder.addCallback(this)
        }

        private fun animateOvals(): Boolean {
            mRotation += 1
            return true
        }

        private fun drawWheel(canvas: Canvas) {
            canvas.drawColor(Color.WHITE)
//            canvas.rotate(mRotation, mDisplayWidth / 2f, mDisplayHeight / 2f)

            //drawOval(float left, float top, float right, float bottom, @NonNull Paint paint)

//            canvas.drawOval(mDisplayWidth/2f - 100f/2f - 100f, mDisplayHeight/2 + 100f/2f,
//                mDisplayWidth/2f + 100f/2f + 100f, mDisplayHeight/2f - 100/2f, mPainter)

            if (_top > 0f && _left > 0f)
                canvas.drawOval(_left, _top, _left + 200f, _top + 350f, mPainter)
        }

        override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
            mDisplayWidth = w
            mDisplayHeight = h
            super.onSizeChanged(w, h, oldw, oldh)
        }

        override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        }

        override fun surfaceDestroyed(holder: SurfaceHolder) {
            if (mDrawingThread != null) {
                mDrawingThread!!.interrupt()
                running = false
                mDrawingThread!!.join()
                Log.e("qqq", "Thread done")
            }
        }

        override fun surfaceCreated(holder: SurfaceHolder) {

            mDrawingThread = Thread(Runnable {

                var frameStartTime = System.nanoTime();
                var frameTime: Long = 0
                var canvas: Canvas? = null
                while (!Thread.currentThread().isInterrupted && animateOvals() && running) {

                    canvas = mSurfaceHolder.lockCanvas()
                    if (canvas != null) {
                        drawWheel(canvas)
                        mSurfaceHolder.unlockCanvasAndPost(canvas)
                    }

                    frameTime = (System.nanoTime() - frameStartTime) / 1000000
                    if (frameTime < MAX_FRAME_TIME) // faster than the max fps - limit the FPS
                    {
                        try {
                            Thread.sleep(MAX_FRAME_TIME - frameTime)
                        } catch (e: InterruptedException) {
                            // ignore
                        }
                    }
                }
            })
            mDrawingThread!!.start()
        }
    }
}


问:
ThreadAbortException when running nunit test with Thread.SetApartmentState(ApartmentState.STA)
I have the following classes. I am trying to test the component that I built but its throwing ThreadAbortException and I'm unable to fix the issue. Following is the code I've written

This is on codebehind of

UserPromptWPS.xaml.cs

```<code>public partial class UserPromptWPS : Window
{
        public bool WPSButtonFailed { get; set; }
        public bool WPSButtonPassed { get; set; }
        public bool DoTest { get; set; }

        private IWebDriver driver;
        private WebDriverWait wait;

        public UserPromptWPS(IWebDriver driver, WebDriverWait wait)
        {
            InitializeComponent();
            this.driver = driver;
            this.wait = wait;

            Loaded += UserPromptWPS_Loaded;
        }

        private async void UserPromptWPS_Loaded(object sender, RoutedEventArgs e)
        {
            WPSButton wpsButton = new WPSButton();

            await Task.Run(() =>
            {
               while(true)
               {
                  if(wpsButton.ClickWPS(driver,wait))
                  {
                      break;
                  }
               }

            });
            this.Close();
        }
}
</code>```

Here WPSButton is an object I'm calling. And below is the NUnit test I've written.

NUnit Test

```<code>[TestFixture]
public class WPSButtonTests
{
    [Test]
    public void ExecuteClickWPS_Success_ReturnsTrue()
    {
        var result = false;

        Thread thread = new Thread(new ThreadStart(delegate
        {
            LoginWebGui loginWebGui = new LoginWebGui();
            ClearLog clearLog = new ClearLog();
            WPSButton wpsButton = new WPSButton();
            LogoutWebGui logoutWebGui = new LogoutWebGui();

            var webDriverSetup = new WebDriverSetup();
            var driver = webDriverSetup.WebDriver;
            var wait = webDriverSetup.Wait;
            loginWebGui.ExecuteLogin(driver, wait);
            clearLog.ExecuteClearLog(driver, wait);

            UserPromptWPS userPromptWPS = new UserPromptWPS(driver, wait);
            userPromptWPS.Closed += (s, e) => userPromptWPS.Dispatcher.InvokeShutdown();
            userPromptWPS.ShowDialog();

            result = userPromptWPS.WPSButtonPassed;
        }));

        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();

        Assert.That(result, Is.True);

    }
}
</code>```

Here running this unit test throwing ThreadAbortException error. What I'm trying to achieve here is to run an infinite loop when 'UserPromptWPS' window is open and upon (if) condition is met then break the loop and close the window. I couldn't fix the issue of why am I getting ThreadAbortException error.
If someone could help me out please.

Body:
I have the following classes. I am trying to test the component that I built but its throwing ThreadAbortException and I'm unable to fix the issue. Following is the code I've written

This is on codebehind of

UserPromptWPS.xaml.cs

public partial class UserPromptWPS : Window
{
        public bool WPSButtonFailed { get; set; }
        public bool WPSButtonPassed { get; set; }
        public bool DoTest { get; set; }

        private IWebDriver driver;
        private WebDriverWait wait;

        public UserPromptWPS(IWebDriver driver, WebDriverWait wait)
        {
            InitializeComponent();
            this.driver = driver;
            this.wait = wait;

            Loaded += UserPromptWPS_Loaded;
        }

        private async void UserPromptWPS_Loaded(object sender, RoutedEventArgs e)
        {
            WPSButton wpsButton = new WPSButton();

            await Task.Run(() =>
            {
               while(true)
               {
                  if(wpsButton.ClickWPS(driver,wait))
                  {
                      break;
                  }
               }

            });
            this.Close();
        }
}

Here WPSButton is an object I'm calling. And below is the NUnit test I've written.

NUnit Test

[TestFixture]
public class WPSButtonTests
{
    [Test]
    public void ExecuteClickWPS_Success_ReturnsTrue()
    {
        var result = false;

        Thread thread = new Thread(new ThreadStart(delegate
        {
            LoginWebGui loginWebGui = new LoginWebGui();
            ClearLog clearLog = new ClearLog();
            WPSButton wpsButton = new WPSButton();
            LogoutWebGui logoutWebGui = new LogoutWebGui();

            var webDriverSetup = new WebDriverSetup();
            var driver = webDriverSetup.WebDriver;
            var wait = webDriverSetup.Wait;
            loginWebGui.ExecuteLogin(driver, wait);
            clearLog.ExecuteClearLog(driver, wait);

            UserPromptWPS userPromptWPS = new UserPromptWPS(driver, wait);
            userPromptWPS.Closed += (s, e) => userPromptWPS.Dispatcher.InvokeShutdown();
            userPromptWPS.ShowDialog();

            result = userPromptWPS.WPSButtonPassed;
        }));

        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();

        Assert.That(result, Is.True);

    }
}

Here running this unit test throwing ThreadAbortException error. What I'm trying to achieve here is to run an infinite loop when 'UserPromptWPS' window is open and upon (if) condition is met then break the loop and close the window. I couldn't fix the issue of why am I getting ThreadAbortException error.
If someone could help me out please.


问:
Python - Double integral of matrix
I want to solve an equation which has matrix in it with Python.

I tried to use the scimpy.integrate.dblquad, but I don't figure how to use it.

Here is my code :

import numpy as np
import sympy as smp

x = smp.symbols('x')
y = smp.symbols('y')

B = np.array([[2x, 0., 0],[0, 2y, 0]])
BT = np.transpose(B)

MinY = 0
MaxY = 0.1
MinX = 0
MaxX = 0.2
f = lambda x, y: BT50B*10
k = integrate.dblquad(f,MinX, MaxX, MinY, MaxY)[0]

I get this: ValueError: operands could not be broadcast together with shapes (3,2) (2,3)

how I can correct my code ?

Title: Python - Double integral of matrix


问:
How can I take a data set that is 2 columns by 225 rows and print it in as few pages as possible?
In excel, I have to make a table list for 225 people.  Column #1 is name.  Column #2 is table number. I don't want it to be 6 pages long. If I move 56 rows side by side and do that 4 times I lose the sorting (alphabetizing ability).  How can I make it 8 columns (The first A-J, the second K-P, the third Q-U....) or something like that?

I tried selecting 56 rows and moving them. Then the next 56 and moving them etc. But you lose the ability to sort and filter.

I tried transposing then using from table range making custom columns, but it didn't quite work and is very tedious.  Is there an easier way?