问:
Thymeleaf errors are not showing on page but validation is fine
Controller:

```<code>@PostMapping("/saveExpense/{walletId}")
public String saveExpense(@PathVariable(value = "walletId") long walletId,
                          @ModelAttribute("wallets") @Valid Transaction transaction, BindingResult result, Model model) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();

    Wallet wallet = walletService.getWalletById(walletId);

    boolean thereAreErrors = result.hasErrors();
    if (thereAreErrors) {
        model.addAttribute("transaction", transaction);
        return "redirect:/api/transaction/showNewTransactionForm/" + walletId;

    }

    transaction.setWallet(wallet);
    transactionService.saveExpense(transaction, walletId, userId);
    return "redirect:/api/wallet/userWallet/balance/" + userId;
}
</code>```

This is form inside Thymeleaf:

```<code><form action="#" id="Expense" class="hidden" th:action="@{/api/transaction/saveExpense/{walletId} (walletId=${id})}"
      th:object="${transaction}" method="POST">

    <input type="text" th:field="*{amount}" placeholder="Enter amount" class="form-control mb-4 col-4">
    <p th:if="${#fields.hasErrors('amount')}" th:class="${#fields.hasErrors('amount')}? error">
        Invalid Age</p>

    <input type="text" th:field="*{note}" placeholder="Enter note" class="form-control mb-4 col-4">
    <input type="date" th:field="*{date}" class="form-control mb-4 col-4">

    <select th:field="${transaction.expenseCategories}">
        <option value="0">Select expense category</option>
        <option
                th:each="expenseCategories : ${expenseCategories}"
                th:value="${expenseCategories}"
                th:text="${expenseCategories.displayName}"
        ></option>
    </select>

    <button type="submit" class="btn btn-info col-2"> Save Wallet</button>

</form>
</code>```

Here is the part of field that I want to display error:

```<code> <input type="text" th:field="*{amount}" placeholder="Enter amount" class="form-control mb-4 col-4">
    <p th:if="${#fields.hasErrors('amount')}" th:class="${#fields.hasErrors('amount')}? error">
        Invalid Age</p>
</code>```

And inside model:

```<code>@Min(value = 0, message = "Please, insert a positive amount")
private double amount;
</code>```

So for example, if I try to set amount -1 and after I submit form, that data is not saved in database so that is fine, but I cant see errors on page, I just get redirected to same page but no errors are showing.

Just to mention, I already tried to find something useful here on SO but nothing worked so far

Body:
Controller:

@PostMapping("/saveExpense/{walletId}")
public String saveExpense(@PathVariable(value = "walletId") long walletId,
                          @ModelAttribute("wallets") @Valid Transaction transaction, BindingResult result, Model model) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();

    Wallet wallet = walletService.getWalletById(walletId);

    boolean thereAreErrors = result.hasErrors();
    if (thereAreErrors) {
        model.addAttribute("transaction", transaction);
        return "redirect:/api/transaction/showNewTransactionForm/" + walletId;

    }

    transaction.setWallet(wallet);
    transactionService.saveExpense(transaction, walletId, userId);
    return "redirect:/api/wallet/userWallet/balance/" + userId;
}

This is form inside Thymeleaf:

<form action="#" id="Expense" class="hidden" th:action="@{/api/transaction/saveExpense/{walletId} (walletId=${id})}"
      th:object="${transaction}" method="POST">

    <input type="text" th:field="*{amount}" placeholder="Enter amount" class="form-control mb-4 col-4">

        Invalid Age

    <input type="text" th:field="*{note}" placeholder="Enter note" class="form-control mb-4 col-4">
    <input type="date" th:field="*{date}" class="form-control mb-4 col-4">

    <select th:field="${transaction.expenseCategories}">
        <option value="0">Select expense category</option>
        <option
                th:each="expenseCategories : ${expenseCategories}"
                th:value="${expenseCategories}"
                th:text="${expenseCategories.displayName}"
        ></option>
    </select>

    <button type="submit" class="btn btn-info col-2"> Save Wallet</button>

</form>

Here is the part of field that I want to display error:

 <input type="text" th:field="*{amount}" placeholder="Enter amount" class="form-control mb-4 col-4">

        Invalid Age

And inside model:

@Min(value = 0, message = "Please, insert a positive amount")
private double amount;

So for example, if I try to set amount -1 and after I submit form, that data is not saved in database so that is fine, but I cant see errors on page, I just get redirected to same page but no errors are showing.

Just to mention, I already tried to find something useful here on SO but nothing worked so far


来源: stackexchange

问:
How to Validate image Width and size before uploading it?
I wanted to validate images before uploading . The requirements are width max : 1024 px , size should be less than 10Mb and png/jpeg allowed only.

I have created code using typescript , it is not working  in a proper way as i expected , one issue which i am facing is , its even uploading when the image fails the criteria of max width and size ! , How can i resolve this error ? Appreciate your help , here's the code so far :

```<code> const [inputFile, setInputFile] = useState<any>();

  const initialValues = {
    thumbnailImg :'',
  }

 const file_choosen = (event) => {
    let filePath = event.target.value;
    const file = event.target.files?.[0];
    var srcUrl = URL.createObjectURL(event.target.files[0]);
    let fileExt = filePath.substring(filePath.lastIndexOf('.') + 1, filePath.length).toLowerCase();
    if (!file) {
      return;
    }
    if(fileExt == "png" || fileExt == "jpeg"){
        const reader = new FileReader();
        reader.onload = (e) => {
          const image = new Image();
          image.src = e?.target?.result as string;
          image.onload = () => {
            if (image.width > 1024) {
                toast(intl.formatMessage({ id: 'IMG.WIDTH.ERR' }), { type: "error" });
              return;
            }
            if (file.size > 10000000) { // 10MB
                toast(intl.formatMessage({ id: 'IMG.SIZE.ERR' }), { type: "error" });
              return;
            }
            // formik_buttons_type.handleChange(event);

          };
        };
        formik_buttons_type.setFieldValue("thumbnailImg" , event.target.value)
        reader.readAsDataURL(file);
        setInputFile(event.target.files[0]);

    } else {
        setInputFile(null)
        toast(intl.formatMessage({ id: 'IMG.ALLOWED' }), { type: "error" });
        return;
    }
  };

return(
  <>
 <form onSubmit={formik_buttons_type.handleSubmit}>
          <div className='row m-10'>
                     <div className='col-lg-5'>
                        <h4><label className="form-label">Thumbnail Image</label></h4>
                        <input
                           {...formik_buttons_type.getFieldProps('thumbnailImg')}
                           className={clsx(
                             'form-control form-control-lg form-control-solid',
                             { 'is-invalid': formik_buttons_type.touched.thumbnailImg && formik_buttons_type.errors.thumbnailImg },
                             {
                               'is-valid': formik_buttons_type.touched.thumbnailImg && !formik_buttons_type.errors.thumbnailImg,
                             }
                           )}
                             type="file"
                             id="input-file"
                             name="image"
                             onChange={file_choosen}
                           />
                     </div>
                    <div className='col-lg-7'>
                    {
                          inputFile ?
                            <div >
                              <div id="templateImg-display border border-dark rounded mb-6">
                                <img id="templateImg" src={URL.createObjectURL(inputFile)} style={{width:"100px" , height:'100px'}} />
                              </div>
                            </div>
                            :
                            <>
                              <div className="border border-primary mb-6 ">
                                <div className="text-center text-muted my-5" style={{ width: "50%" }}>Select Template Image</div>
                              </div>
                            </>
                        }
                    </div>
                </div>

 </form>

  </>
)

</code>```

Any help is appreciated , again the issue i am facing is , The input field to upload image is also selecting the images which fails the requirement mentioned above.
regards

ContentLicense: CC BY-SA 4.0

Body:
I wanted to validate images before uploading . The requirements are width max : 1024 px , size should be less than 10Mb and png/jpeg allowed only.

I have created code using typescript , it is not working  in a proper way as i expected , one issue which i am facing is , its even uploading when the image fails the criteria of max width and size ! , How can i resolve this error ? Appreciate your help , here's the code so far :

 const [inputFile, setInputFile] = useState<any>();

  const initialValues = {
    thumbnailImg :'',
  }

 const file_choosen = (event) => {
    let filePath = event.target.value;
    const file = event.target.files?.[0];
    var srcUrl = URL.createObjectURL(event.target.files[0]);
    let fileExt = filePath.substring(filePath.lastIndexOf('.') + 1, filePath.length).toLowerCase();
    if (!file) {
      return;
    }
    if(fileExt == "png" || fileExt == "jpeg"){
        const reader = new FileReader();
        reader.onload = (e) => {
          const image = new Image();
          image.src = e?.target?.result as string;
          image.onload = () => {
            if (image.width > 1024) {
                toast(intl.formatMessage({ id: 'IMG.WIDTH.ERR' }), { type: "error" });
              return;
            }
            if (file.size > 10000000) { // 10MB
                toast(intl.formatMessage({ id: 'IMG.SIZE.ERR' }), { type: "error" });
              return;
            }
            // formik_buttons_type.handleChange(event);

          };
        };
        formik_buttons_type.setFieldValue("thumbnailImg" , event.target.value)
        reader.readAsDataURL(file);
        setInputFile(event.target.files[0]);

    } else {
        setInputFile(null)
        toast(intl.formatMessage({ id: 'IMG.ALLOWED' }), { type: "error" });
        return;
    }
  };

return(
  <>
 <form onSubmit={formik_buttons_type.handleSubmit}>

Thumbnail Image

                        <input
                           {...formik_buttons_type.getFieldProps('thumbnailImg')}
                           className={clsx(
                             'form-control form-control-lg form-control-solid',
                             { 'is-invalid': formik_buttons_type.touched.thumbnailImg && formik_buttons_type.errors.thumbnailImg },
                             {
                               'is-valid': formik_buttons_type.touched.thumbnailImg && !formik_buttons_type.errors.thumbnailImg,
                             }
                           )}
                             type="file"
                             id="input-file"
                             name="image"
                             onChange={file_choosen}
                           />

                    {
                          inputFile ?

                            :
                            <>

Select Template Image

                            </>
                        }

 </form>

  </>
)

Any help is appreciated , again the issue i am facing is , The input field to upload image is also selecting the images which fails the requirement mentioned above.
regards


问:
Huge output message
I'm trying to execute the following code using tensorflow, Hugginface's transformer and openai/whisper-base model

```<code>import tensorflow as tf
import transformers

# Load the model and tokenizer
model = transformers.TFWhisperModel.from_pretrained('openai/whisper-base')
tokenizer = transformers.WhisperTokenizer.from_pretrained('openai/whisper-base')

# Read the audio file and convert it to a tensor
audio_file = "data/preamble.wav"
with open(audio_file, 'rb') as f:
    audio = f.read()
input_ids = tf.constant(tokenizer.encode(audio, return_tensors='tf'))

# Transcribe the audio
output = model(input_ids)[0]
transcription = tokenizer.decode(output, skip_special_tokens=True)

with open("something.txt", "w") as f:
    f.write(transcription)
</code>```

I'm getting this huge output error, too big to copy and paste here, below is an error snippet. The entire message consists of the same syntax except for the last line, which I've pasted below. The add picture is the top of the error message that I had to screenshot before it disappears.

Top of Error message picture

The 1st output to terminal after running script

Bottom of Error Snippet

```<code>c\xff\x0c\x00\xeb\xff\xb3\xff\xc5\xff\x0f\x00\xde\xff\x16\x00B\x00\x0e\x00\xfd\xff$\x000\x00\xff\x
ff\xe7\xff<\x00\xfb\xff\n\x00/\x008\x00\x06\x00\x17\x00\x1d\x00\xde\xff\xf2\xff\xec\xff\xff\xff\x0
f\x00\x1b\x008\x00\x1d\x003\x00%\x00#\x00\r\x00\x16\x00\x1d\x00\x19\x00\xf7\xff\x14\x00\xff\xff\xc
c\xff\x06\x00\xf1\xff\x11\x00\xf0\xff*\x00P\x00\xe7\xffH\x00\t\x00\xd0\xff\xd0\xff\xee\xff\xf6\xff
\xc6\xff\xe4\xff\xce\xff' is not valid. Should be a string, a list/tuple of strings or a list/tuple
 of integers.
</code>```

The last line is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers. is my only clue as to my next step.

I cannot scroll to the top to find where in my code is throwing the error. I'm new to machine learning and I don't know what I'm seeing. Any help is appreciated.

Thank you in advance!!!

I tried a try execpt block around output and transcription with no change, same output message

I've tried:

```<code>input_ids = str(tf.constant(tokenizer.encode(audio, return_tensors='tf')))
</code>```
```<code>input_ids = []
input_ids = input_ids.append(int(tf.constant(tokenizer.encode(audio, return_tensors='tf'))))
</code>```
```<code>output = model(str(input_ids))[0]
</code>```

No change to the output

Title: Huge output message

Body:
I'm trying to execute the following code using tensorflow, Hugginface's transformer and openai/whisper-base model

import tensorflow as tf
import transformers

# Load the model and tokenizer
model = transformers.TFWhisperModel.from_pretrained('openai/whisper-base')
tokenizer = transformers.WhisperTokenizer.from_pretrained('openai/whisper-base')

# Read the audio file and convert it to a tensor
audio_file = "data/preamble.wav"
with open(audio_file, 'rb') as f:
    audio = f.read()
input_ids = tf.constant(tokenizer.encode(audio, return_tensors='tf'))

# Transcribe the audio
output = model(input_ids)[0]
transcription = tokenizer.decode(output, skip_special_tokens=True)

with open("something.txt", "w") as f:
    f.write(transcription)

I'm getting this huge output error, too big to copy and paste here, below is an error snippet. The entire message consists of the same syntax except for the last line, which I've pasted below. The add picture is the top of the error message that I had to screenshot before it disappears.

Top of Error message picture

The 1st output to terminal after running script

Bottom of Error Snippet

c\xff\x0c\x00\xeb\xff\xb3\xff\xc5\xff\x0f\x00\xde\xff\x16\x00B\x00\x0e\x00\xfd\xff$\x000\x00\xff\x
ff\xe7\xff<\x00\xfb\xff\n\x00/\x008\x00\x06\x00\x17\x00\x1d\x00\xde\xff\xf2\xff\xec\xff\xff\xff\x0
f\x00\x1b\x008\x00\x1d\x003\x00%\x00#\x00\r\x00\x16\x00\x1d\x00\x19\x00\xf7\xff\x14\x00\xff\xff\xc
c\xff\x06\x00\xf1\xff\x11\x00\xf0\xff*\x00P\x00\xe7\xffH\x00\t\x00\xd0\xff\xd0\xff\xee\xff\xf6\xff
\xc6\xff\xe4\xff\xce\xff' is not valid. Should be a string, a list/tuple of strings or a list/tuple
 of integers.

The last line is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers. is my only clue as to my next step.

I cannot scroll to the top to find where in my code is throwing the error. I'm new to machine learning and I don't know what I'm seeing. Any help is appreciated.

Thank you in advance!!!

I tried a try execpt block around output and transcription with no change, same output message

I've tried:

input_ids = str(tf.constant(tokenizer.encode(audio, return_tensors='tf')))

input_ids = []
input_ids = input_ids.append(int(tf.constant(tokenizer.encode(audio, return_tensors='tf'))))

output = model(str(input_ids))[0]

No change to the output


问:
Android animating a (clone of a) view while keeping original view unchanged
I'm trying to trigger an animation on a button press where one view is cloned and its clone is animated to another location on the screen.

Is there any existing animation method to do the trick?

Since I couldn't find one, I tried the following:

Created another 'ghost' view in the XML with the same properties but with visibility of View.GONE and in the activity file tried the following:

Move the position of the 'ghost view' to where the original view is using View.SetX(), View.SetY().

Set the visibility of the 'ghost view' to View.VISIBLE.

animate the now visible 'ghost view' using View.animate().xBy().yBy()

The result was that the 'ghost view' was animated back to where it originally was and not to the location specified in the xBy().yBy() method and seems like it was caused by the View.SetX(), View.SetY() calls for some reason.

This is a part of a complex activity that isn't quite readable but if necessary I will create a project with an isolated example.

This is in Java.

Thanks for any help.


问:
How do I access the Linkedin search API?
https://learn.microsoft.com/en-us/linkedin/shared/integrations/people/handle-lookup

I am trying to call this API as the documentation shows, but I get this error back:

Here is the headers I am sending:
{'Authorization': 'Bearer xxxxxx', 'cache-control': 'no-cache', 'X-Restli-Protocol-Version': '2.0.0', 'X-Forwarded-For': '198.51.100.1', 'Caller-Account-Age': '2', 'Caller-Device-UUID': 'a859b63d-7135-4d96-be47-c21d392bfad2'}

I have authenticated with the right scopes and got the right OAUTH token and validated it by calling the userinfo endpoint

Here is the response I get back from calling this API:

https://api.linkedin.com/v2/clientAwareMemberHandles?q=handleString&handleString={something@something.com}

{'serviceErrorCode': 100, 'message': 'Not enough permissions to access: GET-handleString /clientAwareMemberHandles', 'status': 403}

All I am trying to do is get the user LinkedIn profile for a specific email address.

Also, is there a way to reach out to Linkedin support for this?

The API listed above.

Was expecting the member profile associated with the email.


问:
electron virtual keyboard on external child window
i am working with electron@22.0.0 running on raspberry, and i need to support connecting to WIFI through captive portal. the captive portal being opened by window.open and handled with preload.js by mainWindow.webContents.setWindowOpenHandler method. i am trying to use in the child window (captive portal) the same keyboard that i use for the app which is 'electron-virtual-keyboard', the problem is that i cannot inject any js (i.e webFrame.executeJavaScript) since i cannot require any module inside the child window.

for example , the following code will throw exception 'require is undefined'

captivePortalPreload.js

i have tried enabling the following
webPreferences: { devTools: true, nodeIntegration: false, webSecurity: true, contextIsolation: true, enableRemoteModule: true, sandbox: false, preload: app.isPackaged ? path.join(__dirname, 'captivePortalPreload.js') : path.join(__dirname, '../../.erb/dll/captivePortalPreload.js'), },


问:
"blocked by CORS policy" error, Take input locally rather than webcam in teachable machine code
From the teachable machine export, I copied javascript code and it takes its input from the webcam to give produced results. I want to provide an input image from my device but facing an issue as my code is not giving any output.

This is my code

```<code><div>Teachable Machine Image Model</div>
<button type="button" onclick="init()">Start</button>
<div id="label-container"></div>

<!-- Add the file input element -->
<input type="file" id="file-input" accept="image/*"/>

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.3.1/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@teachablemachine/image@0.8/dist/teachablemachine-image.min.js"></script>
<script type="text/javascript">
  // More API functions here:
  // https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/image

  // the link to your model provided by Teachable Machine export panel
  const URL = "https://teachablemachine.withgoogle.com/models/Kk5_BUYCy/";

  let model, fileInput, labelContainer, maxPredictions;

  // Load the image model and setup the file input element
  async function init() {
    console.log("inside init")
    const modelURL = URL + "model.json";
    const metadataURL = URL + "metadata.json";

    // load the model and metadata
    // Refer to tmImage.loadFromFiles() in the API to support files from a file picker
    // or files from your local hard drive
    // Note: the pose library adds "tmImage" object to your window (window.tmImage)
    model = await tmImage.load(modelURL, metadataURL);
    maxPredictions = model.getTotalClasses();

    // Replace the webcam object with the file input element
    // webcam = new tmImage.Webcam(200, 200, flip);
    fileInput = document.getElementById("file-input")
    fileInput.addEventListener("change", predict(fileInput));

    labelContainer = document.getElementById("label-container");
    for (let i = 0; i < maxPredictions; i++) { // and class labels
      labelContainer.appendChild(document.createElement("div"));
    }
  }

  async function predict(fileInput) {
    console.log("inside predict")
    try {
        // Get the file from the file input element
        const file = fileInput.files[0];
        // Load the image
        const image = await tmImage.load(URL + file);
        // Predict the class
        const prediction = await model.predict(fileinput);
        for (let i = 0; i < maxPredictions; i++) {
            const classPrediction =
                prediction[i].className + ": " + prediction[i].probability.toFixed(2);
            labelContainer.childNodes[i].innerHTML = classPrediction;
        }

    } catch (error) {
        console.log(error)
    }

  }
</script>

</code>```

Getting error:
Access to fetch at 'https://teachablemachine.withgoogle.com/models/Kk5_BUYCy/%5Bobject%20File%5D' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Body:
From the teachable machine export, I copied javascript code and it takes its input from the webcam to give produced results. I want to provide an input image from my device but facing an issue as my code is not giving any output.

This is my code

Teachable Machine Image Model

<button type="button" onclick="init()">Start</button>

<input type="file" id="file-input" accept="image/*"/>

Getting error:
Access to fetch at 'https://teachablemachine.withgoogle.com/models/Kk5_BUYCy/%5Bobject%20File%5D' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


问:
Change numbering format for tables in rmarkdown, to whole document instead of per section
I am producing a Word document with tables. This is mycode:

```<code>---
title: Tables Query
output:
  bookdown::word_document2: default
---

```{r setup, include= FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE)

```

# Section

Here is Table \@ref(tab:foo)

```{r foo}
knitr::kable( head(mtcars), caption = "a table")
```

Here is another table Table \@ref(tab:bar)

```{r bar}
knitr::kable( head(iris), caption = "another table")
```
</code>```

This produces:

But I just want the tables to be numbered Table 1 and Table 2. If I started an new section with a third table, that would be Table 3.

Body:
I am producing a Word document with tables. This is mycode:

---
title: Tables Query
output:
  bookdown::word_document2: default
---

```{r setup, include= FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE)

```

# Section

Here is Table \@ref(tab:foo)

```{r foo}
knitr::kable( head(mtcars), caption = "a table")
```

Here is another table Table \@ref(tab:bar)

```{r bar}
knitr::kable( head(iris), caption = "another table")
```

This produces:

But I just want the tables to be numbered Table 1 and Table 2. If I started an new section with a third table, that would be Table 3.


问:
Error while compiling assets in Prestashop
I decided to study Prestashop and during the preparation of the development environment during the compilation of assets through the console and the make assets command, an error appears as in the screenshot.

I have installed: XAMMP 8.0, Prestashop 8.0, GnuWin 32 and chocolatey. I tried many options both on this forum and on other sites - the error remained. Does anyone have any ideas or solutions to this problem?

```<code>PS C:\xampp\htdocs\presta> make assets
./tools/assets/build.sh
process_begin: CreateProcess(NULL, bash C:\xampp\htdocs\presta\tools\assets\build.sh, ...) failed.
make (e=2): The system cannot find the file specified.
make: *** [Makefile:7: assets] Error 2
PS C:\xampp\htdocs\presta>
</code>```

Body:
I decided to study Prestashop and during the preparation of the development environment during the compilation of assets through the console and the make assets command, an error appears as in the screenshot.

I have installed: XAMMP 8.0, Prestashop 8.0, GnuWin 32 and chocolatey. I tried many options both on this forum and on other sites - the error remained. Does anyone have any ideas or solutions to this problem?

PS C:\xampp\htdocs\presta> make assets
./tools/assets/build.sh
process_begin: CreateProcess(NULL, bash C:\xampp\htdocs\presta\tools\assets\build.sh, ...) failed.
make (e=2): The system cannot find the file specified.
make: *** [Makefile:7: assets] Error 2
PS C:\xampp\htdocs\presta>


问:
Clear text in a form from a Button Press in Kivy
I'm new to Kivy. Below is my Kivy code, where I'm trying to clear the form data(TextField) by using a button click event, which is written at the bottom of my kv code.
It gives an error:
Exception has occurred: AttributeError
'super' object has no attribute 'getattr'

studentregister.kv (See the code from bottom)

```<code>MDScreen:
    name: "student_create"
    #StudentRegister:
    MDFloatLayout:
        md_bg_color: 1,1,1,1
        MDIconButton:
            icon: "arrow-left"
            pos_hint: {"center_y": .95}
            on_release:
                root.manager.transition.direction= "right"
                root.manager.current= "newaccount"
        Image:
            source: "images/newstud.png"
            pos_hint: {"center_x": .78, "center_y": .9}
            size_hint: .13, .13
        MDLabel:`your text`
            text: 'Create New Student Account'
            #font_name: 'MPoppins'
            font_size: "18sp"
            pos_hint: {"center_x": .6, "center_y": .84}
            color: rgba(135, 133, 193, 255)
        MDFloatLayout:
            size_hint: .7, .07
            pos_hint: {"center_x": .5, "center_y": .73}
            MDTextField:
                id: "t1"
                hint_text: 'Calling Name'
                pos_hint: {'center_x': 0.43, 'center_y': 0.43}
                background_color: 1,1,1,0
                foreground_color: rgba(0, 0, 59, 255)
                cursor_color: rgba(0, 0, 59, 255)
                font_size: '12sp'
                cursor_width: '2sp'
                multiline: False
        MDFloatLayout:
            size_hint: .7, .07
            pos_hint: {"center_x": .5, "center_y": .65}
            MDTextField:
                id: "t2"
                hint_text: 'Surname'
                pos_hint: {'center_x': 0.43, 'center_y': 0.43}
                background_color: 1,1,1,0
                foreground_color: rgba(0, 0, 59, 255)
                cursor_color: rgba(0, 0, 59, 255)
                font_size: '12sp'
                cursor_width: '2sp'
                multiline: False
        Button:
            text: "Clear"
            size_hint: .35, .065
            background_color: 0,0,0,0
            pos_hint: {"center_x": .32, "center_y": .06}
            on_release:
                root.ids.t1.text: ""
                root.ids.t2.text: ""
            canvas.before:
                Color:
                    rgb: rgba (52, 0, 231, 255)
                RoundedRectangle:
                    size: self.size
                    pos: self.pos
                    radius: [5]
</code>```

main.py

```<code>from kivymd.app import MDApp
from drivermapview import DriversMapView
from mysqlconn import SqlConn
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager
Window.size=(310,580)

class MainApp(MDApp):
    connection = None
    cursor = None

    def build(self):
        #Connect to database
        self.cursor = SqlConn.sbdb.cursor()
        self.theme_cls.material_style = "M3"
        screen_mgr = ScreenManager()
        screen_mgr.add_widget(Builder.load_file("studentregister.kv"))
        screen_mgr.add_widget(Builder.load_file("newaccount.kv"))
        screen_mgr.add_widget(Builder.load_file("main.kv"))

        return screen_mgr
MainApp().run()
</code>```

Body:
I'm new to Kivy. Below is my Kivy code, where I'm trying to clear the form data(TextField) by using a button click event, which is written at the bottom of my kv code.
It gives an error:
Exception has occurred: AttributeError
'super' object has no attribute 'getattr'

studentregister.kv (See the code from bottom)

MDScreen:
    name: "student_create"
    #StudentRegister:
    MDFloatLayout:
        md_bg_color: 1,1,1,1
        MDIconButton:
            icon: "arrow-left"
            pos_hint: {"center_y": .95}
            on_release:
                root.manager.transition.direction= "right"
                root.manager.current= "newaccount"
        Image:
            source: "images/newstud.png"
            pos_hint: {"center_x": .78, "center_y": .9}
            size_hint: .13, .13
        MDLabel:`your text`
            text: 'Create New Student Account'
            #font_name: 'MPoppins'
            font_size: "18sp"
            pos_hint: {"center_x": .6, "center_y": .84}
            color: rgba(135, 133, 193, 255)
        MDFloatLayout:
            size_hint: .7, .07
            pos_hint: {"center_x": .5, "center_y": .73}
            MDTextField:
                id: "t1"
                hint_text: 'Calling Name'
                pos_hint: {'center_x': 0.43, 'center_y': 0.43}
                background_color: 1,1,1,0
                foreground_color: rgba(0, 0, 59, 255)
                cursor_color: rgba(0, 0, 59, 255)
                font_size: '12sp'
                cursor_width: '2sp'
                multiline: False
        MDFloatLayout:
            size_hint: .7, .07
            pos_hint: {"center_x": .5, "center_y": .65}
            MDTextField:
                id: "t2"
                hint_text: 'Surname'
                pos_hint: {'center_x': 0.43, 'center_y': 0.43}
                background_color: 1,1,1,0
                foreground_color: rgba(0, 0, 59, 255)
                cursor_color: rgba(0, 0, 59, 255)
                font_size: '12sp'
                cursor_width: '2sp'
                multiline: False
        Button:
            text: "Clear"
            size_hint: .35, .065
            background_color: 0,0,0,0
            pos_hint: {"center_x": .32, "center_y": .06}
            on_release:
                root.ids.t1.text: ""
                root.ids.t2.text: ""
            canvas.before:
                Color:
                    rgb: rgba (52, 0, 231, 255)
                RoundedRectangle:
                    size: self.size
                    pos: self.pos
                    radius: [5]

main.py

from kivymd.app import MDApp
from drivermapview import DriversMapView
from mysqlconn import SqlConn
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager
Window.size=(310,580)

class MainApp(MDApp):
    connection = None
    cursor = None

    def build(self):
        #Connect to database
        self.cursor = SqlConn.sbdb.cursor()
        self.theme_cls.material_style = "M3"
        screen_mgr = ScreenManager()
        screen_mgr.add_widget(Builder.load_file("studentregister.kv"))
        screen_mgr.add_widget(Builder.load_file("newaccount.kv"))
        screen_mgr.add_widget(Builder.load_file("main.kv"))

        return screen_mgr
MainApp().run()


问:
Attempting to test a class using @Value annotation in primary constructor fails

Technology used

Spring Boot 3.0.1

Kotlin

JUnit

Problems

When I run the test code, I am getting the error below.

```<code>AmazonS3ClientTest > sample test() FAILED
    org.junit.jupiter.api.extension.ParameterResolutionException at ParameterResolutionUtils.java:159
        Caused by: java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:142
            Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:798
                Caused by: org.springframework.beans.TypeMismatchException at TypeConverterSupport.java:79
                    Caused by: java.lang.IllegalArgumentException at CustomBooleanEditor.java:154
</code>```

Test code and the code of the class under test

AmazonS3ClientTest

```<code>
:

@Configuration
@SpringBootApplication
internal class AmazonS3ClientTest(
    @Autowired private val storageClient: StorageClient
) {

    @Test
    fun `sample test`() {

    :

}

</code>```

AmazonS3Client

```<code>
:

@Component
class AmazonS3Client(
    @Value("\${app.s3.endpoint}") private val endpoint: String,
    @Value("\${app.s3.accessKey") private val accessKey: String,
    @Value("\${app.s3.secretKey") private val secretKey: String,
    ): StorageClient {

  :

}

</code>```

Body:
Technology used

Spring Boot 3.0.1

Kotlin

JUnit

Problems

When I run the test code, I am getting the error below.

AmazonS3ClientTest > sample test() FAILED
    org.junit.jupiter.api.extension.ParameterResolutionException at ParameterResolutionUtils.java:159
        Caused by: java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:142
            Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:798
                Caused by: org.springframework.beans.TypeMismatchException at TypeConverterSupport.java:79
                    Caused by: java.lang.IllegalArgumentException at CustomBooleanEditor.java:154

Test code and the code of the class under test

AmazonS3ClientTest

:

@Configuration
@SpringBootApplication
internal class AmazonS3ClientTest(
    @Autowired private val storageClient: StorageClient
) {

    @Test
    fun `sample test`() {

    :

}

AmazonS3Client

:

@Component
class AmazonS3Client(
    @Value("\${app.s3.endpoint}") private val endpoint: String,
    @Value("\${app.s3.accessKey") private val accessKey: String,
    @Value("\${app.s3.secretKey") private val secretKey: String,
    ): StorageClient {

  :

}


问:
Opencv-python, face recognition problem, camera turnoff automatically
I am trying to detect faces through OpenCV module but facing a problem when my camera is turned on after running the code, it turns off automatically and shows me some errors, please take a look at I Would appreciate your help.

Thank you

```<code>for (top,right,bottom,left), name in zip (self.face_location,self.face_names):
                top*=4
                right*=4
                bottom*=4
                left*=4

                cv2.rectangle(frame,(left,top), (right, bottom), (0,0,255),2)
                cv2.rectangle(frame,(left,bottom-35),(right,bottom),(0,0,255),-1)
                cv2.putText(frame, name,(left + 6,bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 0,8,(255,255,255), 2)

            cv2.imshow('Face recognition', frame)
            if cv2.waitKey(1)== ord('q'):
                break
</code>```

OutPut Error:

```<code>Traceback (most recent call last):
  File "c:/Users/HP/Desktop/facerecogniation/main.py", line 94, in <module>
    fr.run_recognition()
  File "c:/Users/HP/Desktop/facerecogniation/main.py", line 82, in run_recognition
    cv2.putText(frame, name,(left + 6,bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 0,8,(255,255,255), int(2))
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Argument 'thickness' is required to be an integer
>  - Argument 'thickness' is required to be an integer
</code>```

I need help with this. If you know why this error occurs, please let me know. I will be very grateful.

Body:
I am trying to detect faces through OpenCV module but facing a problem when my camera is turned on after running the code, it turns off automatically and shows me some errors, please take a look at I Would appreciate your help.

Thank you

for (top,right,bottom,left), name in zip (self.face_location,self.face_names):
                top*=4
                right*=4
                bottom*=4
                left*=4

                cv2.rectangle(frame,(left,top), (right, bottom), (0,0,255),2)
                cv2.rectangle(frame,(left,bottom-35),(right,bottom),(0,0,255),-1)
                cv2.putText(frame, name,(left + 6,bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 0,8,(255,255,255), 2)

            cv2.imshow('Face recognition', frame)
            if cv2.waitKey(1)== ord('q'):
                break

OutPut Error:

Traceback (most recent call last):
  File "c:/Users/HP/Desktop/facerecogniation/main.py", line 94, in <module>
    fr.run_recognition()
  File "c:/Users/HP/Desktop/facerecogniation/main.py", line 82, in run_recognition
    cv2.putText(frame, name,(left + 6,bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 0,8,(255,255,255), int(2))
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Argument 'thickness' is required to be an integer
>  - Argument 'thickness' is required to be an integer

I need help with this. If you know why this error occurs, please let me know. I will be very grateful.


问:
How to navigate from one local webpage to a Website using POST menthod in Flutter Web view plugin?
```<code>const String kNavigationExamplePage = '''
<!DOCTYPE html><html>
<head><title>Navigation Delegate Example</title></head>
<body>
<form action="${model.url}" id="MPUForm" name="MPUForm"  method="POST">
<input type="text" name="amount"  value="${model.amount}" />
</form>
</body>
</html>
''';
</code>```
```<code> Future<void> _onLoadHtmlStringExample() {
    return webViewController.loadHtmlString(kLocalExamplePage);
  }
</code>```
```<code>Future<void> onDoPostRequest() async {
    return webcontroller.loadRequest(
      Uri.parse(url),
      method: LoadRequestMethod.post,
      body: Uint8List.fromList(kNavigationExamplePage.codeUnits),
    );
  }
</code>```

I try the above code . it did navigate to the second webpage but it doesnt include the data i posted from first local page

```<code><form action="${model.url}" id="MPUForm" name="MPUForm"  method="POST">
<input type="text" name="amount"  value="${model.amount}" />
</form>
</code>```

Body:
const String kNavigationExamplePage = '''
<!DOCTYPE html>
<title>Navigation Delegate Example</title>

<form action="${model.url}" id="MPUForm" name="MPUForm"  method="POST">
<input type="text" name="amount"  value="${model.amount}" />
</form>

''';

 Future<void> _onLoadHtmlStringExample() {
    return webViewController.loadHtmlString(kLocalExamplePage);
  }

Future<void> onDoPostRequest() async {
    return webcontroller.loadRequest(
      Uri.parse(url),
      method: LoadRequestMethod.post,
      body: Uint8List.fromList(kNavigationExamplePage.codeUnits),
    );
  }

I try the above code . it did navigate to the second webpage but it doesnt include the data i posted from first local page

<form action="${model.url}" id="MPUForm" name="MPUForm"  method="POST">
<input type="text" name="amount"  value="${model.amount}" />
</form>


问:
SQL Server Difference() function not working as expected
I need to do a fuzzy name comparison for two names and see if they match. Think of it like you've written a check for "Frank A. Anderson" and when the check is deposited it changed to "Frank Smith". The goal is to see how close the two names match.

I discovered the function Difference() in SQL Server and it seems like that does the job by comparing two strings and return how similar they are. However, I am having a problem understanding why the below query returns the same result:

```<code>SELECT
    DIFFERENCE ('Frank A. Anderson', 'Frank Anderson') AS Good,
    DIFFERENCE ('Frank A. Anderson', 'Frank Smith') AS Bad
</code>```

Both Good and Bad returns "4", which I understand is a match. For the first one, sure, missing a middle name "A" is OK. But for the second one, not only it's missing the middle name A, it has a completely different last name. How come it also returns a 4? How can these two comparison returns the same result?

If Difference() is not the right method I need for my purpose, what other suggestions you have? I hate to do a straight string equal as a comma/dot/space would ruin the comparison.

Any help would be appreciated.

Body:
I need to do a fuzzy name comparison for two names and see if they match. Think of it like you've written a check for "Frank A. Anderson" and when the check is deposited it changed to "Frank Smith". The goal is to see how close the two names match.

I discovered the function Difference() in SQL Server and it seems like that does the job by comparing two strings and return how similar they are. However, I am having a problem understanding why the below query returns the same result:

SELECT
    DIFFERENCE ('Frank A. Anderson', 'Frank Anderson') AS Good,
    DIFFERENCE ('Frank A. Anderson', 'Frank Smith') AS Bad

Both Good and Bad returns "4", which I understand is a match. For the first one, sure, missing a middle name "A" is OK. But for the second one, not only it's missing the middle name A, it has a completely different last name. How come it also returns a 4? How can these two comparison returns the same result?

If Difference() is not the right method I need for my purpose, what other suggestions you have? I hate to do a straight string equal as a comma/dot/space would ruin the comparison.

Any help would be appreciated.


问:
Nuxt 3 SSR - No console logs of server API in dev environment
When you do a simple console log in server API side, it doesn't show up when you build it using pnpm run dev.

But if you build it using pnpm run build and run the index.mjs, the console log will show up.

Code:

```<code>export default defineEventHandler(async (event) => {
  console.log('HAHAHAHAHA');

  return 'LOGIN!';
});
</code>```

Here is my npx nuxi info:

```<code>------------------------------
- Operating System: `Linux`
- Node Version:     `v18.12.1`
- Nuxt Version:     `3.0.0`
- Nitro Version:    `1.0.0`
- Package Manager:  `pnpm@7.22.0`
- Builder:          `vite`
- User Config:      `app`, `runtimeConfig`, `modules`, `ssr`, `vite`, `typescript`, `css`, `build`
- Runtime Modules:  `@app/ui@1.0.0-alpha`, `nuxt-icon@0.1.8`, `@pinia/nuxt@0.4.6`
- Build Modules:    `-`
------------------------------
</code>```

Body:
When you do a simple console log in server API side, it doesn't show up when you build it using pnpm run dev.

But if you build it using pnpm run build and run the index.mjs, the console log will show up.

Code:

export default defineEventHandler(async (event) => {
  console.log('HAHAHAHAHA');

  return 'LOGIN!';
});

Here is my npx nuxi info:

------------------------------
- Operating System: `Linux`
- Node Version:     `v18.12.1`
- Nuxt Version:     `3.0.0`
- Nitro Version:    `1.0.0`
- Package Manager:  `pnpm@7.22.0`
- Builder:          `vite`
- User Config:      `app`, `runtimeConfig`, `modules`, `ssr`, `vite`, `typescript`, `css`, `build`
- Runtime Modules:  `@app/ui@1.0.0-alpha`, `nuxt-icon@0.1.8`, `@pinia/nuxt@0.4.6`
- Build Modules:    `-`
------------------------------


问:
Does the hierarchical structure of an xreg influence selection a fable model?
I was looking at this post which got me wondering: if an xreg for a fable model is hierarchical, does this influence model selection of the dependent variable? In other words, would using the hierarchical xreg vs an aggregate of the xreg values (I.e., the sums with no hierarchical structure) result in different models, assuming the dependent variable is an identical time series in both scenarios?

How to implement regressors in a Hierarchical Series in R, with the Fable package?

Haven’t tried this so I have no code.


问:
Flutter Firebase installation issue
I tried to install firebase in my flutter. I'm experiencing corrupted issue.

Here is my complete screen with error status:

```<code>  mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sL https://firebase.tools | bash
Password:
-- Checking for existing firebase-tools on PATH...
-- Checking your machine type...
-- Downloading binary from https://firebase.tools/bin/macos/latest
######################################################################## 100.0%##O=#  #                          #########                                                                 13.3%curl: (92) HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)

-- Setting permissions on binary...
Password:
Something went wrong, firebase has not been installed.
Please file a bug with your system information on Github.
https://github.com/firebase/firebase-tools/
-- All done!
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sL https://firebase.tools | bash
-- Checking for existing firebase-tools on PATH...
Your machine has a corrupted firebase-tools binary installed.
If you would like to upgrade your install run: curl -sL firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sl firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sl firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd %
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sL https://firebase.tools | bash
-- Checking for existing firebase-tools on PATH...
Your machine has a corrupted firebase-tools binary installed.
If you would like to upgrade your install run: curl -sL firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sl firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd %

</code>```

Title: Flutter Firebase installation issue

Body:
I tried to install firebase in my flutter. I'm experiencing corrupted issue.

Here is my complete screen with error status:

  mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sL https://firebase.tools | bash
Password:
-- Checking for existing firebase-tools on PATH...
-- Checking your machine type...
-- Downloading binary from https://firebase.tools/bin/macos/latest
######################################################################## 100.0%##O=#  #                          #########                                                                 13.3%curl: (92) HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)

-- Setting permissions on binary...
Password:
Something went wrong, firebase has not been installed.
Please file a bug with your system information on Github.
https://github.com/firebase/firebase-tools/
-- All done!
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sL https://firebase.tools | bash
-- Checking for existing firebase-tools on PATH...
Your machine has a corrupted firebase-tools binary installed.
If you would like to upgrade your install run: curl -sL firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sl firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sl firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd %
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sL https://firebase.tools | bash
-- Checking for existing firebase-tools on PATH...
Your machine has a corrupted firebase-tools binary installed.
If you would like to upgrade your install run: curl -sL firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd % curl -sl firebase.tools | upgrade=true bash
mdjahangiralam@Mds-MacBook-Pro test_app_2nd %


问:
How to get the correct XPath for =ImportXML to get the Historical Data of a Crypto
I am trying to get the Historical Data in Coin Market Cap getting the price for the "Date" and the "Close Price" for that date.

https://coinmarketcap.com/currencies/bitcoin/historical-data/

I tried this but I'm still trying to get the basics of IMPORTXML.

=IMPORTXML("https://coinmarketcap.com/currencies/the-sandbox/historical-data/","//table//tr//td")

any help would be appreciated.


问:
Difference between S3Client and AmazonS3Client
Below is official aws sdk source regarding getting s3 object.

https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java

```<code>public class GetObjectData {

public static void main(String[] args) {
    String bucketName = args[0];
    String keyName = args[1];
    String path = args[2];

    ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create();
    Region region = Region.US_EAST_1;
    S3Client s3 = S3Client.builder()
        .region(region)
        .credentialsProvider(credentialsProvider)
        .build();

    getObjectBytes(s3,bucketName,keyName, path);
    s3.close();
}

// snippet-start:[s3.java2.getobjectdata.main]
public static void getObjectBytes (S3Client s3, String bucketName, String keyName, String path) {

    try {
        GetObjectRequest objectRequest = GetObjectRequest
            .builder()
            .key(keyName)
            .bucket(bucketName)
            .build();

        ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
        byte[] data = objectBytes.asByteArray();

        // Write the data to a local file.
        File myFile = new File(path );
        OutputStream os = new FileOutputStream(myFile);
        os.write(data);
        System.out.println("Successfully obtained bytes from an S3 object");
        os.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (S3Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
}
// snippet-end:[s3.java2.getobjectdata.main]
}
</code>```

As you can see, there is s3.close in the middle of the code block.

However, I have the second code which does not close the s3 client in the official aws sdk as below.

the code below can be seen in the link here https://docs.aws.amazon.com/AmazonS3/latest/userguide/download-objects.htm

```<code>public class GetObject2 {

    public static void main(String[] args) throws IOException {
        Regions clientRegion = Regions.DEFAULT_REGION;
        String bucketName = "*** Bucket name ***";
        String key = "*** Object key ***";

        S3Object fullObject = null, objectPortion = null, headerOverrideObject = null;
        try {
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new ProfileCredentialsProvider())
                    .build();

            // Get an object and print its contents.
            System.out.println("Downloading an object");
            fullObject = s3Client.getObject(new GetObjectRequest(bucketName, key));
            System.out.println("Content-Type: " + fullObject.getObjectMetadata().getContentType());
            System.out.println("Content: ");
            displayTextInputStream(fullObject.getObjectContent());

            // Get a range of bytes from an object and print the bytes.
            GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, key)
                    .withRange(0, 9);
            objectPortion = s3Client.getObject(rangeObjectRequest);
            System.out.println("Printing bytes retrieved.");
            displayTextInputStream(objectPortion.getObjectContent());

            // Get an entire object, overriding the specified response headers, and print the object's content.
            ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides()
                    .withCacheControl("No-cache")
                    .withContentDisposition("attachment; filename=example.txt");
            GetObjectRequest getObjectRequestHeaderOverride = new GetObjectRequest(bucketName, key)
                    .withResponseHeaders(headerOverrides);
            headerOverrideObject = s3Client.getObject(getObjectRequestHeaderOverride);
            displayTextInputStream(headerOverrideObject.getObjectContent());
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        } finally {
            // To ensure that the network connection doesn't remain open, close any open input streams.
            if (fullObject != null) {
                fullObject.close();
            }
            if (objectPortion != null) {
                objectPortion.close();
            }
            if (headerOverrideObject != null) {
                headerOverrideObject.close();
            }
        }
    }

    private static void displayTextInputStream(InputStream input) throws IOException {
        // Read the text input stream one line at a time and display each line.
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println();
    }
}
</code>```

The code above you can see that there is no close for AmazonS3 client.
It is created by the AwsClientBuilder.

So.  when you creat the aws s3 client by AwsClientBuilder then it is no needed for close? why is it?

Thanks.

Body:
Below is official aws sdk source regarding getting s3 object.

https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java

public class GetObjectData {

public static void main(String[] args) {
    String bucketName = args[0];
    String keyName = args[1];
    String path = args[2];

    ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create();
    Region region = Region.US_EAST_1;
    S3Client s3 = S3Client.builder()
        .region(region)
        .credentialsProvider(credentialsProvider)
        .build();

    getObjectBytes(s3,bucketName,keyName, path);
    s3.close();
}

// snippet-start:[s3.java2.getobjectdata.main]
public static void getObjectBytes (S3Client s3, String bucketName, String keyName, String path) {

    try {
        GetObjectRequest objectRequest = GetObjectRequest
            .builder()
            .key(keyName)
            .bucket(bucketName)
            .build();

        ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
        byte[] data = objectBytes.asByteArray();

        // Write the data to a local file.
        File myFile = new File(path );
        OutputStream os = new FileOutputStream(myFile);
        os.write(data);
        System.out.println("Successfully obtained bytes from an S3 object");
        os.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (S3Exception e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
}
// snippet-end:[s3.java2.getobjectdata.main]
}

As you can see, there is s3.close in the middle of the code block.

However, I have the second code which does not close the s3 client in the official aws sdk as below.

the code below can be seen in the link here https://docs.aws.amazon.com/AmazonS3/latest/userguide/download-objects.htm

public class GetObject2 {

    public static void main(String[] args) throws IOException {
        Regions clientRegion = Regions.DEFAULT_REGION;
        String bucketName = "*** Bucket name ***";
        String key = "*** Object key ***";

        S3Object fullObject = null, objectPortion = null, headerOverrideObject = null;
        try {
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new ProfileCredentialsProvider())
                    .build();

            // Get an object and print its contents.
            System.out.println("Downloading an object");
            fullObject = s3Client.getObject(new GetObjectRequest(bucketName, key));
            System.out.println("Content-Type: " + fullObject.getObjectMetadata().getContentType());
            System.out.println("Content: ");
            displayTextInputStream(fullObject.getObjectContent());

            // Get a range of bytes from an object and print the bytes.
            GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, key)
                    .withRange(0, 9);
            objectPortion = s3Client.getObject(rangeObjectRequest);
            System.out.println("Printing bytes retrieved.");
            displayTextInputStream(objectPortion.getObjectContent());

            // Get an entire object, overriding the specified response headers, and print the object's content.
            ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides()
                    .withCacheControl("No-cache")
                    .withContentDisposition("attachment; filename=example.txt");
            GetObjectRequest getObjectRequestHeaderOverride = new GetObjectRequest(bucketName, key)
                    .withResponseHeaders(headerOverrides);
            headerOverrideObject = s3Client.getObject(getObjectRequestHeaderOverride);
            displayTextInputStream(headerOverrideObject.getObjectContent());
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        } finally {
            // To ensure that the network connection doesn't remain open, close any open input streams.
            if (fullObject != null) {
                fullObject.close();
            }
            if (objectPortion != null) {
                objectPortion.close();
            }
            if (headerOverrideObject != null) {
                headerOverrideObject.close();
            }
        }
    }

    private static void displayTextInputStream(InputStream input) throws IOException {
        // Read the text input stream one line at a time and display each line.
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println();
    }
}

The code above you can see that there is no close for AmazonS3 client.
It is created by the AwsClientBuilder.

So.  when you creat the aws s3 client by AwsClientBuilder then it is no needed for close? why is it?

Thanks.


问:
node-opcua crawler, Transaction has timed out
I'm trying to get all element in plc by using crawler.read method in node-opcua library. At first I was getting TypeError: Cannot read properties of undefined (reading '0') at /node_modules/node-opcua-client-crawler/dist/node_crawler_base.js:27:49. When I look at node_crawler_base.js file I realized that in catch it says: Transaction has timed out (60000 ms). I believe it is giving me this undefined (reading '0') error because session.read is time out. I tried several ways to increase 60000 ms but none of them work. Here is my current code:

const items = [];
const client = opcua.OPCUAClient.create({
    keepSessionAlive: true,
    requestedSessionTimeout: 20000000,
    requestedPublishingInterval: 1000,
    requestedMaxKeepAliveCount: 2,
    requestedLifetimeCount: 100,
    maxNotificationsPerPublish: 10,
    publishingEnabled: true,
    priority: 10,
});
await client.connect(url);
const session = await client.createSession(userInfo);
const crawler = new NodeCrawler(session);
crawler.on("browsed", function (element) {
    items.push(element);
  }
});
await crawler.read(node.topic);
```

Is there a way to increase this time out value?

Body:
I'm trying to get all element in plc by using crawler.read method in node-opcua library. At first I was getting TypeError: Cannot read properties of undefined (reading '0') at /node_modules/node-opcua-client-crawler/dist/node_crawler_base.js:27:49. When I look at node_crawler_base.js file I realized that in catch it says: Transaction has timed out (60000 ms). I believe it is giving me this undefined (reading '0') error because session.read is time out. I tried several ways to increase 60000 ms but none of them work. Here is my current code:

const items = [];
const client = opcua.OPCUAClient.create({
    keepSessionAlive: true,
    requestedSessionTimeout: 20000000,
    requestedPublishingInterval: 1000,
    requestedMaxKeepAliveCount: 2,
    requestedLifetimeCount: 100,
    maxNotificationsPerPublish: 10,
    publishingEnabled: true,
    priority: 10,
});
await client.connect(url);
const session = await client.createSession(userInfo);
const crawler = new NodeCrawler(session);
crawler.on("browsed", function (element) {
    items.push(element);
  }
});
await crawler.read(node.topic);

Is there a way to increase this time out value?


问:
How do I publish a Widget to the App Store?
I've been publishing apps to the App Store for some time. But today I'm going to publish a widget which is in a different target within the same project.

I tried to submit as usual, but the widget is not visible.
So the question is, how does one publish an app to the App Store with multiple targets? In this case, an app with a widget.


问:
Override VirtualizationMode default value on TreeViewItems
I want the default value of VirtualizingPanel.VirtualizationMode to Recycling, mainly on TreeViewItems. It may be something simple I'm missing but I've tried all these:

```<code><TreeView VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.CacheLengthUnit="Pixel"
          VirtualizingPanel.VirtualizationMode="Recycling"/>

<Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource {x:Type TreeViewItem}}">
    <Setter Property="VirtualizingPanel.VirtualizationMode" Value="Recycling" />
</Style>
</code>```
```<code>static MainWindow()
{
    VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(
        typeof(VirtualizingPanel), new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
    VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(
        typeof(MainWindow), new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
    VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(
        typeof(TreeViewItem), new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
    VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(
        typeof(VirtualizingStackPanel), new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
}
</code>```

But it all seems to do nothing. According to the Xaml live property explorer.

How to reproduce:

Download and run the source code from github in Visual Studio in debug mode.

Open the "Live Visual Tree" window in Visual Studio and find a VirtualizingStackPanel under some TreeViewItem.

Right-click, select properties, and find the VirualizationMode property.

Body:
I want the default value of VirtualizingPanel.VirtualizationMode to Recycling, mainly on TreeViewItems. It may be something simple I'm missing but I've tried all these:

<TreeView VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.CacheLengthUnit="Pixel"
          VirtualizingPanel.VirtualizationMode="Recycling"/>

static MainWindow()
{
    VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(
        typeof(VirtualizingPanel), new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
    VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(
        typeof(MainWindow), new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
    VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(
        typeof(TreeViewItem), new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
    VirtualizingPanel.VirtualizationModeProperty.OverrideMetadata(
        typeof(VirtualizingStackPanel), new FrameworkPropertyMetadata(VirtualizationMode.Recycling));
}

But it all seems to do nothing. According to the Xaml live property explorer.

How to reproduce:

Download and run the source code from github in Visual Studio in debug mode.

Open the "Live Visual Tree" window in Visual Studio and find a VirtualizingStackPanel under some TreeViewItem.

Right-click, select properties, and find the VirualizationMode property.


问:
C# FileSystemWatcher.Renamed NoRename not in context
I am writing a hotfolder application to pull files as they enter an FTP site and move them to another server. On large file the file is name file.FilePart until complete so I need to catch the file rename. I am using FileSystemWatcher to do this and it works fine except for the Rename. I am using VS 2022 V 17.4.3, .Net 7.0 and C# 11.0 but I get Name 'NoRename' not in the current context. Thisis driving me nuts. Anybody have an idea what I am doing wrong.

I have tried uaing NoRename and Rename but neither works, I have changed .net version and C# version and updated VS. Here is the code up to the error.

```<code>using System;
using System.Collections;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Renci.SshNet;
using Renci.SshNet.Sftp;

namespace Hotfolder1
{
    class Program
    {
        static void Main()
        {

            string HFBase = @"c:\FTP";
            FileSystemWatcher watcher = new FileSystemWatcher(HFBase);
            watcher.IncludeSubdirectories = true;
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
            watcher.Created += new FileSystemEventHandler(FileCreated);
            watcher.Renamed += new RenamedEventHandler(*NoRename*);
            watcher.EnableRaisingEvents = true;
</code>```

`

Body:
I am writing a hotfolder application to pull files as they enter an FTP site and move them to another server. On large file the file is name file.FilePart until complete so I need to catch the file rename. I am using FileSystemWatcher to do this and it works fine except for the Rename. I am using VS 2022 V 17.4.3, .Net 7.0 and C# 11.0 but I get Name 'NoRename' not in the current context. Thisis driving me nuts. Anybody have an idea what I am doing wrong.

I have tried uaing NoRename and Rename but neither works, I have changed .net version and C# version and updated VS. Here is the code up to the error.

using System;
using System.Collections;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Renci.SshNet;
using Renci.SshNet.Sftp;

namespace Hotfolder1
{
    class Program
    {
        static void Main()
        {

            string HFBase = @"c:\FTP";
            FileSystemWatcher watcher = new FileSystemWatcher(HFBase);
            watcher.IncludeSubdirectories = true;
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
            watcher.Created += new FileSystemEventHandler(FileCreated);
            watcher.Renamed += new RenamedEventHandler(*NoRename*);
            watcher.EnableRaisingEvents = true;

`


问:
How to fix Next-Auth auth?
next-auth doesn't work at all, in Safari browser when I want to sigin it redirects me from localhost:3000/login to localhost:3000/api/auth/error which is error page in next, in google it redirects me from localhost:3000/login to localhost:3000/login? and it's not working, user not authenticated. In console it says Client_fetch_error in documentation this error means that NEXTAUTH_URL not defined but I defined it. Didn't find any solutions. So maybe you can help. Neither credentials, google and GitHub auth doesn't work

Here is [...nextauth].ts

```<code>import NextAuth, {NextAuthOptions} from "next-auth";
import GoogleProvider from 'next-auth/providers/google'
import GithubProvider from 'next-auth/providers/github'
import {MongoDBAdapter} from "@next-auth/mongodb-adapter";
import clientPromise, {loginUser} from "../../../utils/mongodb";
import CredentialsProvider from 'next-auth/providers/credentials'

export const authOptions: NextAuthOptions ={
providers:[
    GoogleProvider({
        clientId: process.env.GOOGLE_ID,
        clientSecret: process.env.GOOGLE_SECRET
    }),
    GithubProvider({
        clientId: process.env.GITHUB_ID,
        clientSecret: process.env.GITHUB_SECRET
    }),
    CredentialsProvider({
        name: 'Credentials',
        credentials:{},
        async authorize(credentials, req) {
            // @ts-ignore
            const { email, password } = credentials
            // @ts-ignore
            const {user, error} = await loginUser(email, password)
            if (error) throw new Error (error)
            if (user) {
                return user
            } else {
                return null
            }
        }
    })
],
adapter: MongoDBAdapter(clientPromise),
secret: process.env.NEXTAUTH_SECRET,
session:{
    strategy: "jwt"
},
pages: {
    signIn: "/login"
}
}

export default NextAuth(authOptions)
</code>```

Here is my Login component where I use signIn functions

```<code>import React, {useState} from 'react';
import styles from "../../styles/Login.module.scss";
import LayoutAuth from "../../layouts/LayoutAuth";
import Link from "next/link";
import Image from "next/image";
import google from "./../../public/asset/google.svg"
import git from "./../../public/asset/github.svg"
import {signIn} from "next-auth/react"
import {useRouter} from "next/router";

const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const router = useRouter()

async function handleLogin() {
    if (email && password) {
        const status = await signIn('credentials', {
            redirect: false,
            email: email,
            password: password,
            callbackUrl: "/"
        })
        console.log(status)
        setEmail("")
        setPassword("")
        if (status?.ok) {
            // @ts-ignore
            router.push(status?.url)
        }
    } else {
        alert("Заповніть всі поля")
    }

}

const handleGoogleSignIn = async () => {
    const res = await signIn('google', {callbackUrl: "http://localhost:3000"})
    console.log(res)
}

async function handleGitHubSignIn() {
    await signIn('github', {callbackUrl: "http://localhost:3000"})
}

return (
    <LayoutAuth>
        <div className={styles.wrap}>
            <div className={styles.title}>
                <h2>Авторизція</h2>
                <p>Ввійдіть для того щоб використовувати всі можливості нашого сайту</p>
            </div>
            <form className={styles.inputs}>
                <input onChange={(e) => setEmail(e.target.value)} value={email} className={styles.titleInput}
                       type="text" placeholder={"Введіть e-mail"}/>
                <input onChange={(e) => setPassword(e.target.value)} value={password} className={styles.titleInput}
                       type="password" placeholder={"Пароль"}/>
                <button className={styles.button} onClick={handleLogin}><h2>Ввійти</h2></button>
                <button className={styles.buttonGoogle} onClick={handleGoogleSignIn}><h2>Ввійти за допомогою
                    Google</h2><Image src={google} alt={"google"} width={20} height={20}/></button>
                <button className={styles.buttonGit} onClick={handleGitHubSignIn}><h2>Ввійти за допомогою
                    GitHub </h2><Image src={git} alt={"git"} width={20} height={20}/></button>
            </form>
            <div className={styles.desc}>
                <p>Ще не маєте акаунту?</p>
                <Link href={"/registration"}>
                    <p className={styles.ptag}>Зареєструйтесь</p>
                </Link>
            </div>
        </div>
    </LayoutAuth>
);
 };

export default Login;
</code>```

fixed by adding e.preventDafault() before signIn function in Login component. Can anybody explain why do I need to add preventDefault?

Title: How to fix Next-Auth auth?

Body:
next-auth doesn't work at all, in Safari browser when I want to sigin it redirects me from localhost:3000/login to localhost:3000/api/auth/error which is error page in next, in google it redirects me from localhost:3000/login to localhost:3000/login? and it's not working, user not authenticated. In console it says Client_fetch_error in documentation this error means that NEXTAUTH_URL not defined but I defined it. Didn't find any solutions. So maybe you can help. Neither credentials, google and GitHub auth doesn't work

Here is [...nextauth].ts

import NextAuth, {NextAuthOptions} from "next-auth";
import GoogleProvider from 'next-auth/providers/google'
import GithubProvider from 'next-auth/providers/github'
import {MongoDBAdapter} from "@next-auth/mongodb-adapter";
import clientPromise, {loginUser} from "../../../utils/mongodb";
import CredentialsProvider from 'next-auth/providers/credentials'

export const authOptions: NextAuthOptions ={
providers:[
    GoogleProvider({
        clientId: process.env.GOOGLE_ID,
        clientSecret: process.env.GOOGLE_SECRET
    }),
    GithubProvider({
        clientId: process.env.GITHUB_ID,
        clientSecret: process.env.GITHUB_SECRET
    }),
    CredentialsProvider({
        name: 'Credentials',
        credentials:{},
        async authorize(credentials, req) {
            // @ts-ignore
            const { email, password } = credentials
            // @ts-ignore
            const {user, error} = await loginUser(email, password)
            if (error) throw new Error (error)
            if (user) {
                return user
            } else {
                return null
            }
        }
    })
],
adapter: MongoDBAdapter(clientPromise),
secret: process.env.NEXTAUTH_SECRET,
session:{
    strategy: "jwt"
},
pages: {
    signIn: "/login"
}
}

export default NextAuth(authOptions)

Here is my Login component where I use signIn functions

import React, {useState} from 'react';
import styles from "../../styles/Login.module.scss";
import LayoutAuth from "../../layouts/LayoutAuth";
import Link from "next/link";
import Image from "next/image";
import google from "./../../public/asset/google.svg"
import git from "./../../public/asset/github.svg"
import {signIn} from "next-auth/react"
import {useRouter} from "next/router";

const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const router = useRouter()

async function handleLogin() {
    if (email && password) {
        const status = await signIn('credentials', {
            redirect: false,
            email: email,
            password: password,
            callbackUrl: "/"
        })
        console.log(status)
        setEmail("")
        setPassword("")
        if (status?.ok) {
            // @ts-ignore
            router.push(status?.url)
        }
    } else {
        alert("Заповніть всі поля")
    }

}

const handleGoogleSignIn = async () => {
    const res = await signIn('google', {callbackUrl: "http://localhost:3000"})
    console.log(res)
}

async function handleGitHubSignIn() {
    await signIn('github', {callbackUrl: "http://localhost:3000"})
}

return (
    <LayoutAuth>

Авторизція

Ввійдіть для того щоб використовувати всі можливості нашого сайту

            <form className={styles.inputs}>
                <input onChange={(e) => setEmail(e.target.value)} value={email} className={styles.titleInput}
                       type="text" placeholder={"Введіть e-mail"}/>
                <input onChange={(e) => setPassword(e.target.value)} value={password} className={styles.titleInput}
                       type="password" placeholder={"Пароль"}/>
                <button className={styles.button} onClick={handleLogin}>
Ввійти
</button>
                <button className={styles.buttonGoogle} onClick={handleGoogleSignIn}>
Ввійти за допомогою
                    Google
<Image src={google} alt={"google"} width={20} height={20}/></button>
                <button className={styles.buttonGit} onClick={handleGitHubSignIn}>
Ввійти за допомогою
                    GitHub
<Image src={git} alt={"git"} width={20} height={20}/></button>
            </form>

Ще не маєте акаунту?

                <Link href={"/registration"}>

Зареєструйтесь

                </Link>

    </LayoutAuth>
);
 };

export default Login;

fixed by adding e.preventDafault() before signIn function in Login component. Can anybody explain why do I need to add preventDefault?


问:
Not understanding control flow of JavaScript WebSocket (using React)
Using web sockets in React (TypeScript), I'm a bit confused over the control flow of the web socket object.

The WebSocket object requires the URL to the web socket. It presumably connects immediately.

But only after having created the object and presumably connected to the web socket, the onopen and onmessage events are configured. This is how every single tutorial and explanation I've seen online does things.

What I don't really understand, is why it works. In my test code (shown below), it works fine, and it always logs in properly and always receives the message. But it seems to me that there is a built-in race condition that sooner or later is going to show itself.

I've looked online for ways to configure a WebSocket object but connect to it later setting the parameters, but found nothing.

There are two reasons I'm asking.

One is that I don't understand how this code avoids a race condition where the connection is successful before the onopen event is configured.

The other is that I would like to keep the web socket object somewhere central (using atoms in Jotai, if it matters), but I don't necessarily want to connect to the web socket at the same time that I create the object. In other words, I would very much like to create the object first, and then connect with a connect function or some equivalent. I've found no such thing to be available in JavaScript's WebSocket.

Can someone please explain to me what I'm missing? Thanks in advance.

```<code>    const webSocket = new WebSocket(constants.WS_URI);
    webSocket.onopen = (event) => {
      webSocket.send(
        JSON.stringify({
          command: "login",
          token: "Bearer " + user.token,
        })
      );
    };
    webSocket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log("**" + data.username + "**: " + data.message + "\n");
    };
</code>```

Body:
Using web sockets in React (TypeScript), I'm a bit confused over the control flow of the web socket object.

The WebSocket object requires the URL to the web socket. It presumably connects immediately.

But only after having created the object and presumably connected to the web socket, the onopen and onmessage events are configured. This is how every single tutorial and explanation I've seen online does things.

What I don't really understand, is why it works. In my test code (shown below), it works fine, and it always logs in properly and always receives the message. But it seems to me that there is a built-in race condition that sooner or later is going to show itself.

I've looked online for ways to configure a WebSocket object but connect to it later setting the parameters, but found nothing.

There are two reasons I'm asking.

One is that I don't understand how this code avoids a race condition where the connection is successful before the onopen event is configured.

The other is that I would like to keep the web socket object somewhere central (using atoms in Jotai, if it matters), but I don't necessarily want to connect to the web socket at the same time that I create the object. In other words, I would very much like to create the object first, and then connect with a connect function or some equivalent. I've found no such thing to be available in JavaScript's WebSocket.

Can someone please explain to me what I'm missing? Thanks in advance.

    const webSocket = new WebSocket(constants.WS_URI);
    webSocket.onopen = (event) => {
      webSocket.send(
        JSON.stringify({
          command: "login",
          token: "Bearer " + user.token,
        })
      );
    };
    webSocket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log("**" + data.username + "**: " + data.message + "\n");
    };


问:
How to do stemming in text mining Slovene texts in R
I am text-mining a series of interviews I performed in the Slovene language. After I transformed the vector file into a corpus, I tried this command to stem the words:

```<code>pupils<- tm_map(pupils, stemDocument(pupils, language = "slovene"))
</code>```

However, the response was this:

Error in UseMethod("stemDocument", x) :
no applicable method for 'stemDocument' applied to an object of class "c('VCorpus', 'Corpus')"

I could perform the intended text mining operations (ngrams) without the stemming process, but they will not be completely legit. I saw the post where a gentleman asked about stemming in Italian and was instructed to use the SnowballC package. Unfortunately, SnowballC does not incorporate Slovene, so there's that.

I will appreciate any help. Thank you.
Janez

Body:
I am text-mining a series of interviews I performed in the Slovene language. After I transformed the vector file into a corpus, I tried this command to stem the words:

pupils<- tm_map(pupils, stemDocument(pupils, language = "slovene"))

However, the response was this:

Error in UseMethod("stemDocument", x) :
no applicable method for 'stemDocument' applied to an object of class "c('VCorpus', 'Corpus')"

I could perform the intended text mining operations (ngrams) without the stemming process, but they will not be completely legit. I saw the post where a gentleman asked about stemming in Italian and was instructed to use the SnowballC package. Unfortunately, SnowballC does not incorporate Slovene, so there's that.

I will appreciate any help. Thank you.
Janez


问:
I can't connect one spring container and another with mysql using docker run
I am trying to connect my springboot application with my mysql database but without success. I have tried putting them on the same network, but the springboot container closes with the following error.

```<code>com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
</code>```

docker commands

```<code>docker build -t frarm2014/spring-boot3-rest:v1 .

docker network create spring-network

docker run -d -p 3306:3306 --name mysql-springboot3 --network spring-network -e MYSQL_ROOT_PASSWORD=ThePassword -e MYSQL_USER=springuser -e MYSQL_PASSWORD=ThePassword -e MYSQL_DATABASE=db_example mysql:5.7
docker run -d -p 8080:8080 --name rest-springboot3 --network spring-network frarm2014/spring-boot3-rest:v1
</code>```

application properties

```<code>loggin.level.org.springframework=debug
management.endpoints.web.exposure.include=*

server.port=8080
spring.datasource.url=jdbc:mysql://mysql-springboot3:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update
</code>```

When I run the application from the jar or from vscode, I can make calls to the mysql container created with the docker run

Body:
I am trying to connect my springboot application with my mysql database but without success. I have tried putting them on the same network, but the springboot container closes with the following error.

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

docker commands

docker build -t frarm2014/spring-boot3-rest:v1 .

docker network create spring-network

docker run -d -p 3306:3306 --name mysql-springboot3 --network spring-network -e MYSQL_ROOT_PASSWORD=ThePassword -e MYSQL_USER=springuser -e MYSQL_PASSWORD=ThePassword -e MYSQL_DATABASE=db_example mysql:5.7
docker run -d -p 8080:8080 --name rest-springboot3 --network spring-network frarm2014/spring-boot3-rest:v1

application properties

loggin.level.org.springframework=debug
management.endpoints.web.exposure.include=*

server.port=8080
spring.datasource.url=jdbc:mysql://mysql-springboot3:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update

When I run the application from the jar or from vscode, I can make calls to the mysql container created with the docker run


问:
How do I integrate the BTCpay server api to my MERN app
I am creating an app that requires users to sign up, link their wallet and then be able to make crypto transactions between them and another user. I am using BTCpay for this but am unsure on how to link the api to my MERN app and how to allow users to link their wallets and create invoices</p>


问:
React PDF: Annotations for a rotated PDF document do not align
When I use react-pdf to render a rotated pdf document containing links, the annotation layer renders with a rotation different from the document. Therefore, the links do not align.

I have deployed an example showing that the highlighted links do not align with the pdf's links.

Deployed example

Github Repo for the example

Here's an image of what I see:

And here's the code I am using to render the PDF:

```<code>import { Document, Page } from 'react-pdf/dist/esm/entry.parcel2'
import 'react-pdf/dist/esm/Page/AnnotationLayer.css'

export const Root = () => {
    return (
        <Document file="sample-rotated.pdf">
            <Page pageNumber={1} renderTextLayer={false} renderAnnotationLayer={true} />
            <Page pageNumber={2} renderTextLayer={false} renderAnnotationLayer={true} />
        </Document>
    )
}
</code>```

Is this a bug or is there something I'm missing with regard to how I ought to be rendering rotated PDFs? If it's a bug, I'll happily make an issue for it.

As a workaround, I'm able to manually rotate the annotation layer itself so everything matches up, but I can't help but feel I'm missing something here.

Body:
When I use react-pdf to render a rotated pdf document containing links, the annotation layer renders with a rotation different from the document. Therefore, the links do not align.

I have deployed an example showing that the highlighted links do not align with the pdf's links.

Deployed example

Github Repo for the example

Here's an image of what I see:

And here's the code I am using to render the PDF:

import { Document, Page } from 'react-pdf/dist/esm/entry.parcel2'
import 'react-pdf/dist/esm/Page/AnnotationLayer.css'

export const Root = () => {
    return (
        <Document file="sample-rotated.pdf">
            <Page pageNumber={1} renderTextLayer={false} renderAnnotationLayer={true} />
            <Page pageNumber={2} renderTextLayer={false} renderAnnotationLayer={true} />
        </Document>
    )
}

Is this a bug or is there something I'm missing with regard to how I ought to be rendering rotated PDFs? If it's a bug, I'll happily make an issue for it.

As a workaround, I'm able to manually rotate the annotation layer itself so everything matches up, but I can't help but feel I'm missing something here.


问:
problem factor outcome with decision tree with R
Data: https://www.kaggle.com/datasets/shravan3273/credit-approval

I want to create a decision tree with "default" as a dependent variable and "checking balance","personal_status" and "job" as independent variables.

The code I'm trying to use:

```<code>Y <- credit%>%select(default)
X <- credit%>%select(checking_balance,personal_status,job)

X$checking_balance<-as.factor(X$checking_balance)
X$personal_status<-as.factor(X$personal_status)
X$job<-as.factor(X$job)
Y$default<-as.factor(Y$default)

model<-C50::C5.0(X,Y,rules=TRUE)
</code>```

Result:

```<code>Error: C5.0 models require a factor outcome
</code>```

What am I doing wrong?

Body:
Data: https://www.kaggle.com/datasets/shravan3273/credit-approval

I want to create a decision tree with "default" as a dependent variable and "checking balance","personal_status" and "job" as independent variables.

The code I'm trying to use:

Y <- credit%>%select(default)
X <- credit%>%select(checking_balance,personal_status,job)

X$checking_balance<-as.factor(X$checking_balance)
X$personal_status<-as.factor(X$personal_status)
X$job<-as.factor(X$job)
Y$default<-as.factor(Y$default)

model<-C50::C5.0(X,Y,rules=TRUE)

Result:

Error: C5.0 models require a factor outcome

What am I doing wrong?


问:
Cannot input text into a React search bar
Update - solved, Thanks Konrad! I had text that was blocking the search bar, adding pointer-events: none; to the text fixed my issue.

I am learning react and trying to create a search bar. Right now, I just want to have the user's input to the search bar be logged to the console or pop up in a message when they submit text.
However, I cannot even enter text into my search bar right now.

I have tried looking at the react documentation (https://reactjs.org/docs/forms.html) and (https://reactjs.org/docs/state-and-lifecycle.html) and I think the issue has something to do with setting state but I am not sure where I am going wrong. I saw other people on stack overflow had this issue, but it was fixed for them when they added 'value=' to their <in bar which did not work for me.

Thank you for reading!

```<code>
import React from 'react'
import './SearchBar.css'

class SearchBar extends React.Component { //
  constructor(props){
    super(props);

    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
   }

   handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A value was submitted: ' + this.state.value);
    event.preventDefault();
  }

    render() {
      return (
        <div className='Container'>
          <form className='SearchBar' onSubmit={this.handleSubmit}>
            <input type="text" placeholder='Enter the link to your IMDB profile' value={this.state.value} onChange={this.handleChange} />
          </form>
        <p className='Warning'>Make sure your imdb profile is set to public!</p>
        </div>
      );
    }
  }

export default SearchBar

</code>```

As pointed out by Konrad below, the isolated component works fine, so there must be some issue in my integration. When I comment out my App.css file, it also works fine, so it is some issue in those that is causing me an issue, does anyone know what I need to add?
Here is my app.css:

```<code>.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    height: 20vmin;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(20px + 2vmin);
  color: white;
}

.Wrapped{
  position:absolute;
  left: 40%;
  height: 75%;
  font-size: 75px;
  transform: rotate(45deg);
  font-family: "Apple Chancery", cursive;
  color:deeppink
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

</code>```

and my app.js:

```<code>import logo from './Logo_2016.png';
import './App.css';
import SearchBar from './components/SearchBar';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1 className='Wrapped'> Wrapped </h1>
        <img src={logo} className="App-logo" alt="logo" />
        <p> Welcome! </p>
        <SearchBar/>
      </header>
    </div>
  );
}

export default App;

</code>```

Body:
Update - solved, Thanks Konrad! I had text that was blocking the search bar, adding pointer-events: none; to the text fixed my issue.

I am learning react and trying to create a search bar. Right now, I just want to have the user's input to the search bar be logged to the console or pop up in a message when they submit text.
However, I cannot even enter text into my search bar right now.

I have tried looking at the react documentation (https://reactjs.org/docs/forms.html) and (https://reactjs.org/docs/state-and-lifecycle.html) and I think the issue has something to do with setting state but I am not sure where I am going wrong. I saw other people on stack overflow had this issue, but it was fixed for them when they added 'value=' to their <in bar which did not work for me.

Thank you for reading!

import React from 'react'
import './SearchBar.css'

class SearchBar extends React.Component { //
  constructor(props){
    super(props);

    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
   }

   handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A value was submitted: ' + this.state.value);
    event.preventDefault();
  }

    render() {
      return (

          <form className='SearchBar' onSubmit={this.handleSubmit}>
            <input type="text" placeholder='Enter the link to your IMDB profile' value={this.state.value} onChange={this.handleChange} />
          </form>

Make sure your imdb profile is set to public!

      );
    }
  }

export default SearchBar

As pointed out by Konrad below, the isolated component works fine, so there must be some issue in my integration. When I comment out my App.css file, it also works fine, so it is some issue in those that is causing me an issue, does anyone know what I need to add?
Here is my app.css:

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    height: 20vmin;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(20px + 2vmin);
  color: white;
}

.Wrapped{
  position:absolute;
  left: 40%;
  height: 75%;
  font-size: 75px;
  transform: rotate(45deg);
  font-family: "Apple Chancery", cursive;
  color:deeppink
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

and my app.js:

import logo from './Logo_2016.png';
import './App.css';
import SearchBar from './components/SearchBar';

function App() {
  return (

 Wrapped

 Welcome!

        <SearchBar/>

  );
}

export default App;


问:
Unable to use GitHub personal access token to login to PyCharm. How do I fix this error?
I want to login to GitHub on PyCharm, so I generated a new personal access token and tried entering it. PyCharm gives me the following error as seen below:

Invalid Authentication Data. Connection refused: no further information

I first tried logging in through the IDE directly, which didn't work. I found numerous solutions online to use the personal access token to log in, but after trying many times it just doesn't seem to work.

Does anyone have an idea on how to fix this?