问:
Using Herkou, Python, Gunicorn, and Flask trying to host a web application but getting application error
I am using python, heroku, gunicorn, and flask attempting to host a very basic web application. The URL provides me only with the error shown below:
enter image description here

Here are the errors in the error log, they are common, ive read as many stack overflow questions about this issue as I can find and none have helped.

2022-12-07T00:43:06.517424+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2022-12-07T00:43:06.517467+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2022-12-07T00:43:06.672564+00:00 heroku[web.1]: Process exited with status 1
2022-12-07T00:43:06.728584+00:00 heroku[web.1]: State changed from up to crashed
2022-12-07T00:43:19.882600+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=spo-bet-an.herokuapp.com request_id=b11bfee6-9bdd-4a2d-a446-92a927818e54 fwd="65.189.83.94" dyno= connect= service= status=503 bytes= protocol=https
2022-12-07T00:43:20.529051+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=spo-bet-an.herokuapp.com request_id=d1e24818-b06e-4cec-b254-11812b71dd9c fwd="65.189.83.94" dyno= connect= service= status=503 bytes= protocol=https

Here are my files for reference:

home.py

```<code>import os
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello World'

if __name__ == '__main__':
    port = int(os.environ.get('PORT'))
    app.run(host='0.0.0.0', port=port, debug=True)
</code>```

Procfile

```<code>web: gunicorn --bind 0.0.0.0:${PORT} home:app
</code>```

I have also tried

```<code>web: gunicorn home:app
</code>```

with the following Procfile

```<code>import os
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello World'

if __name__ == '__main__':
    app.run()
</code>```

I have tried as many changes as i can think of to the Profile and not one thing has helped. I am a software developer and have a decent understanding of things like this and am completely stumped. At this point the only thing that could potentially be affecting it is the requirements.txt Ive seen people say one of their packages was wrong but I have no idea how to determine if any of mine are wrong, after typing this I will most likely comment them out one by one and see if that can isolate the issue. here is said file:

```<code>async-generator==1.10
attrs==22.1.0
certifi==2022.9.24
cffi==1.15.1
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
dnspython==2.2.1
Flask==2.2.2
gunicorn==20.1.0
h11==0.14.0
heroku==0.1.4
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
outcome==1.2.0
packaging==21.3
pycparser==2.21
pymongo==4.3.3
pyparsing==3.0.9
PySocks==1.7.1
python-dateutil==1.5
python-dotenv==0.21.0
requests==2.28.1
selenium==4.6.1
sniffio==1.3.0
sortedcontainers==2.4.0
tqdm==4.64.1
trio==0.22.0
trio-websocket==0.9.2
urllib3==1.26.13
webdriver-manager==3.8.5
Werkzeug==2.2.2
wsproto==1.2.0
uwsgi
gunicorn

</code>```

I have tried with and without both the gunicorn and uwsgi, ive made attempts to use uwsgi instead of guniocrn though I dont think I was using it correctly nor think my pip install of uswgi worked, or if it was even needed. For more reference points, I am on windows, I am not using a virtualenv, and I have not changed any system variables because I could not find anyone saying how to change them or what to. All files are in the directory as well. If there are any other files that need to be seen please let me know, or if you have even remotely any idea what could help, it would be greatly greatly appreciated.

Thanks

I am trying to host a flask python application using gunicorn and heroku and am getting an application error.

Body:
I am using python, heroku, gunicorn, and flask attempting to host a very basic web application. The URL provides me only with the error shown below:
enter image description here

Here are the errors in the error log, they are common, ive read as many stack overflow questions about this issue as I can find and none have helped.

2022-12-07T00:43:06.517424+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2022-12-07T00:43:06.517467+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2022-12-07T00:43:06.672564+00:00 heroku[web.1]: Process exited with status 1
2022-12-07T00:43:06.728584+00:00 heroku[web.1]: State changed from up to crashed
2022-12-07T00:43:19.882600+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=spo-bet-an.herokuapp.com request_id=b11bfee6-9bdd-4a2d-a446-92a927818e54 fwd="65.189.83.94" dyno= connect= service= status=503 bytes= protocol=https
2022-12-07T00:43:20.529051+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=spo-bet-an.herokuapp.com request_id=d1e24818-b06e-4cec-b254-11812b71dd9c fwd="65.189.83.94" dyno= connect= service= status=503 bytes= protocol=https

Here are my files for reference:

home.py

import os
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello World'

if __name__ == '__main__':
    port = int(os.environ.get('PORT'))
    app.run(host='0.0.0.0', port=port, debug=True)

Procfile

web: gunicorn --bind 0.0.0.0:${PORT} home:app

I have also tried

web: gunicorn home:app

with the following Procfile

import os
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello World'

if __name__ == '__main__':
    app.run()

I have tried as many changes as i can think of to the Profile and not one thing has helped. I am a software developer and have a decent understanding of things like this and am completely stumped. At this point the only thing that could potentially be affecting it is the requirements.txt Ive seen people say one of their packages was wrong but I have no idea how to determine if any of mine are wrong, after typing this I will most likely comment them out one by one and see if that can isolate the issue. here is said file:

async-generator==1.10
attrs==22.1.0
certifi==2022.9.24
cffi==1.15.1
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
dnspython==2.2.1
Flask==2.2.2
gunicorn==20.1.0
h11==0.14.0
heroku==0.1.4
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
outcome==1.2.0
packaging==21.3
pycparser==2.21
pymongo==4.3.3
pyparsing==3.0.9
PySocks==1.7.1
python-dateutil==1.5
python-dotenv==0.21.0
requests==2.28.1
selenium==4.6.1
sniffio==1.3.0
sortedcontainers==2.4.0
tqdm==4.64.1
trio==0.22.0
trio-websocket==0.9.2
urllib3==1.26.13
webdriver-manager==3.8.5
Werkzeug==2.2.2
wsproto==1.2.0
uwsgi
gunicorn

I have tried with and without both the gunicorn and uwsgi, ive made attempts to use uwsgi instead of guniocrn though I dont think I was using it correctly nor think my pip install of uswgi worked, or if it was even needed. For more reference points, I am on windows, I am not using a virtualenv, and I have not changed any system variables because I could not find anyone saying how to change them or what to. All files are in the directory as well. If there are any other files that need to be seen please let me know, or if you have even remotely any idea what could help, it would be greatly greatly appreciated.

Thanks

I am trying to host a flask python application using gunicorn and heroku and am getting an application error.


来源: stackexchange

问:
how run gcc command from python script
I'm using this command from the terminal to create a text file that saves the errors without creating an output file.

```<code> strace -e write -f gcc -I/home/user/my_test/headers -fsyntax-only test_file.c 2>log.txt
</code>```

I was wondering if there is a python library that allow me to run the command above using a script. I'll appreciate any suggestion. thanks.

so I tried and it works as in the terminal

```<code>import subprocess
subprocess.run(["strace", "-e", "write", "-f", "gcc", "-I/home/user/my_test/headers", "-fsyntax-only", "test_file.c"])
</code>```

but if I use this

```<code>import subprocess
subprocess.run(["strace", "-e", "write", "-f", "gcc", "-I/home/user/my_test/headers", "-fsyntax-only", "test_file.c", "2>log.txt"])
</code>```

it errors out. I think i'm missing something there.

```<code>write(2, "\33[01m\33[Kgcc:\33[m\33[K \33[01;31m\33[Ker"..., 81gcc: error: 2> log.txt: No such file or directory                           ) = 81
+++ exited with 1 +++
</code>```

ContentLicense: CC BY-SA 4.0

Title: how run gcc command from python script

Body:
I'm using this command from the terminal to create a text file that saves the errors without creating an output file.

 strace -e write -f gcc -I/home/user/my_test/headers -fsyntax-only test_file.c 2>log.txt

I was wondering if there is a python library that allow me to run the command above using a script. I'll appreciate any suggestion. thanks.

so I tried and it works as in the terminal

import subprocess
subprocess.run(["strace", "-e", "write", "-f", "gcc", "-I/home/user/my_test/headers", "-fsyntax-only", "test_file.c"])

but if I use this

import subprocess
subprocess.run(["strace", "-e", "write", "-f", "gcc", "-I/home/user/my_test/headers", "-fsyntax-only", "test_file.c", "2>log.txt"])

it errors out. I think i'm missing something there.

write(2, "\33[01m\33[Kgcc:\33[m\33[K \33[01;31m\33[Ker"..., 81gcc: error: 2> log.txt: No such file or directory                           ) = 81
+++ exited with 1 +++


问:
Capture value of input counter created with tailwind and alpine JS
I have a counter made with Tailwind and Alpine JS. I am trying to capture the value of the input field when the user types in or uses the counter buttons, but I am only able to capture the value when a user types their response. Any ideas on how to capture the values when the user uses the counter buttons to increment or decrement?</p>
```<code><!-- counter -->

<div class="z-50 relative" x-data="{ quantity : 0 }">
    <div class="fisker-bold text-gray-900 text-center mx-auto text-sm">
        Quantity</div>
    <div class=" mt-1 mb-3 flex rounded-md justify-center">
        <button @click="quantity--" type="button"
            class=" relative inline-flex items-center space-x-2 px-4 py-2  text-sm font-medium rounded-l-md text-gray-700 bg-gray-50 hover:bg-gray-100 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 bg-gray-300">
            -
        </button>
        <div class="relative flex items-stretch focus-within:z-10">
            <input type="text" x-model="quantity" name="qty-1" id="qty-1"
                class="text-center focus:ring-blue-500 focus:border-indigo-500 block w-20 text-gray-900 rounded-none pl-3 sm:text-sm border-gray-300 bg-gray-300"
                value="0">
        </div>
        <button @click="quantity++" type="button"
            class="relative inline-flex items-center space-x-2 px-4 py-2  text-sm font-medium rounded-r-md text-gray-700 bg-gray-50 hover:bg-gray-100 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 bg-gray-300">
            +
        </button>
    </div>
</div>
<!-- counter -->
</code>```

```<code> <script>
        $(function () {
            $("#qty-1").on("change", function () {
                var text = $(this).find('option:selected').text();
                $('#qty').text(' x' + text);

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

Body:
I have a counter made with Tailwind and Alpine JS. I am trying to capture the value of the input field when the user types in or uses the counter buttons, but I am only able to capture the value when a user types their response. Any ideas on how to capture the values when the user uses the counter buttons to increment or decrement?

        Quantity

        <button @click="quantity--" type="button"
            class=" relative inline-flex items-center space-x-2 px-4 py-2  text-sm font-medium rounded-l-md text-gray-700 bg-gray-50 hover:bg-gray-100 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 bg-gray-300">
            -
        </button>

            <input type="text" x-model="quantity" name="qty-1" id="qty-1"
                class="text-center focus:ring-blue-500 focus:border-indigo-500 block w-20 text-gray-900 rounded-none pl-3 sm:text-sm border-gray-300 bg-gray-300"
                value="0">

        <button @click="quantity++" type="button"
            class="relative inline-flex items-center space-x-2 px-4 py-2  text-sm font-medium rounded-r-md text-gray-700 bg-gray-50 hover:bg-gray-100 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 bg-gray-300">
            +
        </button>


问:
Databricks Autoloader - dealing with combined files
I'm working with some files that have some complexities

multiple tab files concatenated into 1

csv files with some meta data prior to the csv data

csv files with an extra row after the header that should be ignored

csv files with log information interspersed into the file

My question relates to whether autoloader can split the stream (ie 1 input file to 2 or more output files) based on pattern matching or has some other mechanism for dealing with these scenarios

Ignoring the metadata using skipRows isn't an option as I want to retain the metadata in a separate output file
The RescuedDataColumn option doesn't appear to be a valid approach as the data doesn't fall into the 3 identified scenarios (from the docs). ie.

The column is missing from the schema.

Type mismatches.

Case mismatches.


问:
Extracting replies using Twitter V2
I have been trying to get the replies given a conversation id and every time I get the following response.Json response from twitter

My credential file is a json file and it is set as below:

```<code>
</code>```

{
"API key": "the api key",
"API Key Secret": "the api secret",
"Bearer Token": "bearer token",
"Access Token": "access token",
"Access Token Secret": "access token secret",
"Client ID": "client id",
"Client Secret": "client secret"
}

```<code>
</code>```

I use the bearer token from the credential file as the header in the request url. The sample code for search url is below:

```<code>
</code>```

search_url = "https://api.twitter.com/2/tweets/search/recent" #Change to the endpoint you want to collect data from

```<code> #change params based on the endpoint you are using
query_params = { 'query':'conversation_id:{}'.format(convo_id),  'tweet.fields':'author_id,conversation_id,in_reply_to_user_id,referenced_tweets,public_metrics',
                'pagination_token': {} }
</code>```
```<code>
</code>```

I even tried running the program on Postman and got the same result there. The result is constant for any given conversation id.

I'm not sure where I have mistaken.

Title: Extracting replies using Twitter V2

Body:
I have been trying to get the replies given a conversation id and every time I get the following response.Json response from twitter

My credential file is a json file and it is set as below:

{
"API key": "the api key",
"API Key Secret": "the api secret",
"Bearer Token": "bearer token",
"Access Token": "access token",
"Access Token Secret": "access token secret",
"Client ID": "client id",
"Client Secret": "client secret"
}

I use the bearer token from the credential file as the header in the request url. The sample code for search url is below:

search_url = "https://api.twitter.com/2/tweets/search/recent" #Change to the endpoint you want to collect data from

 #change params based on the endpoint you are using
query_params = { 'query':'conversation_id:{}'.format(convo_id),  'tweet.fields':'author_id,conversation_id,in_reply_to_user_id,referenced_tweets,public_metrics',
                'pagination_token': {} }

I even tried running the program on Postman and got the same result there. The result is constant for any given conversation id.

I'm not sure where I have mistaken.


问:
bind_rows() error: Error in `bind_rows()`: ! Can't combine `..1$comment_id` <character> and `..2$comment_id` <integer>
I am running a pretty long function that deals with reddit comment data from RedditExtractoR:

```<code># Create an empty data frame to store the thread information
threads_df = data.frame(date = character(), title = character(), url = character(), subreddit = character())

# Bind threads

threads_df = bind_rows(
  data.frame(threads1, subreddit = "SSBM"),
  data.frame(threads2, subreddit = "funny"),
  data.frame(threads3, subreddit = "meltyblood"),
  data.frame(threads4, subreddit = "bloomington")
)

# Get the comments from each thread
comments_df = data.frame()
for (i in 1:nrow(threads_df)) {
  result = get_thread_content(threads_df$url[i])[[2]]
  result$subreddit = threads_df$subreddit[i]
  comments_df = bind_rows(comments_df, result)
  print(paste("Completed thread", i, "of", nrow(threads_df)))
  if (nrow(result) == 0) {
    stop("Failed to retrieve comments for thread", i)
  }
  if (i %% 100 == 0) {
    print("Checking for timeouts")
    Sys.sleep(10)
  }
}

</code>```

After getting to thread 115/977, I am greeted with the following error:

```<code>Error in `bind_rows()`:
! Can't combine `..1$comment_id` <character> and `..2$comment_id` <integer>.
---
Backtrace:
 1. dplyr::bind_rows(comments_df, result)
 4. vctrs::vec_rbind(!!!dots, .names_to = .id)
</code>```

I have tried using trycatch to skip the error only to compile even more errors that I don't understand. It would be ideal to just skip threads that generated this error. I tried the following to do that, but it only complicated things past a level that I can comprehend:

```<code># Get the comments from each thread
comments_df = data.frame()
for (i in 1:nrow(threads_df)) {
  result = tryCatch(
    expr = {
      get_thread_content(threads_df$url[i])[[2]]
    },
    error = function(e) {
      NULL
    }
  )
  if (is.null(result)) {
    print(paste("Skipped thread", i, "due to bind_rows error"))
    next
  }
  result$subreddit = threads_df$subreddit[i]
  comments_df = bind_rows(comments_df, result)
  print(paste("Completed thread", i, "of", nrow(threads_df)))
  if (nrow(result) == 0) {
    stop("Failed to retrieve comments for thread", i)
  }
  if (i %% 100 == 0) {
    print("Checking for timeouts")
    Sys.sleep(10)
  }
}
</code>```

Does anyone have any insight into why this original error might be happening and what I could try to fix it? If not, is there maybe another way to bypass the error?

Body:
I am running a pretty long function that deals with reddit comment data from RedditExtractoR:

# Create an empty data frame to store the thread information
threads_df = data.frame(date = character(), title = character(), url = character(), subreddit = character())

# Bind threads

threads_df = bind_rows(
  data.frame(threads1, subreddit = "SSBM"),
  data.frame(threads2, subreddit = "funny"),
  data.frame(threads3, subreddit = "meltyblood"),
  data.frame(threads4, subreddit = "bloomington")
)

# Get the comments from each thread
comments_df = data.frame()
for (i in 1:nrow(threads_df)) {
  result = get_thread_content(threads_df$url[i])[[2]]
  result$subreddit = threads_df$subreddit[i]
  comments_df = bind_rows(comments_df, result)
  print(paste("Completed thread", i, "of", nrow(threads_df)))
  if (nrow(result) == 0) {
    stop("Failed to retrieve comments for thread", i)
  }
  if (i %% 100 == 0) {
    print("Checking for timeouts")
    Sys.sleep(10)
  }
}

After getting to thread 115/977, I am greeted with the following error:

Error in `bind_rows()`:
! Can't combine `..1$comment_id` <character> and `..2$comment_id` <integer>.
---
Backtrace:
 1. dplyr::bind_rows(comments_df, result)
 4. vctrs::vec_rbind(!!!dots, .names_to = .id)

I have tried using trycatch to skip the error only to compile even more errors that I don't understand. It would be ideal to just skip threads that generated this error. I tried the following to do that, but it only complicated things past a level that I can comprehend:

# Get the comments from each thread
comments_df = data.frame()
for (i in 1:nrow(threads_df)) {
  result = tryCatch(
    expr = {
      get_thread_content(threads_df$url[i])[[2]]
    },
    error = function(e) {
      NULL
    }
  )
  if (is.null(result)) {
    print(paste("Skipped thread", i, "due to bind_rows error"))
    next
  }
  result$subreddit = threads_df$subreddit[i]
  comments_df = bind_rows(comments_df, result)
  print(paste("Completed thread", i, "of", nrow(threads_df)))
  if (nrow(result) == 0) {
    stop("Failed to retrieve comments for thread", i)
  }
  if (i %% 100 == 0) {
    print("Checking for timeouts")
    Sys.sleep(10)
  }
}

Does anyone have any insight into why this original error might be happening and what I could try to fix it? If not, is there maybe another way to bypass the error?


问:
Managing configs for client-side npm modules - is there a preferred/standard way to go about this?
My primary question is whether or not the 'config' should be in a separate JSON/rc format, or if a general withCustomConfig-like function makes more sense. I realize this may be a matter of opinion, but I'm interested in hearing what more experienced developers think, as my searches for more information on this topic are coming up completely empty and I'm sure there's a preferred/standard way of handling something like this.

Essentially, I'm building an npm package for the generation/parsing of markdown for a specific use-case. The package allows for custom configurations to the characters utilized in the structure of the markdown itself. Originally, I was just intending on having users apply changes to the config via a simple withCustomConfig function (that accepts a config object); however, I started wondering if setting it via a JS function was not ideal - as the config's state then generally appears to seem more transient/loosely-defined than a completely separate rc or JSON config. I realize that is a matter of perception, but I think many people would share the same sentiment. And this poses a large risk because any changes to the configuration post-production would result in existing markdown becoming unparseable.

So, I started looking into having users configure a separate JSON config file. In order to import that into the browser, I realized I'd have to parse the JSON and convert it into a JS module before the user builds their client side application, which was relatively easy thanks to packages like fs. I set-up a small CLI utility to regenerate the JS module and added a postinstall script which parses the config file.

Then I started wondering if I was over-engineering this library, considering it's bound to be a relatively small aspect in its users' application. I started wondering if it even really warranted a completely separate config file and all the logic associated with parsing that for the browser. In general, would a simple withCustomConfig function actually be preferred/more-standard, or would an rc file be preferred by most people in this use case?


问:
Trying to download h5py, could not build wheels
I am trying to download the h5py package on windows. I am trying to install it with the pip command using a git bash terminal.

I have made sure to have python and some other things to my PATH/Environment Variables. I tried redownloading vscode, and python, tried to update pip and some other commands from this link: https://bobbyhadz.com/blog/python-failed-building-wheel-for-h5py . I was able to succesfully download h5py on my mac, I was wondering if anyone could explain the difference too.

```<code></code>```
```<code>  Loading library to get build settings and version: hdf5.dll
  error: Unable to load dependency HDF5, make sure HDF5 is installed properly
  error: Could not find module 'hdf5.dll' (or one of its dependencies). Try using the full path with constructor syntax.
  [end of output]
</code>```

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for h5py
Failed to build h5py
ERROR: Could not build wheels for h5py, which is required to install pyproject.toml-based projects

```<code>
</code>```

Body:
I am trying to download the h5py package on windows. I am trying to install it with the pip command using a git bash terminal.

I have made sure to have python and some other things to my PATH/Environment Variables. I tried redownloading vscode, and python, tried to update pip and some other commands from this link: https://bobbyhadz.com/blog/python-failed-building-wheel-for-h5py . I was able to succesfully download h5py on my mac, I was wondering if anyone could explain the difference too.

  Loading library to get build settings and version: hdf5.dll
  error: Unable to load dependency HDF5, make sure HDF5 is installed properly
  error: Could not find module 'hdf5.dll' (or one of its dependencies). Try using the full path with constructor syntax.
  [end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for h5py
Failed to build h5py
ERROR: Could not build wheels for h5py, which is required to install pyproject.toml-based projects


问:
After tomcat is deployed, an error occurs when the foreground returns to the page
After tomcat is deployed, an error occurs when the foreground returns to the page
Let's take a look at the details

enter image description here
enter image description here

```<code><div class="app" style="margin: 10px">
    <label class="title">图书信息修改</label>

    <sql:query dataSource="${snapshot}" var="bookre">
        SELECT * from `books_type`;
    </sql:query>

    <form class="input-box" action="/BookUpdateProceServlet" method="get">
        <%
            String id = request.getParameter("id");

            BookService bookService = new BookService();
            Book book = bookService.queryBook(id);

            out.print("<input type=\"text\" name=\"bookIdUpdate\" value=\"" + book.getBookId() + "\" style=\"display:none\" />");
            out.print("<input type=\"text\" name=\"bookNameUpdate\" class=\"table-add-text form-control text-flag\" placeholder=\"图书名称\" value=\"" + book.getBookName() + "\"/>");
            out.print("<input type=\"text\" name=\"bookAuthorUpdate\" class=\"table-add-text form-control text-flag\" placeholder=\"图书作者\" value=\"" + book.getBookAuthor() + "\"/>");
            out.print("<input type=\"text\" name=\"bookPriceNameUpdate\" class=\"table-add-text form-control text-flag\" placeholder=\"图书价格\" value=\"" + book.getBookPrice() + "\"/>");
        %>
</code>```

An error occurred while modifying the data。
I hope he can run without errors, but I have been debugging for a long time without success

Body:
After tomcat is deployed, an error occurs when the foreground returns to the page
Let's take a look at the details

enter image description here
enter image description here

    图书信息修改

    <sql:query dataSource="${snapshot}" var="bookre">
        SELECT * from `books_type`;
    </sql:query>

    <form class="input-box" action="/BookUpdateProceServlet" method="get">
        <%
            String id = request.getParameter("id");

            BookService bookService = new BookService();
            Book book = bookService.queryBook(id);

            out.print("<input type=\"text\" name=\"bookIdUpdate\" value=\"" + book.getBookId() + "\" style=\"display:none\" />");
            out.print("<input type=\"text\" name=\"bookNameUpdate\" class=\"table-add-text form-control text-flag\" placeholder=\"图书名称\" value=\"" + book.getBookName() + "\"/>");
            out.print("<input type=\"text\" name=\"bookAuthorUpdate\" class=\"table-add-text form-control text-flag\" placeholder=\"图书作者\" value=\"" + book.getBookAuthor() + "\"/>");
            out.print("<input type=\"text\" name=\"bookPriceNameUpdate\" class=\"table-add-text form-control text-flag\" placeholder=\"图书价格\" value=\"" + book.getBookPrice() + "\"/>");
        %>

An error occurred while modifying the data。
I hope he can run without errors, but I have been debugging for a long time without success


问:
How can I limit a series of PS outputs to a log file so that the log doesn't exceed a given character count & continues to a new log file?
I'm working with a PS script that has over 100 instances of writing a log for a given step of the script to a log file, and I've now been tasked with getting all those log outputs pushed into Windows Event Logs. The issue is, I don't want to go through by hand and write individual Write-EventLog lines for each write to the log file, I don't know which log writes are most critical to the script, and trying to write the whole log file directly to the Event Log isn't feasible since the log file wildly exceeds the character limit for Windows Event Logs.

With all that said, how would I change the following log function to stop writing to the current log file when it hits a given character limit, and begin writing to a new file with a number added to the original log file's filename?

Example of logging script:

```<code>$vScrLogFile = ((Get-Item $PSCommandPath).FullName).Replace((Get-Item $PSCommandPath).Name,"logs\$((Get-Item $PSCommandPath).Basename).$(get-date -Format "MM.dd.yyyy").log.txt")

Function Log_Info {
    # Define parameters
    param(
        [Parameter(Mandatory=$true, Position=0)][string]$vLogInfo,
        [Parameter(Mandatory=$true, Position=1)][int]$vLogFlag = 1,
        [Parameter(Mandatory=$false, Position=2)][string]$vLogFile,
        [Parameter(Mandatory=$false, Position=3)][string]$vConsoleColor
    )

    # If flag value = 1 then log to screen only.
    # If flag value = 2 then log to file only.
    # If flag value = 3 then log to file and screen.
    If($vLogFlag -eq 1 -OR $vLogFlag -eq 3){
        # Log to screen
        if ($vConsoleColor -eq $null -or $vConsoleColor -eq "") {$vConsoleColor = "green"}
        Write-Host "$vLogInfo" -ForegroundColor $vConsoleColor
        #Write-Host "$vLogInfo`n" -ForegroundColor green
    }

    If($vLogFlag -eq 2 -OR $vLogFlag -eq 3){
        # Log to file
        if (-not [string]::IsNullOrWhiteSpace($vLogFile)){
            Add-Content $vLogFile $vLogInfo
        }
    }
}

Log_Info -vLogInfo "This is a test log entry." -vLogFlag 3 -vLogFile $vScrLogFile
</code>```

This is not my script, but I'd like to keep the end result looking close to this for documentation reasons.

I've tried looking for anything similar to this, but might just be wording it poorly since the closest I got was this guy's question, and he wanted just one rotating log file while I need multiple numbered copies once the file hits the character maximum.

Body:
I'm working with a PS script that has over 100 instances of writing a log for a given step of the script to a log file, and I've now been tasked with getting all those log outputs pushed into Windows Event Logs. The issue is, I don't want to go through by hand and write individual Write-EventLog lines for each write to the log file, I don't know which log writes are most critical to the script, and trying to write the whole log file directly to the Event Log isn't feasible since the log file wildly exceeds the character limit for Windows Event Logs.

With all that said, how would I change the following log function to stop writing to the current log file when it hits a given character limit, and begin writing to a new file with a number added to the original log file's filename?

Example of logging script:

$vScrLogFile = ((Get-Item $PSCommandPath).FullName).Replace((Get-Item $PSCommandPath).Name,"logs\$((Get-Item $PSCommandPath).Basename).$(get-date -Format "MM.dd.yyyy").log.txt")

Function Log_Info {
    # Define parameters
    param(
        [Parameter(Mandatory=$true, Position=0)][string]$vLogInfo,
        [Parameter(Mandatory=$true, Position=1)][int]$vLogFlag = 1,
        [Parameter(Mandatory=$false, Position=2)][string]$vLogFile,
        [Parameter(Mandatory=$false, Position=3)][string]$vConsoleColor
    )

    # If flag value = 1 then log to screen only.
    # If flag value = 2 then log to file only.
    # If flag value = 3 then log to file and screen.
    If($vLogFlag -eq 1 -OR $vLogFlag -eq 3){
        # Log to screen
        if ($vConsoleColor -eq $null -or $vConsoleColor -eq "") {$vConsoleColor = "green"}
        Write-Host "$vLogInfo" -ForegroundColor $vConsoleColor
        #Write-Host "$vLogInfo`n" -ForegroundColor green
    }

    If($vLogFlag -eq 2 -OR $vLogFlag -eq 3){
        # Log to file
        if (-not [string]::IsNullOrWhiteSpace($vLogFile)){
            Add-Content $vLogFile $vLogInfo
        }
    }
}

Log_Info -vLogInfo "This is a test log entry." -vLogFlag 3 -vLogFile $vScrLogFile

This is not my script, but I'd like to keep the end result looking close to this for documentation reasons.

I've tried looking for anything similar to this, but might just be wording it poorly since the closest I got was this guy's question, and he wanted just one rotating log file while I need multiple numbered copies once the file hits the character maximum.


问:
C# Regex is matching only one of two groups
I have a list that contains with entries that will be in 1 of the 3 formats:

```<code>Test Section - Main Series -
Test 2 Section - Test Section - Main Seris
Main Series -  -
</code>```

I am try to use a RegEX to remove the training - from the lines. I came up with the following code to try and do it and it kind of works. It removed the double instance of dashes in the third format, leaves the second format alone, but ti does not remove the single instance of the dash in the first format.

```<code>        foreach (var item in menuItems)
        {
            item.NameWithParents = Regex.Replace(item.NameWithParents, @"(\s-\s\s-\s)|(\s-\s[^a-zA-Z])", "").ToString();
        }}
</code>```

I had thought the first group would make it remove the double dash while the second group would remove the single dash but it is not. The output I get is:

```<code>Test Section - Main Series -
Test 2 Section - Test Section - Main Seris
Main Series
</code>```

Why is the single instance not being removed?

Body:
I have a list that contains with entries that will be in 1 of the 3 formats:

Test Section - Main Series -
Test 2 Section - Test Section - Main Seris
Main Series -  -

I am try to use a RegEX to remove the training - from the lines. I came up with the following code to try and do it and it kind of works. It removed the double instance of dashes in the third format, leaves the second format alone, but ti does not remove the single instance of the dash in the first format.

        foreach (var item in menuItems)
        {
            item.NameWithParents = Regex.Replace(item.NameWithParents, @"(\s-\s\s-\s)|(\s-\s[^a-zA-Z])", "").ToString();
        }}

I had thought the first group would make it remove the double dash while the second group would remove the single dash but it is not. The output I get is:

Test Section - Main Series -
Test 2 Section - Test Section - Main Seris
Main Series

Why is the single instance not being removed?


问:
Loop through a list to find values that are present in a dataframe
I’m attempting to perform a loop in a list to check if any item is present on specific row of a dataframe if so then a new column is created on the dataframe with the item matched in the list and row.
In case my logic isn't clear, what I want is basically to extract the brand and model from a given column with the products description. I apologize if this question is trivial.

I tried running it through two methods, one using a lambda and regex function and the other with a simple loop.
The problem with the method using regex is that the loop does not return the third string "Ti" or "Super".

The problem with the method using a simple loop is when in the dataframe row there are, for example, the models "Ti" or "Super" because there are "RTX 3060" and "RTX 3060 Ti" as well on the list.

I can imagine that the problem lies in the fact that my list contains both "RTX 3060" and "RTX 3060 Ti" items. So in the case of logic using the regex method when the first item in the list satisfies the condition then it returns the corresponding string. In the case of the second method it is the same problem, however both items that satisfy the condition are returned.

Method 1:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
import pandas as pd
import datetime as dt
import os
import time
from numpy import loadtxt
import numpy as np
import re

df = pd.read_csv("./tables/KABUM - VGA_NVIDIA 20221205.csv",index_col=0)

class header:

    txt_brands = open("./lists/list_brands_vga_nvidia.txt","r")
    txt_models = open("./lists/list_models_vga.txt","r")
    txt_lines = open("./lists/list_lines_vga.txt","r")

    list_brands = txt_brands.read().splitlines()
    list_models = txt_models.read().splitlines()
    list_lines = txt_lines.read().splitlines()

    pattern_brands= '|'.join(list_brands)
    pattern_model = '|'.join(list_models)
    pattern_line = '|'.join(list_lines)

    df_nvidia = pd.read_csv('./tables/KABUM - VGA_NVIDIA 20221205.csv')

headers = header()

def model_searcher(search_str:str,search_list:str):
    search_obj = re.search(search_list,search_str,re.IGNORECASE)

    if search_obj:
        return_str = search_str[search_obj.start():search_obj.end()]
    else:
        return_str = 'NA'
    return return_str

df['Fabricante'] = df['Produto'].apply(lambda x:model_searcher(search_str=x,search_list=getattr(headers,'pattern_brands')))
df['Modelo'] = df['Produto'].apply(lambda x:model_searcher(search_str=x,search_list=getattr(headers,'pattern_model')))
df['Linha'] = df['Produto'].apply(lambda x:model_searcher(search_str=x,search_list=getattr(headers,'pattern_line')))

df['Modelo'] = df['Modelo'].str.cat(df['Linha'],sep=' ')
</code>```

Method2:

```<code>import pandas as pd
import re

list_brands = open('./lists/list_models_nvidia.txt','r')
df = pd.read_csv('./tables/KABUM - VGA_NVIDIA 20221206.csv',index_col=0)
df['Produto'] = df['Produto'].str.upper()

brands = list_brands.read().splitlines()

tmp = []

for produto in df['Produto']:
    x = [brand.upper() for brand in brands if brand.upper() in produto]
    tmp.append(x)

df['Marca'] = tmp
df.drop_duplicates(subset=['Marca'])

df.to_csv("./tests/Test01 - loop brands.csv",encoding="utf-8")
</code>```

I'll leave the github repository in case it's helpful, again I apologize for the trivial question.

Body:
I’m attempting to perform a loop in a list to check if any item is present on specific row of a dataframe if so then a new column is created on the dataframe with the item matched in the list and row.
In case my logic isn't clear, what I want is basically to extract the brand and model from a given column with the products description. I apologize if this question is trivial.

I tried running it through two methods, one using a lambda and regex function and the other with a simple loop.
The problem with the method using regex is that the loop does not return the third string "Ti" or "Super".

The problem with the method using a simple loop is when in the dataframe row there are, for example, the models "Ti" or "Super" because there are "RTX 3060" and "RTX 3060 Ti" as well on the list.

I can imagine that the problem lies in the fact that my list contains both "RTX 3060" and "RTX 3060 Ti" items. So in the case of logic using the regex method when the first item in the list satisfies the condition then it returns the corresponding string. In the case of the second method it is the same problem, however both items that satisfy the condition are returned.

Method 1:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
import pandas as pd
import datetime as dt
import os
import time
from numpy import loadtxt
import numpy as np
import re

df = pd.read_csv("./tables/KABUM - VGA_NVIDIA 20221205.csv",index_col=0)

class header:

    txt_brands = open("./lists/list_brands_vga_nvidia.txt","r")
    txt_models = open("./lists/list_models_vga.txt","r")
    txt_lines = open("./lists/list_lines_vga.txt","r")

    list_brands = txt_brands.read().splitlines()
    list_models = txt_models.read().splitlines()
    list_lines = txt_lines.read().splitlines()

    pattern_brands= '|'.join(list_brands)
    pattern_model = '|'.join(list_models)
    pattern_line = '|'.join(list_lines)

    df_nvidia = pd.read_csv('./tables/KABUM - VGA_NVIDIA 20221205.csv')

headers = header()

def model_searcher(search_str:str,search_list:str):
    search_obj = re.search(search_list,search_str,re.IGNORECASE)

    if search_obj:
        return_str = search_str[search_obj.start():search_obj.end()]
    else:
        return_str = 'NA'
    return return_str

df['Fabricante'] = df['Produto'].apply(lambda x:model_searcher(search_str=x,search_list=getattr(headers,'pattern_brands')))
df['Modelo'] = df['Produto'].apply(lambda x:model_searcher(search_str=x,search_list=getattr(headers,'pattern_model')))
df['Linha'] = df['Produto'].apply(lambda x:model_searcher(search_str=x,search_list=getattr(headers,'pattern_line')))

df['Modelo'] = df['Modelo'].str.cat(df['Linha'],sep=' ')

Method2:

import pandas as pd
import re

list_brands = open('./lists/list_models_nvidia.txt','r')
df = pd.read_csv('./tables/KABUM - VGA_NVIDIA 20221206.csv',index_col=0)
df['Produto'] = df['Produto'].str.upper()

brands = list_brands.read().splitlines()

tmp = []

for produto in df['Produto']:
    x = [brand.upper() for brand in brands if brand.upper() in produto]
    tmp.append(x)

df['Marca'] = tmp
df.drop_duplicates(subset=['Marca'])

df.to_csv("./tests/Test01 - loop brands.csv",encoding="utf-8")

I'll leave the github repository in case it's helpful, again I apologize for the trivial question.


问:
How to pass options to babel plugin transform-modules-commonjs?
I create a Vue 2 project by Vue-Cli 5, then I want to remove "use strick" in the complied code.

As I Know, the @babel/plugin-transform-strick-mode may be enabled via @babel/plugin-transform-modules-commonjs, and the plugin is included in @babel/preset-env under the modules option.

But the Vue-Cli used a preset @vue/babel-preset-app by a plugin @vue/cli-plugin-babel for babel.

So my question is How pass strictMode: false as an option to the transform-modules-commonjs by @vue/babel-preset-app which preset is in the @vue/cli-plugin-babel ?

module.exports = {
  presets: [["@vue/cli-plugin-babel/preset", { modules: "auto" }]],
  plugins: [
    // I tried this way, but it throw many errors like:
    /**
ERROR in ./node_modules/axios/dist/node/axios.cjs 11:15-32
Module not found: Error: Can't resolve 'stream' in 'D:\workspace\cqset_offical_website\node_modules\axios\dist\node'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }
     */
    ["@babel/plugin-transform-modules-commonjs", {}],
    [
      "component",
      {
        libraryName: "element-ui",
        styleLibraryName: "theme-chalk",
      },
    ],
  ],
};

```


问:
multiple inclusion of helm dependency
Helm Chart A is a library chart and defines a template function f1

Chart B adds A as a dependency

Chart C adds both A and B as dependencies.

Requirement here is that App B can be deployed by itself, but App C needs B to be deployed as well.

Now A.tgz is present in C/charts as well as in B/charts directory.

In such case I have noticed that template function f1 from C/charts/A.tgz gets executed.

Are there any best practices for this situation?

Title: multiple inclusion of helm dependency


问:
Is there a way to make separate dataframes from one dataframe?
I have a dataframe containing stock prices from different dates ranging from 2017 to 2022. The dates are set as the index and they are formatted as YYYY-MM-DD. I'm trying to create separate dataframes for each year. Is there a way I can filter my data to do so?

I am new to python and am not sure of how to do this. I tried to use .iloc to pick the specific year I wanted, but it didn't work since the dates are formatted as YYY-MM-DD.


问:
explicit many to many self-relations produces weird results in the generated client, pairing up wrong values
I've got users and contact requests with a table in between to explicitly define a self relation for cascade purposes.

user schema:

```<code>  contactRequestsReceivedFrom ContactRequestRelations[] @relation("contactRequestReceivedFrom")
  contactRequestsMadeTo       ContactRequestRelations[] @relation("contactRequestMadeTo")
</code>```

relations schema:

```<code>
model ContactRequestRelations {
  contactRequestReceivedFrom User   @relation("contactRequestReceivedFrom", fields: [requestReceivedFromId], references: [id], onDelete: Cascade)
  contactRequestMadeTo       User   @relation("contactRequestMadeTo", fields: [requestMadeToId], references: [id], onDelete: Cascade)
  requestReceivedFromId      String
  requestMadeToId            String

  @@id([requestReceivedFromId, requestMadeToId])
}
</code>```

• I have to give the relations a name, prisma will complain it's too ambiguous otherwise
• if I give the same relation reference on all 4 of them, prisma will complain of "wrongly named relation detected"

I wanted to make a 'send contact request' operation.

Where I find either the user that the request is made for and then add the relation to the 'contactRequestsReceivedFromarray ---- or ---- find the user that is sending the request and create a relation on thecontactRequestsMadeTo`.

The issue is, even though the relation   contactRequestsReceivedFrom ContactRequestRelations[] @relation("contactRequestReceivedFrom") on the user is clearly paired with the contactRequestReceivedFrom User   @relation("contactRequestReceivedFrom", fields: [requestReceivedFromId], references: [id], onDelete: Cascade) relation on the relation table, when I attempt to create this with the client, prisma only lets me define the opposite of that relation which is rather redundant and confusing:

as it would serve no purpose to define in that context, as I would be defining who made the request.

Is this the correct pattern/syntax, or should I be looking at a more complex model with a couple more tables in between? Not a big fan of that option.

Body:
I've got users and contact requests with a table in between to explicitly define a self relation for cascade purposes.

user schema:

  contactRequestsReceivedFrom ContactRequestRelations[] @relation("contactRequestReceivedFrom")
  contactRequestsMadeTo       ContactRequestRelations[] @relation("contactRequestMadeTo")

relations schema:

model ContactRequestRelations {
  contactRequestReceivedFrom User   @relation("contactRequestReceivedFrom", fields: [requestReceivedFromId], references: [id], onDelete: Cascade)
  contactRequestMadeTo       User   @relation("contactRequestMadeTo", fields: [requestMadeToId], references: [id], onDelete: Cascade)
  requestReceivedFromId      String
  requestMadeToId            String

  @@id([requestReceivedFromId, requestMadeToId])
}

• I have to give the relations a name, prisma will complain it's too ambiguous otherwise
• if I give the same relation reference on all 4 of them, prisma will complain of "wrongly named relation detected"

I wanted to make a 'send contact request' operation.

Where I find either the user that the request is made for and then add the relation to the 'contactRequestsReceivedFromarray ---- or ---- find the user that is sending the request and create a relation on thecontactRequestsMadeTo`.

The issue is, even though the relation   contactRequestsReceivedFrom ContactRequestRelations[] @relation("contactRequestReceivedFrom") on the user is clearly paired with the contactRequestReceivedFrom User   @relation("contactRequestReceivedFrom", fields: [requestReceivedFromId], references: [id], onDelete: Cascade) relation on the relation table, when I attempt to create this with the client, prisma only lets me define the opposite of that relation which is rather redundant and confusing:

as it would serve no purpose to define in that context, as I would be defining who made the request.

Is this the correct pattern/syntax, or should I be looking at a more complex model with a couple more tables in between? Not a big fan of that option.


问:
How to alert when unload page while checking whether each element is changed or not
I developed page in which multiple input and textarea exist.
I would like to set unload event to prevent what we inputed are not inserted.

To set this,I also add checking whether each input elements are changed.

If text are changed. I would like to set this alert system.
while these texts are not changed, we can easily leave page and unload event will not be fired.

I have tried following . I would like to combile window.addEventListener('beforeunload') and window.addEventListener('load'). are there any good ways to achieve this?

My point is how to handle beforeUnloadAlert variables..

Thanks

window.addEventListener('beforeunload', function(e) {
    e.returnValue = 'Are you sure you want to exit?';
}, false);

window.addEventListener('load', function (e) {
    let beforeUnloadAlert = true;
    var inputs = document.querySelectorAll('.inputForm');

    for (var i = inputs.length - 1; i >= 0; i--) {
        inputs[i].addEventListener('change', displayName);
    }

    function displayName(e) {
        console.log(this);
        beforeUnloadAlert = false;
    }
    return beforeUnloadAlert
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class='inputForm'>
<input class='inputForm'>
<input class='inputForm'>
<input class='inputForm'></code>```

Body:
I developed page in which multiple input and textarea exist.
I would like to set unload event to prevent what we inputed are not inserted.

To set this,I also add checking whether each input elements are changed.

If text are changed. I would like to set this alert system.
while these texts are not changed, we can easily leave page and unload event will not be fired.

I have tried following . I would like to combile window.addEventListener('beforeunload') and window.addEventListener('load'). are there any good ways to achieve this?

My point is how to handle beforeUnloadAlert variables..

Thanks

window.addEventListener('beforeunload', function(e) {
    e.returnValue = 'Are you sure you want to exit?';
}, false);

window.addEventListener('load', function (e) {
    let beforeUnloadAlert = true;
    var inputs = document.querySelectorAll('.inputForm');

    for (var i = inputs.length - 1; i >= 0; i--) {
        inputs[i].addEventListener('change', displayName);
    }

    function displayName(e) {
        console.log(this);
        beforeUnloadAlert = false;
    }
    return beforeUnloadAlert
});

<input class='inputForm'>
<input class='inputForm'>
<input class='inputForm'>
<input class='inputForm'>


问:
ClientContext Does not Contain a Definition for AuthenticationMode
I had a script that worked earlier today, but when I restarted my machine I now get ClientContext does not contain an definition for 'AuthenticationMode'. I have tried reinstalling the Nuget Packages. I have tried restarting my machine, no luck. I have another project that uses the same clientContext.AuthenticationMode, and also works fine. How do I fix this reference issue?

ClientContext.Credentials works but ClientContex.AuthenticationMode does not.

```<code>public void GetSharePointSite()
{
    string sharepointURL = $@"https://mySharepointSite";

    using (ClientContext clientContext = new ClientContext(sharepointURL))
    {
        clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
        clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;

        //load subsites and their titles
        Web web = clientContext.Web;
        clientContext.Load(web);
        clientContext.ExecuteQuery();

        Console.WriteLine(Convert.ToString(web.Title));
    }
}
</code>```

}

Body:
I had a script that worked earlier today, but when I restarted my machine I now get ClientContext does not contain an definition for 'AuthenticationMode'. I have tried reinstalling the Nuget Packages. I have tried restarting my machine, no luck. I have another project that uses the same clientContext.AuthenticationMode, and also works fine. How do I fix this reference issue?

ClientContext.Credentials works but ClientContex.AuthenticationMode does not.

public void GetSharePointSite()
{
    string sharepointURL = $@"https://mySharepointSite";

    using (ClientContext clientContext = new ClientContext(sharepointURL))
    {
        clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
        clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;

        //load subsites and their titles
        Web web = clientContext.Web;
        clientContext.Load(web);
        clientContext.ExecuteQuery();

        Console.WriteLine(Convert.ToString(web.Title));
    }
}

}


问:
Regex to repair malformed XML attributes, removing spaces in tags
I've been unfortunate to have come accross alot of malformed XML.

I cannot get the correct regex to remove 2 spaces inside the attribute/key.

My current regex also checks to see if there is a valid "=" attribute.

XML attributes have to have a value or / and just one key.

for example

```<code><ImValid></ImValid>
<Im not Valid></Im not Valid>
<ImValid with="somthing"></ImValid>
</code>```

Here is my malformed XML:

```<code><Addresses>
  <Address>
    <Delivery id>123123</Delivery id>
    <Delivery Code Id>123123</Delivery Code Id>
    <Full Name>Agent Smith</Full Name>
  </Address>
  <Address>
    <Delivery id>12322123</Delivery id>
    <Delivery Code Id>12zz3123</Delivery Code Id>
    <Full Name>Mr Anderson</Full Name>
  </Address>
<Addresses>
</code>```

I'm trying to repair it using regex.

```<code>AstringVar => Regex.Replace(AstringVar , @"(?=<[^=]+?>)(?=</?\w+\s+\w+)(<.*?)(\s+)(.*?>)", @"$1$3", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)
</code>```

This Will Change This

```<code><Full Name>Mr Anderson</Full Name>
</code>```

This

```<code><FullName>Mr Anderson</FullName>
</code>```

Improving  .. But also missing the last space..

```<code><DeliveryCode Id>12zz3123</DeliveryCode Id>
</code>```

Ok...i could run it twice ... but..
that seems ugly...
how would I be able to get both 1 space and 2 spaces whilst also avoiding the values
Thanks to any regex heros who can help ...!

Here it is on regex101https://regex101.com/r/dVs51I/3

Body:
I've been unfortunate to have come accross alot of malformed XML.

I cannot get the correct regex to remove 2 spaces inside the attribute/key.

My current regex also checks to see if there is a valid "=" attribute.

XML attributes have to have a value or / and just one key.

for example

<ImValid></ImValid>
<Im not Valid></Im not Valid>
<ImValid with="somthing"></ImValid>

Here is my malformed XML:

<Addresses>
  <Address>
    <Delivery id>123123</Delivery id>
    <Delivery Code Id>123123</Delivery Code Id>
    <Full Name>Agent Smith</Full Name>
  </Address>
  <Address>
    <Delivery id>12322123</Delivery id>
    <Delivery Code Id>12zz3123</Delivery Code Id>
    <Full Name>Mr Anderson</Full Name>
  </Address>
<Addresses>

I'm trying to repair it using regex.

AstringVar => Regex.Replace(AstringVar , @"(?=<[^=]+?>)(?=</?\w+\s+\w+)(<.*?)(\s+)(.*?>)", @"$1$3", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)

This Will Change This

<Full Name>Mr Anderson</Full Name>

This

<FullName>Mr Anderson</FullName>

Improving  .. But also missing the last space..

<DeliveryCode Id>12zz3123</DeliveryCode Id>

Ok...i could run it twice ... but..
that seems ugly...
how would I be able to get both 1 space and 2 spaces whilst also avoiding the values
Thanks to any regex heros who can help ...!

Here it is on regex101https://regex101.com/r/dVs51I/3


问:
Discord.Net | Why won't my last command register?
This is my program.cs file and obviously the token is actually in there.

```<code>using System;
using System.Reflection;
using System.Threading.Tasks;
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using IResult = Discord.Interactions.IResult;

namespace StorytimeBot.v2
{
    class Program
    {
        static void Main(string[] args) => new Program().RunBotAsync().GetAwaiter().GetResult();

        private DiscordSocketClient _client;
        private InteractionService _commands;
        private IServiceProvider _services;

        public async Task RunBotAsync()
        {
            _client = new DiscordSocketClient();
            _commands = new InteractionService(_client.Rest);

            _services = new ServiceCollection()
                .AddSingleton(_client)
                .AddSingleton(_commands)
                .BuildServiceProvider();

            string token = "xxxxxxx";

            _client.Log += _client_Log;

            await RegisterCommandsAsync();

            await _client.LoginAsync(TokenType.Bot, token);

            await _client.StartAsync();

            await Task.Delay(-1);
        }

        private Task _client_Log(LogMessage arg)
        {
            Console.WriteLine(arg);
            return Task.CompletedTask;
        }

        public async Task RegisterCommandsAsync()
        {
            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
            _client.InteractionCreated += HandleInteraction;
            _commands.SlashCommandExecuted += SlashCommandExecuted;
        }

        private Task SlashCommandExecuted(SlashCommandInfo arg1, IInteractionContext arg2, IResult arg3)
        {
            return Task.CompletedTask;
        }

        private async Task HandleInteraction(SocketInteraction arg)
        {
            try
            {
                // Create an execution context that matches the generic type parameter of your InteractionModuleBase<T> modules
                var ctx = new SocketInteractionContext(_client, arg);
                await _commands.ExecuteCommandAsync(ctx, _services);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                // If a Slash Command execution fails it is most likely that the original interaction acknowledgement will persist. It is a good idea to delete the original
                // response, or at least let the user know that something went wrong during the command execution.
                if (arg.Type == InteractionType.ApplicationCommand)
                    await arg.GetOriginalResponseAsync().ContinueWith(async (msg) => await msg.Result.DeleteAsync());
            }
        }
    }
}
</code>```

This is a snippet of my commands.cs file and the last command won't register since I added it days ago. My other commands got registered using the same code so I have no idea

```<code>public class Commands : InteractionModuleBase<SocketInteractionContext>
    {
</code>```
```<code>[SlashCommand("pointcalc", "Battle Point Calculator!")]
        public async Task PointCalc(int charisma, int wisdom, int intelligence, int armySizeDifference, int conscripts, int armsMen, int cavalry, int knights, bool beingSieged)
        {
            int armySizeAdv = (armySizeDifference % 20) * 1;
            double conscriptsP = conscripts * -.1;
            double armsMenP = armsMen * -.01;
            double cavalryP = cavalry * .1;
            double knightsP = knights * .25;
            int beingSiegedP = 0;
            if (beingSieged == true)
            {
                beingSiegedP = 5;
            }

            double battlePoints = charisma + wisdom + (intelligence * 2) + armySizeAdv + conscriptsP + armsMenP + cavalryP + knightsP + beingSiegedP;
            await RespondAsync($"{battlePoints}");
        }
</code>```

I'm just really lost on the whole thing not being synched up when my other commands synched instantly.

Body:
This is my program.cs file and obviously the token is actually in there.

using System;
using System.Reflection;
using System.Threading.Tasks;
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using IResult = Discord.Interactions.IResult;

namespace StorytimeBot.v2
{
    class Program
    {
        static void Main(string[] args) => new Program().RunBotAsync().GetAwaiter().GetResult();

        private DiscordSocketClient _client;
        private InteractionService _commands;
        private IServiceProvider _services;

        public async Task RunBotAsync()
        {
            _client = new DiscordSocketClient();
            _commands = new InteractionService(_client.Rest);

            _services = new ServiceCollection()
                .AddSingleton(_client)
                .AddSingleton(_commands)
                .BuildServiceProvider();

            string token = "xxxxxxx";

            _client.Log += _client_Log;

            await RegisterCommandsAsync();

            await _client.LoginAsync(TokenType.Bot, token);

            await _client.StartAsync();

            await Task.Delay(-1);
        }

        private Task _client_Log(LogMessage arg)
        {
            Console.WriteLine(arg);
            return Task.CompletedTask;
        }

        public async Task RegisterCommandsAsync()
        {
            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
            _client.InteractionCreated += HandleInteraction;
            _commands.SlashCommandExecuted += SlashCommandExecuted;
        }

        private Task SlashCommandExecuted(SlashCommandInfo arg1, IInteractionContext arg2, IResult arg3)
        {
            return Task.CompletedTask;
        }

        private async Task HandleInteraction(SocketInteraction arg)
        {
            try
            {
                // Create an execution context that matches the generic type parameter of your InteractionModuleBase<T> modules
                var ctx = new SocketInteractionContext(_client, arg);
                await _commands.ExecuteCommandAsync(ctx, _services);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                // If a Slash Command execution fails it is most likely that the original interaction acknowledgement will persist. It is a good idea to delete the original
                // response, or at least let the user know that something went wrong during the command execution.
                if (arg.Type == InteractionType.ApplicationCommand)
                    await arg.GetOriginalResponseAsync().ContinueWith(async (msg) => await msg.Result.DeleteAsync());
            }
        }
    }
}

This is a snippet of my commands.cs file and the last command won't register since I added it days ago. My other commands got registered using the same code so I have no idea

public class Commands : InteractionModuleBase<SocketInteractionContext>
    {

[SlashCommand("pointcalc", "Battle Point Calculator!")]
        public async Task PointCalc(int charisma, int wisdom, int intelligence, int armySizeDifference, int conscripts, int armsMen, int cavalry, int knights, bool beingSieged)
        {
            int armySizeAdv = (armySizeDifference % 20) * 1;
            double conscriptsP = conscripts * -.1;
            double armsMenP = armsMen * -.01;
            double cavalryP = cavalry * .1;
            double knightsP = knights * .25;
            int beingSiegedP = 0;
            if (beingSieged == true)
            {
                beingSiegedP = 5;
            }

            double battlePoints = charisma + wisdom + (intelligence * 2) + armySizeAdv + conscriptsP + armsMenP + cavalryP + knightsP + beingSiegedP;
            await RespondAsync($"{battlePoints}");
        }

I'm just really lost on the whole thing not being synched up when my other commands synched instantly.


问:
In Winform use SunnyUI and ScottPlot Rendering problems
The SunnyUI interface library in Winform is beautiful, and the ScottPlot chart library has good performance. However, if both are used in the same project, the SunnyUI interface rendering will be distorted. The authors on both sides said that please contact each other, not their own problems. Please consult the majority of netizens here. Both are open source, SunnyUI personal research is free, and I have obtained a commercial license; ScottPlot is a MIT license.

In Winform use SunnyUI and ScottPlot Rendering no problems


问:
How to show periodic report from queue in multiprocesssing process in Python
I am using multiprocessing package in Python to start a run in a subprocess to dedicate a thread for the run so that the rest of the threads on the machine can be used for heavy computation. While the process is running, I would like to show the progress. Is there a way to access the report which is updated during the heavy computation? Here is a small example to illustrate what I would like to achieve.

```<code>import multiprocessing as _mp
def compute_squared(queue):
    number_squared = 20
    report = {}
    def run(number_squared, report):
        for i in range(number_squared):
            j = i ** 2
            report[i] = i

    run(number_squared, report)
    queue.put({
        "report": report,
        "name": "compute squared"
    })

queue = _mp.Queue()
run_process = _mp.Process(
                    target=compute_squared,
                    args=(queue, ))
run_process.start()
while run_process.is_alive():
    continue

final_report = queue.get()["report"]
</code>```

While run_process.is_alive() I want to print the report from inside compute_squared so that I can trace the progress. I can access the final report using queue.get() but is there a way to access the intermediate reports?

Body:
I am using multiprocessing package in Python to start a run in a subprocess to dedicate a thread for the run so that the rest of the threads on the machine can be used for heavy computation. While the process is running, I would like to show the progress. Is there a way to access the report which is updated during the heavy computation? Here is a small example to illustrate what I would like to achieve.

import multiprocessing as _mp
def compute_squared(queue):
    number_squared = 20
    report = {}
    def run(number_squared, report):
        for i in range(number_squared):
            j = i ** 2
            report[i] = i

    run(number_squared, report)
    queue.put({
        "report": report,
        "name": "compute squared"
    })

queue = _mp.Queue()
run_process = _mp.Process(
                    target=compute_squared,
                    args=(queue, ))
run_process.start()
while run_process.is_alive():
    continue

final_report = queue.get()["report"]

While run_process.is_alive() I want to print the report from inside compute_squared so that I can trace the progress. I can access the final report using queue.get() but is there a way to access the intermediate reports?


问:
How to make JavaScript fetch request from a react app docker container to a Rails API docker container within the same network?
I have a couple of docker containers within a network. A container with a frontend react project and another container with a Rails API. I'm looking to make a request from the react project container to the Rails API but the fetch API continues to run into this error:

net::ERR_NAME_NOT_RESOLVED

React Code

```<code>function App() {

...
  async function apiRequest() {
    const options = {
      headers: myHeaders,
      method: requestMethod,
    }

    formData.append('username',username);
    formData.append('password',password);

    if (requestMethod === "POST") {
      options.body = formData
    }

    let requestStr = "http://user-api:3000/api/users/";
    let apiRequest = await fetch(requestStr, options)
    let data = await apiRequest.json()
    console.log(data)
  }
...
}

</code>```

Dockerfile Frontend (React app using Vite)

```<code>FROM node
WORKDIR /app
COPY package.json .
RUN npm i
COPY . .
EXPOSE 5000
CMD ["npm", "run", "dev"]
</code>```

Dockerfile Rails API

```<code>FROM ruby:2.7.1

ENV APP_HOME /rails-docker
# Installation of dependencies
RUN apt-get update -qq \
  && apt-get install -y \
      # Needed for certain gems
    build-essential \
         # Needed for postgres gem
    libpq-dev \
    # The following are used to trim down the size of the image by removing unneeded data
  && apt-get clean autoclean \
  && apt-get autoremove -y \
  && rm -rf \
    /var/lib/apt \
    /var/lib/dpkg \
    /var/lib/cache \
    /var/lib/log
# Create a directory for our application
# and set it as the working directory
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
# Add our Gemfile and install gems
ADD Gemfile* $APP_HOME/
RUN bundle install
# Copy over our application code
ADD . $APP_HOME
# Run our app
CMD RAILS_ENV=${RAILS_ENV} bundle exec rails db:create db:migrate db:seed && bundle exec rails s -p ${PORT} -b '0.0.0.0'
</code>```

Docker-compose.yml

```<code>version: '3.8'

services:
  db:
    container_name: movie-db
    image: postgres
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: mysecretpassword
    ports:
      - "5432:5432"
    volumes:
      - postgres:/var/lib/postgresql/data

  frontend:
    container_name: movie-dojo-frontend
    build: ./movie_dojo
    image: "josephse91/movie-dojo-frontend"
    ports:
      - "5000:5000"
  user-api:
    container_name: user-api
    build: ./user_api
    image: "josephse91/rails_api"
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -b '0.0.0.0'"
    volumes:
      - .:/Rails-Docker
    ports:
      - "3000:3000"
    depends_on:
      - db
    tty: true
    stdin_open: true

volumes:
  postgres:

networks:
  default:
    name: "movie-dojo-network"
</code>```

I've tried to place the rails API container name as the host within the fetch call but I haven't had any luck. Any advice?

Body:
I have a couple of docker containers within a network. A container with a frontend react project and another container with a Rails API. I'm looking to make a request from the react project container to the Rails API but the fetch API continues to run into this error:

net::ERR_NAME_NOT_RESOLVED

React Code

function App() {

...
  async function apiRequest() {
    const options = {
      headers: myHeaders,
      method: requestMethod,
    }

    formData.append('username',username);
    formData.append('password',password);

    if (requestMethod === "POST") {
      options.body = formData
    }

    let requestStr = "http://user-api:3000/api/users/";
    let apiRequest = await fetch(requestStr, options)
    let data = await apiRequest.json()
    console.log(data)
  }
...
}

Dockerfile Frontend (React app using Vite)

FROM node
WORKDIR /app
COPY package.json .
RUN npm i
COPY . .
EXPOSE 5000
CMD ["npm", "run", "dev"]

Dockerfile Rails API

FROM ruby:2.7.1

ENV APP_HOME /rails-docker
# Installation of dependencies
RUN apt-get update -qq \
  && apt-get install -y \
      # Needed for certain gems
    build-essential \
         # Needed for postgres gem
    libpq-dev \
    # The following are used to trim down the size of the image by removing unneeded data
  && apt-get clean autoclean \
  && apt-get autoremove -y \
  && rm -rf \
    /var/lib/apt \
    /var/lib/dpkg \
    /var/lib/cache \
    /var/lib/log
# Create a directory for our application
# and set it as the working directory
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
# Add our Gemfile and install gems
ADD Gemfile* $APP_HOME/
RUN bundle install
# Copy over our application code
ADD . $APP_HOME
# Run our app
CMD RAILS_ENV=${RAILS_ENV} bundle exec rails db:create db:migrate db:seed && bundle exec rails s -p ${PORT} -b '0.0.0.0'

Docker-compose.yml

version: '3.8'

services:
  db:
    container_name: movie-db
    image: postgres
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: mysecretpassword
    ports:
      - "5432:5432"
    volumes:
      - postgres:/var/lib/postgresql/data

  frontend:
    container_name: movie-dojo-frontend
    build: ./movie_dojo
    image: "josephse91/movie-dojo-frontend"
    ports:
      - "5000:5000"
  user-api:
    container_name: user-api
    build: ./user_api
    image: "josephse91/rails_api"
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -b '0.0.0.0'"
    volumes:
      - .:/Rails-Docker
    ports:
      - "3000:3000"
    depends_on:
      - db
    tty: true
    stdin_open: true

volumes:
  postgres:

networks:
  default:
    name: "movie-dojo-network"

I've tried to place the rails API container name as the host within the fetch call but I haven't had any luck. Any advice?


问:
create new SideOut and add sink to it at runtime
I have Flink DataStream job that flows like this:

before DataStream definition

define list of Kafka Topics

create Hashmap of string KafkaTopic -> SideOutput

define Kafka Source

during DataStream definition

add Kafka Source to env using fromSource

define Process function that pulls the kafka topic from the message metadata, looks up the SideOutput from the Hashmap of (string KafkaTopic -> SideOutput) and outputs the message to the output tag returned from the Hashmap

after DataStream definition

iterate over Hashmap of string KafkaTopic -> SideOutput

create JDBC sink with unique insert statement for each sideoutput

add a sink to each side OutputTag

I'd like to avoid building the list of KafkaTopics before defining the stream. I want to use the regex function of the KafkaSource to consume from all topics that match the pattern.

Is it possible to create new side Output tags and Sinks at runtime during the process function? If I encounter a new kafka topic create a sideoutput, add it to the stream, then add a new sink to the sideoutput?

The more I think about it, I assume this is not possible.

My alternative plan is to use a kafka connector and build a list of kafka topics in the 'before DataStream definition' step from above. In that case I would have to restart the job to consume from new topics.

I could have thousands of topics, which is why I want to dynamically define them.


问:
Error installing all R packages: not a macOS binary package
I am having an unprecedented error installing all R packages. I have uninstalled and reinstalled R and RStudio.

```<code>sh: tar: command not found
Warning in install.packages :
  error in running command
Warning in install.packages :
  'tar' returned non-zero exit code 127
Error in install.packages : file ‘/var/folders/sb/fll6frln7pqg42sztcn6z_4c0000gn/T//RtmpuMXPIZ/downloaded_packages/sys_3.4.1.tgz’ is not a macOS binary package
</code>```
```<code>platform       x86_64-apple-darwin17.0
arch           x86_64
os             darwin17.0
system         x86_64, darwin17.0
status
major          4
minor          2.2
year           2022
month          10
day            31
svn rev        83211
language       R
version.string R version 4.2.2 (2022-10-31)
nickname       Innocent and Trusting
</code>```

Body:
I am having an unprecedented error installing all R packages. I have uninstalled and reinstalled R and RStudio.

sh: tar: command not found
Warning in install.packages :
  error in running command
Warning in install.packages :
  'tar' returned non-zero exit code 127
Error in install.packages : file ‘/var/folders/sb/fll6frln7pqg42sztcn6z_4c0000gn/T//RtmpuMXPIZ/downloaded_packages/sys_3.4.1.tgz’ is not a macOS binary package

platform       x86_64-apple-darwin17.0
arch           x86_64
os             darwin17.0
system         x86_64, darwin17.0
status
major          4
minor          2.2
year           2022
month          10
day            31
svn rev        83211
language       R
version.string R version 4.2.2 (2022-10-31)
nickname       Innocent and Trusting


问:
Solving a large system of linear equations over the finite field F2
I have 10163 equations and 9000 unknowns, all over finite fields, like this style:

Of course my equation will be much larger than this, I have 10163 rows and 9000 different x.

Presented in the form of a matrix is AX=B. A is a 10163x9000 coefficient matrix and it may be sparse, X is a 9000x1 unknown vector, B is the result of their multiplication and mod 2.

Because of the large number of unknowns that need to be solved for, it can be time consuming. I'm looking for a faster way to solve this system of equations using C language.

I tried to use Gaussian elimination method to solve this equation, In order to make the elimination between rows more efficient, I store the matrix A in a 64-bit two-dimensional array, and let the last column of the array store the value of B, so that the XOR operation may reduce the calculating time.

The code I am using is as follows:

```<code>    uint8_t guss_x_main[R_BITS] = {0};
    uint64_t tmp_guss[guss_j_num];

    for(uint16_t guss_j = 0; guss_j < x_weight; guss_j++)
    {
      uint64_t mask_1    = 1;
      uint64_t mask_guss = (mask_1 << (guss_j % GUSS_BLOCK));
      uint16_t eq_j      = guss_j / GUSS_BLOCK;
      for(uint16_t guss_i = guss_j; guss_i < R_BITS; guss_i++)
      {
        if((mask_guss & equations_guss_byte[guss_i][eq_j]) != 0)
        {
          if(guss_x_main[guss_j] == 0)
          {
            guss_x_main[guss_j] = 1;
            for(uint16_t change_i = 0; change_i < guss_j_num; change_i++)
            {
              tmp_guss[change_i] = equations_guss_byte[guss_j][change_i];
              equations_guss_byte[guss_j][change_i] =
                  equations_guss_byte[guss_i][change_i];
              equations_guss_byte[guss_i][change_i] = tmp_guss[change_i];
            }
          }
          else
          {
            GUARD(xor_64(equations_guss_byte[guss_i], equations_guss_byte[guss_i],
                         equations_guss_byte[guss_j], guss_j_num));
          }
        }
      }
      for(uint16_t guss_i = 0; guss_i < guss_j; guss_i++)
      {
        if((mask_guss & equations_guss_byte[guss_i][eq_j]) != 0)
        {
          GUARD(xor_64(equations_guss_byte[guss_i], equations_guss_byte[guss_i],
                       equations_guss_byte[guss_j], guss_j_num));
        }
      }
    }
</code>```

R_BIT = 10163, x_weight = 9000, GUSS_BLOCK = 64, guss_j_num = x_weight / GUSS_BLOCK + 1; equations_guss_byte is a two-dimensional array of uint64, where x_weight / GUSS_BLOCK column stores the matrix A and the latter column stores the vector B, xor_64() is used to XOR two arrays, GUARD() is used to check the correctness of function operation.

Using this method takes about 8 seconds to run on my machine. Is there a better way to speed up the calculation?

Body:
I have 10163 equations and 9000 unknowns, all over finite fields, like this style:

Of course my equation will be much larger than this, I have 10163 rows and 9000 different x.

Presented in the form of a matrix is AX=B. A is a 10163x9000 coefficient matrix and it may be sparse, X is a 9000x1 unknown vector, B is the result of their multiplication and mod 2.

Because of the large number of unknowns that need to be solved for, it can be time consuming. I'm looking for a faster way to solve this system of equations using C language.

I tried to use Gaussian elimination method to solve this equation, In order to make the elimination between rows more efficient, I store the matrix A in a 64-bit two-dimensional array, and let the last column of the array store the value of B, so that the XOR operation may reduce the calculating time.

The code I am using is as follows:

    uint8_t guss_x_main[R_BITS] = {0};
    uint64_t tmp_guss[guss_j_num];

    for(uint16_t guss_j = 0; guss_j < x_weight; guss_j++)
    {
      uint64_t mask_1    = 1;
      uint64_t mask_guss = (mask_1 << (guss_j % GUSS_BLOCK));
      uint16_t eq_j      = guss_j / GUSS_BLOCK;
      for(uint16_t guss_i = guss_j; guss_i < R_BITS; guss_i++)
      {
        if((mask_guss & equations_guss_byte[guss_i][eq_j]) != 0)
        {
          if(guss_x_main[guss_j] == 0)
          {
            guss_x_main[guss_j] = 1;
            for(uint16_t change_i = 0; change_i < guss_j_num; change_i++)
            {
              tmp_guss[change_i] = equations_guss_byte[guss_j][change_i];
              equations_guss_byte[guss_j][change_i] =
                  equations_guss_byte[guss_i][change_i];
              equations_guss_byte[guss_i][change_i] = tmp_guss[change_i];
            }
          }
          else
          {
            GUARD(xor_64(equations_guss_byte[guss_i], equations_guss_byte[guss_i],
                         equations_guss_byte[guss_j], guss_j_num));
          }
        }
      }
      for(uint16_t guss_i = 0; guss_i < guss_j; guss_i++)
      {
        if((mask_guss & equations_guss_byte[guss_i][eq_j]) != 0)
        {
          GUARD(xor_64(equations_guss_byte[guss_i], equations_guss_byte[guss_i],
                       equations_guss_byte[guss_j], guss_j_num));
        }
      }
    }

R_BIT = 10163, x_weight = 9000, GUSS_BLOCK = 64, guss_j_num = x_weight / GUSS_BLOCK + 1; equations_guss_byte is a two-dimensional array of uint64, where x_weight / GUSS_BLOCK column stores the matrix A and the latter column stores the vector B, xor_64() is used to XOR two arrays, GUARD() is used to check the correctness of function operation.

Using this method takes about 8 seconds to run on my machine. Is there a better way to speed up the calculation?


问:
python error:IsADirectoryError: [Errno 21] Is a directory
I am trying to decompress a list of .xz file and save them in a single folder,my code is show below

```<code>import shutil
path = "/content/drive/MyDrive/dataset_demo/Posts/"
output_path = "/content/sample_data/output/"
os.chdir(path)

for file_com in os.listdir(path):
  if file_com.endswith('.xz'):
    with lzma.open(file_com,'rb') as input:
      with open(output_path,'wb') as output:
        shutil.copyfileobj(input, output)
</code>```

it noticed me that:"IsADirectoryError: [Errno 21] Is a directory: '/content/sample_data/output/'"
and I know the final aim should be a file but how could I save them in a folder

What should I do next, and thanks for your help and time.

Body:
I am trying to decompress a list of .xz file and save them in a single folder,my code is show below

import shutil
path = "/content/drive/MyDrive/dataset_demo/Posts/"
output_path = "/content/sample_data/output/"
os.chdir(path)

for file_com in os.listdir(path):
  if file_com.endswith('.xz'):
    with lzma.open(file_com,'rb') as input:
      with open(output_path,'wb') as output:
        shutil.copyfileobj(input, output)

it noticed me that:"IsADirectoryError: [Errno 21] Is a directory: '/content/sample_data/output/'"
and I know the final aim should be a file but how could I save them in a folder

What should I do next, and thanks for your help and time.


问:
Fetch API stream doesn't work on server but does locally
As I explained in a previous question I have a FastAPI endpoint that returns a StreamingResponse response that is then consumed by a React application using fetch().body.getReader() API.

The problem I'm facing appears when I open my React application, select the image (s) using Uppy and send it to my FastAPI endpoint, locally it works just fine and the images are returned as a stream response:

But when I deploy my application on Heroku or Render the rendered response is all broken:

Adding more context to my previous question I'm rendering the stream using an async generator:

async function* submit({data}) {
    const formData = new FormData()

    data?.current?.files?.successful.map(image =>
        formData.append('images', image.data)
    )

    formData.append('language', data.current.language.code)

    try {
        const response = await fetch(
            'endpoint',
            {
                method: 'POST',
                body: formData
            }
        )

        const reader = response.body.getReader()

        while (true) {
            const { value, done } = await reader.read()

            if (done) break

            const base64 = `data:${response.headers.get(
                'content-type'
            )};base64,${btoa(String.fromCharCode(...new Uint8Array(value)))}`

            yield base64
        }
    } catch (error) {
        // ...
    }
}
```
<p>That is called when the "Gallery" component in the screenshot is rendered:</p>
```const [images, setImages] = useState([])

    useEffect(() => {
        ;(async () => {
            for await (const image of await translateSubmit({
                data
            })) {
                setImages(previous => [...previous, image])
            }
        })()

        // eslint-disable-next-line
    }, [])
```

I was expecting to get the same result in the server when the application is deployed, but it just doesn't work as it should and I'm not sure how to approach the problem. Any tips?

Body:
As I explained in a previous question I have a FastAPI endpoint that returns a StreamingResponse response that is then consumed by a React application using fetch().body.getReader() API.

The problem I'm facing appears when I open my React application, select the image (s) using Uppy and send it to my FastAPI endpoint, locally it works just fine and the images are returned as a stream response:

But when I deploy my application on Heroku or Render the rendered response is all broken:

Adding more context to my previous question I'm rendering the stream using an async generator:

async function* submit({data}) {
    const formData = new FormData()

    data?.current?.files?.successful.map(image =>
        formData.append('images', image.data)
    )

    formData.append('language', data.current.language.code)

    try {
        const response = await fetch(
            'endpoint',
            {
                method: 'POST',
                body: formData
            }
        )

        const reader = response.body.getReader()

        while (true) {
            const { value, done } = await reader.read()

            if (done) break

            const base64 = `data:${response.headers.get(
                'content-type'
            )};base64,${btoa(String.fromCharCode(...new Uint8Array(value)))}`

            yield base64
        }
    } catch (error) {
        // ...
    }
}

That is called when the "Gallery" component in the screenshot is rendered:

const [images, setImages] = useState([])

    useEffect(() => {
        ;(async () => {
            for await (const image of await translateSubmit({
                data
            })) {
                setImages(previous => [...previous, image])
            }
        })()

        // eslint-disable-next-line
    }, [])

I was expecting to get the same result in the server when the application is deployed, but it just doesn't work as it should and I'm not sure how to approach the problem. Any tips?


问:
windows container open ppt failed
container: mcr.microsoft.com/windows:1809

use odt to install office365 in container.

then use this command to open ppt with no response(open function not return)

$Powerpoint = New-Object -ComObject powerpoint.application

$ppt = $Powerpoint.presentations.open("c:\2.pptx", $TRUE, $FALSE)

dockerfile:

```<code>FROM mcr.microsoft.com/windows:1809
WORKDIR C:\\
RUN mkdir c:\\install
COPY .\\office2019 c:\\install\\office2019\\
WORKDIR c:\\install\\office2019
RUN mkdir C:\\Windows\\SysWOW64\\config\\systemprofile\\Desktop
RUN mkdir C:\\Windows\\system32\\config\\systemprofile\\Desktop
RUN C:\\install\\office2019\\setup.exe /configure C:\\install\\office2019\\config.xml
</code>```

config.xml:

```<code><Configuration>
  <Logging Level ="Standard" Path ="c:\\install\\logs" Template ="RI-O365NEW.log.txt"/>
  <Add OfficeClientEdition="32">
    <Product ID="O365ProPlusRetail">
      <Language ID="en-us" />
      <ExcludeApp ID="Excel" />
      <ExcludeApp ID="Groove" />
      <ExcludeApp ID="OneDrive" />
      <ExcludeApp ID="OneNote" />
      <ExcludeApp ID="Outlook" />
      <ExcludeApp ID="Publisher" />
      <ExcludeApp ID="Word" />
    </Product>
  </Add>

  <!--  <RemoveMSI All="True" /> -->

  <Display Level="None" AcceptEULA="TRUE" />

  <!--  <Property Name="AUTOACTIVATE" Value="1" />  -->

</Configuration>

</code>```

some test:

1.ppt delete object action is work
enter image description here

2.use mcr.microsoft.com/windows/server:ltsc2022 is work

3.use office 2019, install failed

how to make it to work with mcr.microsoft.com/windows:1809 and object action?
or how to get the error?

Title: windows container open ppt failed

Body:
container: mcr.microsoft.com/windows:1809

use odt to install office365 in container.

then use this command to open ppt with no response(open function not return)

$Powerpoint = New-Object -ComObject powerpoint.application

$ppt = $Powerpoint.presentations.open("c:\2.pptx", $TRUE, $FALSE)

dockerfile:

FROM mcr.microsoft.com/windows:1809
WORKDIR C:\\
RUN mkdir c:\\install
COPY .\\office2019 c:\\install\\office2019\\
WORKDIR c:\\install\\office2019
RUN mkdir C:\\Windows\\SysWOW64\\config\\systemprofile\\Desktop
RUN mkdir C:\\Windows\\system32\\config\\systemprofile\\Desktop
RUN C:\\install\\office2019\\setup.exe /configure C:\\install\\office2019\\config.xml

config.xml:

<Configuration>
  <Logging Level ="Standard" Path ="c:\\install\\logs" Template ="RI-O365NEW.log.txt"/>
  <Add OfficeClientEdition="32">
    <Product ID="O365ProPlusRetail">
      <Language ID="en-us" />
      <ExcludeApp ID="Excel" />
      <ExcludeApp ID="Groove" />
      <ExcludeApp ID="OneDrive" />
      <ExcludeApp ID="OneNote" />
      <ExcludeApp ID="Outlook" />
      <ExcludeApp ID="Publisher" />
      <ExcludeApp ID="Word" />
    </Product>
  </Add>

  <Display Level="None" AcceptEULA="TRUE" />

</Configuration>

some test:

1.ppt delete object action is work
enter image description here

2.use mcr.microsoft.com/windows/server:ltsc2022 is work

3.use office 2019, install failed

how to make it to work with mcr.microsoft.com/windows:1809 and object action?
or how to get the error?