问:
Add Custom Header to Xamarin WebViewClient
Though there were already some threads on issues like this a few years ago (e.g. Add Authorization header to all requests in Xamarin Forms Android WebView), I am wondering now if there were a solid solution meanwhile to add custom headers to all reqests (GET, PUT, POST...) while using WebFormClient with Xamarin.

ShouldInterceptRequest, ShouldOverrideUrlLoading methods overridden to add custom headers but the headers were not added:

```<code>public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest urlResource)
{
    if (urlResource.RequestHeaders != null && !urlResource.RequestHeaders.ContainsKey("X-LPPTAgent"))
    {
        urlResource.RequestHeaders.Add("key", "value");
    }

    return base.ShouldInterceptRequest(view, urlResource);
}

public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
    WebView.SetWebContentsDebuggingEnabled(true);

    if (request.RequestHeaders != null && !request.RequestHeaders.ContainsKey("X-LPPTAgent"))
    {
        request.RequestHeaders.Add("key", "value");
    }
    return base.ShouldOverrideUrlLoading(view, request);
}
</code>```

Another version of ShouldInterceptRequest - this works, but only for GET requests:

```<code>public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest urlResource)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add("key", "value");

    var requestMessage = GetRequestMessage(urlResource.Url.ToString(), urlResource.Method);

    var result = client.SendAsync(requestMessage).Result;
    var stream = result.Content.ReadAsStreamAsync().Result;

    var contentType = result.Content.Headers.ContentType;
    if (contentType != null)
    {
        return new WebResourceResponse(contentType.MediaType, contentType.CharSet, (int)result.StatusCode, result.ReasonPhrase, urlResource.RequestHeaders, stream);
    }
    return new WebResourceResponse(string.Empty, string.Empty, (int)result.StatusCode, result.ReasonPhrase, urlResource.RequestHeaders, stream);
}
</code>```

since body cannot be sent with as it is not available in WebResourcerequest.

Body:
Though there were already some threads on issues like this a few years ago (e.g. Add Authorization header to all requests in Xamarin Forms Android WebView), I am wondering now if there were a solid solution meanwhile to add custom headers to all reqests (GET, PUT, POST...) while using WebFormClient with Xamarin.

ShouldInterceptRequest, ShouldOverrideUrlLoading methods overridden to add custom headers but the headers were not added:

public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest urlResource)
{
    if (urlResource.RequestHeaders != null && !urlResource.RequestHeaders.ContainsKey("X-LPPTAgent"))
    {
        urlResource.RequestHeaders.Add("key", "value");
    }

    return base.ShouldInterceptRequest(view, urlResource);
}

public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
    WebView.SetWebContentsDebuggingEnabled(true);

    if (request.RequestHeaders != null && !request.RequestHeaders.ContainsKey("X-LPPTAgent"))
    {
        request.RequestHeaders.Add("key", "value");
    }
    return base.ShouldOverrideUrlLoading(view, request);
}

Another version of ShouldInterceptRequest - this works, but only for GET requests:

public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest urlResource)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add("key", "value");

    var requestMessage = GetRequestMessage(urlResource.Url.ToString(), urlResource.Method);

    var result = client.SendAsync(requestMessage).Result;
    var stream = result.Content.ReadAsStreamAsync().Result;

    var contentType = result.Content.Headers.ContentType;
    if (contentType != null)
    {
        return new WebResourceResponse(contentType.MediaType, contentType.CharSet, (int)result.StatusCode, result.ReasonPhrase, urlResource.RequestHeaders, stream);
    }
    return new WebResourceResponse(string.Empty, string.Empty, (int)result.StatusCode, result.ReasonPhrase, urlResource.RequestHeaders, stream);
}

since body cannot be sent with as it is not available in WebResourcerequest.


来源: stackexchange

问:
Text isn't rendering on phones when using CanvasKit on Flutter Web
I build the Flutter Web app with canvaskit using flutter build web --web-renderer canvaskit command. However the text isn't rendering properly on some Android phones (e.g. OnePlus 5) using Chrome.

This is the expected result:

This is the actual result:

These are the logs:

```<code>[✓] Flutter (Channel stable, 3.3.9, on macOS 12.5 21G72 darwin-arm, locale en-EE)
    • Flutter version 3.3.9 on channel stable at /opt/homebrew/Caskroom/flutter/2.10.4/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision b8f7f1f986 (2 weeks ago), 2022-11-23 06:43:51 +0900
    • Engine revision 8f2221fbef
    • Dart version 2.18.5
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/karp/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.0.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14A400
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (2 available)
    • macOS (desktop) • macos  • darwin-arm64   • macOS 12.5 21G72 darwin-arm
    • Chrome (web)    • chrome • web-javascript • Google Chrome 108.0.5359.94

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I build the Flutter Web app with canvaskit using flutter build web --web-renderer canvaskit command. However the text isn't rendering properly on some Android phones (e.g. OnePlus 5) using Chrome.

This is the expected result:

This is the actual result:

These are the logs:

[✓] Flutter (Channel stable, 3.3.9, on macOS 12.5 21G72 darwin-arm, locale en-EE)
    • Flutter version 3.3.9 on channel stable at /opt/homebrew/Caskroom/flutter/2.10.4/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision b8f7f1f986 (2 weeks ago), 2022-11-23 06:43:51 +0900
    • Engine revision 8f2221fbef
    • Dart version 2.18.5
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/karp/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.0.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14A400
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (2 available)
    • macOS (desktop) • macos  • darwin-arm64   • macOS 12.5 21G72 darwin-arm
    • Chrome (web)    • chrome • web-javascript • Google Chrome 108.0.5359.94

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!


问:
Setting image width in table vs main text is not the same in RMarkdown
I have an image I'm putting in a table and the size is completely different for the HTML version compared to the PDF. I prefer the PDF version but don't know how to make the HTML get the same size as the image in the main text (the image in table is oto small).

```<code>---
title: "Untitled"
output:
  pdf_document: default
  html_document: default
date: "`r Sys.Date()`"
---

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

| Icônes    | Explications      | Exemple |
|:-------------|:-----------------------|:--------------------------|
| ![](../../../images/icones_Rstudio/cancel_2x.png){width="5%"}     | `R` est en exécution    | NA  |

main

![](../../../images/icones_Rstudio/cancel_2x.png){width="5%"}
</code>```

The image I used is here. How to make the image size in the table the same without changing the width parameter? I output both HTML and PDF from the same RMarkdown and I don't want to have 2 different files to set the size of these images... so in the end, the images in the HTML should be like the one in the PDF.

Body:
I have an image I'm putting in a table and the size is completely different for the HTML version compared to the PDF. I prefer the PDF version but don't know how to make the HTML get the same size as the image in the main text (the image in table is oto small).

---
title: "Untitled"
output:
  pdf_document: default
  html_document: default
date: "`r Sys.Date()`"
---

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

| Icônes    | Explications      | Exemple |
|:-------------|:-----------------------|:--------------------------|
| ![](../../../images/icones_Rstudio/cancel_2x.png){width="5%"}     | `R` est en exécution    | NA  |

main

![](../../../images/icones_Rstudio/cancel_2x.png){width="5%"}

The image I used is here. How to make the image size in the table the same without changing the width parameter? I output both HTML and PDF from the same RMarkdown and I don't want to have 2 different files to set the size of these images... so in the end, the images in the HTML should be like the one in the PDF.


问:
React-native-iap getAvailablePurchases() return empty array ios
I use auto renewal subscription with react-native-iap in my app
I need to check user has subscription on phone or not, for do this I use getAvailablePurchases()
like this

```<code>import * as RNIap from 'react-native-iap';

const init = await RNIap.initConnection();

    if (init) {
      await RNIap.getAvailablePurchases()
        .then((resp) => {
          const sortedAvailablePurchases = resp.sort(
            (a, b) => b.transactionDate - a.transactionDate,
          );

          const latestAvailableReceipt = sortedAvailablePurchases[0].transactionReceipt;

          RNIap.endConnection();
          return API({
            method: 'POST',
            url: '/subscription/check-receipt',
            data: {
              latestAvailableReceipt,
            },
          });
        })
        .catch((err) => {
          RNIap.endConnection();
        });
    }
</code>```

When I try to do this on my test device with sandbox, it works, but if I try to do this in the store build, I get the response - empty array

P.S I draw up subscription and then start testing

Body:
I use auto renewal subscription with react-native-iap in my app
I need to check user has subscription on phone or not, for do this I use getAvailablePurchases()
like this

import * as RNIap from 'react-native-iap';

const init = await RNIap.initConnection();

    if (init) {
      await RNIap.getAvailablePurchases()
        .then((resp) => {
          const sortedAvailablePurchases = resp.sort(
            (a, b) => b.transactionDate - a.transactionDate,
          );

          const latestAvailableReceipt = sortedAvailablePurchases[0].transactionReceipt;

          RNIap.endConnection();
          return API({
            method: 'POST',
            url: '/subscription/check-receipt',
            data: {
              latestAvailableReceipt,
            },
          });
        })
        .catch((err) => {
          RNIap.endConnection();
        });
    }

When I try to do this on my test device with sandbox, it works, but if I try to do this in the store build, I get the response - empty array

P.S I draw up subscription and then start testing


问:
"The maximum total size of all input parameters is 5242880 bytes." Error message when using BigQuery remote function
When calling a remote function on BigQuery, I get the following error The maximum total size of all input parameters is 5242880 bytes.. This error is undocumented (or my Googling ability is lacking). It is even more unexpected as the query that pop this error is as simple as it gets:

```<code>SELECT
  `remote_function`( payload ) AS results
FROM
  `source_table`
</code>```

The error is definitely on BQ's side, as no error is observed on the cloud-function called.

How to proceed on such issue, I'm guessing I hitting some kind of limit related to remote functions, but which one?

Body:
When calling a remote function on BigQuery, I get the following error The maximum total size of all input parameters is 5242880 bytes.. This error is undocumented (or my Googling ability is lacking). It is even more unexpected as the query that pop this error is as simple as it gets:

SELECT
  `remote_function`( payload ) AS results
FROM
  `source_table`

The error is definitely on BQ's side, as no error is observed on the cloud-function called.

How to proceed on such issue, I'm guessing I hitting some kind of limit related to remote functions, but which one?


问:
How to serialize complex object, which have a custom data type matrix?
I need to serialize a class object whose field is a custom data type matrix, like:

```<code>internal class MyClass
{
    private readonly MyMatrix[,] myField;
    public MyField { get => myField; }
}
</code>```

I am using json serialization code from here: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-7-0

```<code>    public static bool Save(MyClass o, string fileName)
    {
        _ = new JsonSerializerOptions { IncludeFields = true };
        try
        {
            byte[] jsonString = JsonSerializer.SerializeToUtf8Bytes(o);
            File.WriteAllBytes(fileName, jsonString);
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception in serialization: " + e.Message);
            return false;
        }
    }
</code>```

When trying to serialize an object of this class, I get an exception like this:
(https://i.stack.imgur.com/lhbbE.png)

I already understood that json supports a limited list of data types, but what should I do to serialize and then deserialize such an object?

Body:
I need to serialize a class object whose field is a custom data type matrix, like:

internal class MyClass
{
    private readonly MyMatrix[,] myField;
    public MyField { get => myField; }
}

I am using json serialization code from here: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-7-0

    public static bool Save(MyClass o, string fileName)
    {
        _ = new JsonSerializerOptions { IncludeFields = true };
        try
        {
            byte[] jsonString = JsonSerializer.SerializeToUtf8Bytes(o);
            File.WriteAllBytes(fileName, jsonString);
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception in serialization: " + e.Message);
            return false;
        }
    }

When trying to serialize an object of this class, I get an exception like this:
(https://i.stack.imgur.com/lhbbE.png)

I already understood that json supports a limited list of data types, but what should I do to serialize and then deserialize such an object?


问:
Angular *ngFor download to Excel using npm xlsx to create multiple sheets
I have a table that loops through in as many object arrays.
I want to save this as excel file using npm xlsx, every iteration to create new sheet in one excel file.

This is the sample code:

```<code><div class="row"  id="htmltable" #htmltable>
  <div class="col-md-3 shadow-sm" *ngFor="let receiptDetails of report" style="font-size: 0.8em; min-width: 280px; line-height: 1em;">

      <table class="table table-sm" >
        <tr>
          <th colspan="4" class="bg-secondary text-light" style="text-align: center;">Credit Payment</th>
        </tr>
        <tr>
          <th>Amount</th>
          <th>Mode</th>
          <th>Date</th>
          <th>Remarks</th>
        </tr>
        <tr *ngFor="let payment of receiptDetails?.creditPayment">
          <td>{{payment.amount | number : '1.2-2'}}</td>
          <td>{{payment.paymentMode}}</td>
          <td>{{payment.date | date}}</td>
          <td>{{payment.remarks}}</td>
        </tr>
      </table>

  </div>

</div>
</code>```

This is what I have done:

```<code>  exportExcel(): void  {
    this.fileName = this.reportType;
    let element = document.getElementById('htmltable');
    const ws: XLSX.WorkSheet =XLSX.utils.table_to_sheet(element);
    var wscols = [
      { wch: 20 },
      { wch: 20 },
      { wch: 15 },
      { wch: 15 },
    ];
    ws['!cols'] = wscols;
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, 'file.xlsx');
  }
</code>```

This generates one excel file and one single sheet.

Body:
I have a table that loops through in as many object arrays.
I want to save this as excel file using npm xlsx, every iteration to create new sheet in one excel file.

This is the sample code:

          Credit Payment

          Amount
          Mode
          Date
          Remarks

          {{payment.amount | number : '1.2-2'}}
          {{payment.paymentMode}}
          {{payment.date | date}}
          {{payment.remarks}}

This is what I have done:

  exportExcel(): void  {
    this.fileName = this.reportType;
    let element = document.getElementById('htmltable');
    const ws: XLSX.WorkSheet =XLSX.utils.table_to_sheet(element);
    var wscols = [
      { wch: 20 },
      { wch: 20 },
      { wch: 15 },
      { wch: 15 },
    ];
    ws['!cols'] = wscols;
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, 'file.xlsx');
  }

This generates one excel file and one single sheet.


问:
What's the fastest way to iterate through a dataset and perform calculation on rolling frames of data?
I wrote a script that logs bitcoin trading data on a 1-second interval. however I need to convert that back into minute-interval tick charts. in the end I'm trying to produce a 60-minute frame of minute-interval ohlcv data for every tick occurred.

Currently, I have something that works as following:

Sample dataset:
https://wetransfer.com/downloads/1a9d0304ecb9b5d83c6cdca3c5412eaf20221206185100/8033e0

```<code>klinelog
                    id     close  volume  unique_tick
------------------------------------------------------
0        1664553541000 19734.530   4.960         True
1        1664553542000 19734.530   4.960        False
2        1664553543000 19731.480   9.929         True
3        1664553544000 19731.480   9.929        False
4        1664553545000 19737.200   6.023         True
...                ...       ...     ...          ...
2678395  1667231936000 20388.820  10.606         True
2678396  1667231937000 20388.820  10.606        False
2678397  1667231938000 20388.430   5.729         True
2678398  1667231939000 20388.430   5.729        False
2678399  1667231940000 20388.220   6.613         True
</code>```
```<code>for i in range(len(klinelog)):
    # CHECK TO SEE IF THE SECOND DATA IS A UNIQUE TICK
    if klinelog['unique_tick'].iloc[i] == True:
        # GRAB 60MIN OF SECOND DATA
        try:
            kline_combined = klinelog.iloc[i:(i + 3600)].copy().drop('unique_tick', axis=1)
        except:
            continue

        # PROCESS INTO 60MIN OF MINUTE OHLCV DATA
        kline_combined['open'] = kline_combined['close']
        kline_combined['high'] = kline_combined['close']
        kline_combined['low'] = kline_combined['close']
        kline_combined = kline_combined.groupby(np.arange(len(kline_combined)) // 60).agg({'id': 'min', 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'})
</code>```

However since I'm dealing with months/years of data, this would take days to complete. is there any way to do this without iterating over the entire dataset?

Body:
I wrote a script that logs bitcoin trading data on a 1-second interval. however I need to convert that back into minute-interval tick charts. in the end I'm trying to produce a 60-minute frame of minute-interval ohlcv data for every tick occurred.

Currently, I have something that works as following:

Sample dataset:
https://wetransfer.com/downloads/1a9d0304ecb9b5d83c6cdca3c5412eaf20221206185100/8033e0

klinelog
                    id     close  volume  unique_tick
------------------------------------------------------
0        1664553541000 19734.530   4.960         True
1        1664553542000 19734.530   4.960        False
2        1664553543000 19731.480   9.929         True
3        1664553544000 19731.480   9.929        False
4        1664553545000 19737.200   6.023         True
...                ...       ...     ...          ...
2678395  1667231936000 20388.820  10.606         True
2678396  1667231937000 20388.820  10.606        False
2678397  1667231938000 20388.430   5.729         True
2678398  1667231939000 20388.430   5.729        False
2678399  1667231940000 20388.220   6.613         True

for i in range(len(klinelog)):
    # CHECK TO SEE IF THE SECOND DATA IS A UNIQUE TICK
    if klinelog['unique_tick'].iloc[i] == True:
        # GRAB 60MIN OF SECOND DATA
        try:
            kline_combined = klinelog.iloc[i:(i + 3600)].copy().drop('unique_tick', axis=1)
        except:
            continue

        # PROCESS INTO 60MIN OF MINUTE OHLCV DATA
        kline_combined['open'] = kline_combined['close']
        kline_combined['high'] = kline_combined['close']
        kline_combined['low'] = kline_combined['close']
        kline_combined = kline_combined.groupby(np.arange(len(kline_combined)) // 60).agg({'id': 'min', 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'})

However since I'm dealing with months/years of data, this would take days to complete. is there any way to do this without iterating over the entire dataset?


问:
Spark streaming : Two Kafka stream join with time conditions
I have two kafka stream, on stream has event id and the other stream has event id and transaction id.

One event id can have multiple transaction id.

I want to use spark streaming to keep sinking all the data to database from the second kafka topic (without any aggregation), but only for the event id from the first kafka topic and within 20 mins when we first get that event id from the first kafka topic.

I am wondering if there is any suggestion regarding how to do it in Spark Streaming.

Any comments or suggestions are much welcomed.


问:
Pass Parameters Besides URL in Next JS in Client Side API Fetch
I've been working on calling an internal GetCompanies API through the website client side.

So far I made attempts like this based on search results and documentation

```<code>// const fetcher = (includeFiles, folderLocation, SharePointCreds) => fetch(includeFiles, folderLocation, SharePointCreds).then(res => res.json());

  // const { data, error } = useSWR('http://localhost:55419/api/SharePoint/GetCompanies', fetcher);

  // if (error) return <div>failed to load</div>
  // if (!data) return <div>loading...</div>

  // render data
  //return <div>hello {data}!</div>

     useEffect((includeFiles, folderLocation, SharePointCreds) => {
        fetch('http://localhost:55419/api/SharePoint/GetCompanies', includeFiles, folderLocation, { method: "POST", body: SharePointCreds})
            .then((res) => res.json())
            .then((data) => {
                console.log("data is ", data)
            })
    }, [])

    if (isLoading) return <p>Loading...</p>

    // async function GetCompanies(includeFiles, folderLocation, SharePointCreds){
    //   const res = await fetch('http://localhost:55419/api/SharePoint/GetCompanies');
    //   const companies = await res.json();
    // }

    // return (
    //   <div>
    //     <p>{data}</p>
    //   </div>
    // )
</code>```

corresponding to an API call which works when we test it in Swagger

And I got generic error messages like TypeError: Failed to fetch

I guess the error is in how I pass in includeFiles and folderLocation since I haven't yet found documentation or search results for how to pass in parameters besides the URL, though I could be wrong.

I define all the arguments earlier in the portfolio component for now.

Do you see how else I should pass in includeFiles and folderLocation?

Also, please be kind because I'm learning and doing my best and I've worked on this for a few hours already.

Body:
I've been working on calling an internal GetCompanies API through the website client side.

So far I made attempts like this based on search results and documentation

// const fetcher = (includeFiles, folderLocation, SharePointCreds) => fetch(includeFiles, folderLocation, SharePointCreds).then(res => res.json());

  // const { data, error } = useSWR('http://localhost:55419/api/SharePoint/GetCompanies', fetcher);

  // if (error) return
failed to load

  // if (!data) return
loading...

  // render data
  //return
hello {data}!

     useEffect((includeFiles, folderLocation, SharePointCreds) => {
        fetch('http://localhost:55419/api/SharePoint/GetCompanies', includeFiles, folderLocation, { method: "POST", body: SharePointCreds})
            .then((res) => res.json())
            .then((data) => {
                console.log("data is ", data)
            })
    }, [])

    if (isLoading) return
Loading...

    // async function GetCompanies(includeFiles, folderLocation, SharePointCreds){
    //   const res = await fetch('http://localhost:55419/api/SharePoint/GetCompanies');
    //   const companies = await res.json();
    // }

    // return (
    //

    //
{data}

    //

    // )

corresponding to an API call which works when we test it in Swagger

And I got generic error messages like TypeError: Failed to fetch

I guess the error is in how I pass in includeFiles and folderLocation since I haven't yet found documentation or search results for how to pass in parameters besides the URL, though I could be wrong.

I define all the arguments earlier in the portfolio component for now.

Do you see how else I should pass in includeFiles and folderLocation?

Also, please be kind because I'm learning and doing my best and I've worked on this for a few hours already.


问:
Handling parallel files with Huggingface Datasets (or in pytorch)
I've seen mention of sharding training data in the Huggingface Datasets library, but can't see any mention of "horizontal sharding". Specifically with translation it is quite common to have parallel files, with your source language sentences in one file, and their translations in another. Is there an easy way to do this?

I am particularly interested in how to expand this to more than two parallel datasets. One example would be where metadata for each sentence is kept in a 3rd file, and is to be processed somehow and then prefixed to source or target string, or perhaps added to the embedding at a certain layer (an example that shows how concat-ing input strings is too naive).

Is this kind of flexibility possible with  Huggingface Datasets, and how would I go about doing it? If not, is it something that PyTorch DataLoader can do?


问:
BeautifulSoup.__init__() got multiple values for argument 'features' (when importing a custom BeautifulSoup wrapper function)

Problem

I had been using this wrapper function with no issues.

```<code>def make_soup(response):
        return BeautifulSoup(response.text, 'lxml')

response = requests.get('https://www.webscraper.io/test-sites/e-commerce/allinone')

soup = make_soup(response) # No Error
</code>```

However, after upgrading to python 3.11 from 3.8, when importing the function and trying to use it, I get the following error:

```<code>from util import make_soup
response = requests.get('https://www.webscraper.io/test-sites/e-commerce/allinone')

make_soup(response) # Error
</code>```
```<code>TypeError: BeautifulSoup.__init__() got multiple
values for argument 'features'
</code>```

Attempted fix: Passing "features" as a keyword argument

I tried passing lxml as a keyword argument instead:

```<code>def make_soup(response):
    return bs(response.text, features='lxml')
</code>```

Initially, this appeared to fix the issue, as the function ran fine when imported.

However, I noticed that often the returned BeautifulSoup object was missing large parts of the HTML, that were not missing if I executed the same code without importing it.

Here's one more extreme example

```<code>from util import make_soup

session = requests.Session()
response = session.get('https://www.deviantart.com/') # One of the many sites I tested this on

soup = bs(response.text, 'lxml')
soup_from_imported_func = make_soup(response)

num_divs = lambda soup: len(soup.find_all('div'))

print(num_divs(soup))
print(num_divs(soup_from_imported_func))
</code>```

These printed values should be equal, but they're not.

```<code>0
1120
</code>```

If I print the broken soup this is all I get

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

I have tried using a different parser (html.parser and html5lib) but the issue persists.

Conclusion

As a temporary solution I can reluctantly repeat the contents of the make_soup function

However I would like to understand why this is happening, in case it generates more problems in the future.

Body:
Problem

I had been using this wrapper function with no issues.

def make_soup(response):
        return BeautifulSoup(response.text, 'lxml')

response = requests.get('https://www.webscraper.io/test-sites/e-commerce/allinone')

soup = make_soup(response) # No Error

However, after upgrading to python 3.11 from 3.8, when importing the function and trying to use it, I get the following error:

from util import make_soup
response = requests.get('https://www.webscraper.io/test-sites/e-commerce/allinone')

make_soup(response) # Error

TypeError: BeautifulSoup.__init__() got multiple
values for argument 'features'

Attempted fix: Passing "features" as a keyword argument

I tried passing lxml as a keyword argument instead:

def make_soup(response):
    return bs(response.text, features='lxml')

Initially, this appeared to fix the issue, as the function ran fine when imported.

However, I noticed that often the returned BeautifulSoup object was missing large parts of the HTML, that were not missing if I executed the same code without importing it.

Here's one more extreme example

from util import make_soup

session = requests.Session()
response = session.get('https://www.deviantart.com/') # One of the many sites I tested this on

soup = bs(response.text, 'lxml')
soup_from_imported_func = make_soup(response)

num_divs = lambda soup: len(soup.find_all('div'))

print(num_divs(soup))
print(num_divs(soup_from_imported_func))

These printed values should be equal, but they're not.

0
1120

If I print the broken soup this is all I get

<?xml version="1.0" encoding="utf-8"?>

I have tried using a different parser (html.parser and html5lib) but the issue persists.

Conclusion

As a temporary solution I can reluctantly repeat the contents of the make_soup function

However I would like to understand why this is happening, in case it generates more problems in the future.


问:
Where should I place the return to only get the plots I want?
I want only displot / countplot to return based on the choice, I am not sure where to place the return function

```<code>def viz(plottype, col):

    if plottype == "count":
        plt.figure(figsize=(15,15))
        sns.countplot(x=df[col],palette="mako", hue=df['Credit_Score'])
        plt.xticks(rotation=45)
        plt.show()

    elif plottype == 'dist':

        plt.figure(figsize=(12,12))
        sns.displot(df[col], color='crimson', kde=True, bins=50)
        plt.xticks(rotation=45)
        plt.show()

occ =viz("count", "Occupation")
cm = viz("count", "Credit_Mix")
mSal = viz('dist', 'Monthly_Inhand_Salary')
cm
</code>```

I want cm to return only a countplot and mSal to return only the displot. I am not sure what to return and where to place the return. Or is there another way to carry this out?

Body:
I want only displot / countplot to return based on the choice, I am not sure where to place the return function

def viz(plottype, col):

    if plottype == "count":
        plt.figure(figsize=(15,15))
        sns.countplot(x=df[col],palette="mako", hue=df['Credit_Score'])
        plt.xticks(rotation=45)
        plt.show()

    elif plottype == 'dist':

        plt.figure(figsize=(12,12))
        sns.displot(df[col], color='crimson', kde=True, bins=50)
        plt.xticks(rotation=45)
        plt.show()

occ =viz("count", "Occupation")
cm = viz("count", "Credit_Mix")
mSal = viz('dist', 'Monthly_Inhand_Salary')
cm

I want cm to return only a countplot and mSal to return only the displot. I am not sure what to return and where to place the return. Or is there another way to carry this out?


问:
API call to link a number to a 10 DLC campaign
I buy numbers and set up callbacks on them through the Vonage API without any problems. Now, however, I am required to link every new number with a 10 DLC campaign. Do I have to resort to the console to do this, or is there an API call that will do the job? I've searched the API documentation without success.</p>


问:
Failed to load resource: the server responded with a status of 403 (Forbidden) in MERN Chat project
I am working on MERN chat app project. I have completed the backend and routes for authentication and login signup. My laptop is in service center. When I tried running the project on my friends laptop using all same credentials, I am getting following error
Failed to load resource: the server responded with a status of 403 (Forbidden)

I am able to register user through postman but not through the frontend of the app.
Also for logging in from the postman it is showing the same error
Please help!
Images :
[I am able to register new user through postman]

(https://i.stack.imgur.com/DYnrZ.jpg)

Error Image Postman

Error Image

I am not getting enough details. I searched everywhere. The project was running fine on my own machine.


问:
While loop not working while i tell it specific words to not loop on
```<code>form = input("Please input your form name: ")
while form != "St Albans"or"York"or"Rochester"or"Rochester 2":
    form = input("Please input your form name: ")

</code>```

Why isnt this working?

It keeps on repeating itself no matter what, it is because of the "or"'s?

Body:
form = input("Please input your form name: ")
while form != "St Albans"or"York"or"Rochester"or"Rochester 2":
    form = input("Please input your form name: ")

Why isnt this working?

It keeps on repeating itself no matter what, it is because of the "or"'s?


问:
GStreamer RTSP streaming to multiple clients
I'm trying to serve RTSP stream for multiple clients from CSI connected to Jetson Nano (without centralized video server)

Some searching has lead me to test-launch.c.

I've downloaded source code above, commented gst_rtsp_media_factory_set_enable_rtcp (factory, !disable_rtcp); line (since my GStreamer not support it) and built it via gcc test-launch.c -o test-launch $(pkg-config --cflags --libs gstreamer-1.0 gstreamer-rtsp-server-1.0)  successfully.

My next step is to start RTSP server:

./test-launch -p 44554 "nvarguscamerasrc sensor-id=0 ! video/x-raw(memory:NVMM), format=NV12, width=416, height=256 ! nvv4l2h264enc insert-sps-pps=true ! h264parse ! rtph264pay name=pay0 pt=96"

after RTSP server starts I see:

stream ready at rtsp://127.0.0.1:44554/test

Everything seems to be fine and I can execute ffmpeg to test if it actually works:

ffmpeg -i rtsp://127.0.0.1:44554/test -acodec copy -vcodec copy -y out.mp4

Everything is good again. BUT. When I'm trying to start another ffmpeg session I get next error:

```<code># This error appears till I stop first session.
[rtsp @ 0x55a7fb3680] method PLAY failed: 503 Service Unavailable
rtsp://127.0.0.1:44554/test: Server returned 5XX Server Error reply
</code>```

Is there something that I missing? Are there better ways to achieve multi-client RTSP streaming on JetsonNano+CSI camera?

P.S. My setup:

Camera: Arducam IMX477

GStreamer version: 1.14.5

Jetson OS: Jetpack 4.6

Body:
I'm trying to serve RTSP stream for multiple clients from CSI connected to Jetson Nano (without centralized video server)

Some searching has lead me to test-launch.c.

I've downloaded source code above, commented gst_rtsp_media_factory_set_enable_rtcp (factory, !disable_rtcp); line (since my GStreamer not support it) and built it via gcc test-launch.c -o test-launch $(pkg-config --cflags --libs gstreamer-1.0 gstreamer-rtsp-server-1.0)  successfully.

My next step is to start RTSP server:

./test-launch -p 44554 "nvarguscamerasrc sensor-id=0 ! video/x-raw(memory:NVMM), format=NV12, width=416, height=256 ! nvv4l2h264enc insert-sps-pps=true ! h264parse ! rtph264pay name=pay0 pt=96"

after RTSP server starts I see:

stream ready at rtsp://127.0.0.1:44554/test

Everything seems to be fine and I can execute ffmpeg to test if it actually works:

ffmpeg -i rtsp://127.0.0.1:44554/test -acodec copy -vcodec copy -y out.mp4

Everything is good again. BUT. When I'm trying to start another ffmpeg session I get next error:

# This error appears till I stop first session.
[rtsp @ 0x55a7fb3680] method PLAY failed: 503 Service Unavailable
rtsp://127.0.0.1:44554/test: Server returned 5XX Server Error reply

Is there something that I missing? Are there better ways to achieve multi-client RTSP streaming on JetsonNano+CSI camera?

P.S. My setup:

Camera: Arducam IMX477

GStreamer version: 1.14.5

Jetson OS: Jetpack 4.6


问:
Error installing devstack permission denied
enter image description here

```<code>touch: cannot touch '/devstack/.localrc.password': Permission denied
Error on exit
/devstack/tools/worlddump.py:22: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives
  from distutils import spawn
World dumping... see /opt/stack/logs/worlddump-2022-12-06-185541.txt for details
Traceback (most recent call last):
  File "/devstack/tools/worlddump.py", line 272, in <module>
    sys.exit(main())
  File "/devstack/tools/worlddump.py", line 249, in main
    with io.open(fname, 'w') as f:
PermissionError: [Errno 13] Permission denied: '/opt/stack/logs/worlddump-2022-12-06-185541.txt'

</code>```

i tried but dont complete. please help me

Body:
enter image description here

touch: cannot touch '/devstack/.localrc.password': Permission denied
Error on exit
/devstack/tools/worlddump.py:22: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives
  from distutils import spawn
World dumping... see /opt/stack/logs/worlddump-2022-12-06-185541.txt for details
Traceback (most recent call last):
  File "/devstack/tools/worlddump.py", line 272, in <module>
    sys.exit(main())
  File "/devstack/tools/worlddump.py", line 249, in main
    with io.open(fname, 'w') as f:
PermissionError: [Errno 13] Permission denied: '/opt/stack/logs/worlddump-2022-12-06-185541.txt'

i tried but dont complete. please help me


问:
how to save a null value to core data
I am using a helper method to try to save a null value to core data.

```<code>

 @objc func newB() {
        CoredataHandler.saveObject(username: null, password  : null, tf: null)
}

class CoredataHandler : NSManagedObject {
   class func saveObject(username: String,password: String,tf: Bool) -> Bool{
        let context = getContext()
        let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
        let managedObject = NSManagedObject(entity: entity!, insertInto: context)

        managedObject.setValue(username, forKey: "username")
        managedObject.setValue(password, forKey: "password")
        managedObject.setValue(tf, forKey: "tf")

        do {
            try context.save()

            return true
        } catch{
            return false
        }

    }

</code>```

I tried to save the values as coredataHandler.saveObject(username: null, password : null, tf: null) and that does not fit into what is trying to be passed into the parament of class func saveObject.

Title: how to save a null value to core data

Body:
I am using a helper method to try to save a null value to core data.

 @objc func newB() {
        CoredataHandler.saveObject(username: null, password  : null, tf: null)
}

class CoredataHandler : NSManagedObject {
   class func saveObject(username: String,password: String,tf: Bool) -> Bool{
        let context = getContext()
        let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
        let managedObject = NSManagedObject(entity: entity!, insertInto: context)

        managedObject.setValue(username, forKey: "username")
        managedObject.setValue(password, forKey: "password")
        managedObject.setValue(tf, forKey: "tf")

        do {
            try context.save()

            return true
        } catch{
            return false
        }

    }

I tried to save the values as coredataHandler.saveObject(username: null, password : null, tf: null) and that does not fit into what is trying to be passed into the parament of class func saveObject.


问:
add new data with ExcelWriter() without deleting old data in excel file
I am trying to add data to excel sheet from pandas library. Now I am needed to add new data without deleting old data in excel sheet
My Code:

editableExcelSheet = pd.ExcelWriter(r'D:\Projects\MOJ\MOJ.xlsx', engine='xlsxwriter')

serialNumberFromSheet_htmlName = request.form.get("serialNumberFromSheet_htmlName")
dataSet = {'Serial Number': [serialNumberFromSheet_htmlName]}
newCase = pd.DataFrame(dataSet)
newCase.to_excel(editableExcelSheet, sheet_name='Sheet1')
editableExcelSheet.save()
```


问:
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' - Cypress, TypeScript and Axios
I'm trying to create simple API test with Axios, but getting below error:
How to solve below problem?

```<code>SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'
</code>```

My test file

```<code>const axios = require('axios');
axios.get('http://localhost:8080/')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
  });

</code>```

Basic setting of my tsconfig.json

```<code>{
    "compilerOptions": {
      "target": "es5",
      "lib": ["es5", "dom"],
      "types": ["cypress", "node"],
      "resolveJsonModule": true,
    },
    "include": ["**/*.ts"],
    "exclude": ["node_modules"]
  }
</code>```

I add below dependencies in my package.json

```<code>{
  "main": "index.ts",
  "sourceType": "module",
  },
  "cypress-cucumber-preprocessor": {
    "nonGlobalStepDefinitions": true
  },
  "dependencies": {
    "@types/browserify": "^12.0.37",
    "@types/cypress-cucumber-preprocessor": "^4.0.1",
    "axios": "^1.2.0",
    "cypress": "^9.7.0",
    "cypress-cucumber-preprocessor": "^4.3.1",
    "install": "^0.13.0",
    "tsc": "^2.0.4"
  },
  "devDependencies": {
    "@babel/core": "^7.20.2",
    "@babel/preset-env": "^7.20.2",
    "@cucumber/cucumber": "^8.8.0",
    "@cypress/webpack-preprocessor": "^5.15.5",
    "typescript": "^4.9.3",
    "webpack": "^5.75.0"
  }
}
</code>```

Body:
I'm trying to create simple API test with Axios, but getting below error:
How to solve below problem?

SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'

My test file

const axios = require('axios');
axios.get('http://localhost:8080/')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
  });

Basic setting of my tsconfig.json

{
    "compilerOptions": {
      "target": "es5",
      "lib": ["es5", "dom"],
      "types": ["cypress", "node"],
      "resolveJsonModule": true,
    },
    "include": ["**/*.ts"],
    "exclude": ["node_modules"]
  }

I add below dependencies in my package.json

{
  "main": "index.ts",
  "sourceType": "module",
  },
  "cypress-cucumber-preprocessor": {
    "nonGlobalStepDefinitions": true
  },
  "dependencies": {
    "@types/browserify": "^12.0.37",
    "@types/cypress-cucumber-preprocessor": "^4.0.1",
    "axios": "^1.2.0",
    "cypress": "^9.7.0",
    "cypress-cucumber-preprocessor": "^4.3.1",
    "install": "^0.13.0",
    "tsc": "^2.0.4"
  },
  "devDependencies": {
    "@babel/core": "^7.20.2",
    "@babel/preset-env": "^7.20.2",
    "@cucumber/cucumber": "^8.8.0",
    "@cypress/webpack-preprocessor": "^5.15.5",
    "typescript": "^4.9.3",
    "webpack": "^5.75.0"
  }
}


问:
How to make baseline on nested flex box elements
Is there a solution to align .item__header on the baseline with other elements?

I have a situation where title is required but the subtitle is optional and when the subtitle is empty I have an issue with a baseline of the item header?

The solutions that I don't want to consider:

adding min-height

adding fake/empty/mock element

without using scripts like JS/React (unless that's the only solution)

code sandbox
https://codesandbox.io/embed/pedantic-hertz-3mk5sq?fontsize=14&hidenavigation=1&theme=dark


问:
Moving conditional element rendering into a separate function within the same component
I'm trying to move a part of the code where it gets very repetitive into a function within the same component.

Here is what it would look like before moving this conditional statement into a separate function...

```<code>                <div className="col-4">
                    {parts.map(part => (
                        part.active[0] && <div key={part.bodyPart}>{part.bodyPart}</div>
                    ))}
                </div>
</code>```

and I'm trying to move it so it would look something like this in the function.

```<code>    const showParts = (activeIndex) => {
        return parts.map(part => (
            //this one does not work
            part.active[activeIndex] && <div key={part.bodyPart}>{part.bodyPart}</div>

            //but for some reason, this works below without the conditional statement
            /* <div key={part.bodyPart}>{part.bodyPart}</div> */

        ))
    }
</code>```

And here's what it would look like in the return statement.

```<code>    return (
        <div className="container text-center">
            <div className="row rows-cols-3">
                <div className="col-4">
                    {showParts(0)}
                </div>
            </div>
        </div>
    );
</code>```

I know that the conditional statement is causing the issue but I'm not sure what bracket or return statement I'm missing in the function to make it work.

It's also confusing because I am not getting any error with the conditional statement I have it on here.

Also, here's what the 'parts' state looks like.

```<code>const [parts, setParts] = useState([
        { bodyPart: "upperLip", price: 1000, active: [true, true, true] }]
</code>```

Thanks!

Body:
I'm trying to move a part of the code where it gets very repetitive into a function within the same component.

Here is what it would look like before moving this conditional statement into a separate function...

                    {parts.map(part => (
                        part.active[0] &&
{part.bodyPart}

                    ))}

and I'm trying to move it so it would look something like this in the function.

    const showParts = (activeIndex) => {
        return parts.map(part => (
            //this one does not work
            part.active[activeIndex] &&
{part.bodyPart}

            //but for some reason, this works below without the conditional statement
            /*
{part.bodyPart}
 */

        ))
    }

And here's what it would look like in the return statement.

    return (

                    {showParts(0)}

    );

I know that the conditional statement is causing the issue but I'm not sure what bracket or return statement I'm missing in the function to make it work.

It's also confusing because I am not getting any error with the conditional statement I have it on here.

Also, here's what the 'parts' state looks like.

const [parts, setParts] = useState([
        { bodyPart: "upperLip", price: 1000, active: [true, true, true] }]

Thanks!


问:
Are there any tools or 3rd parties - free or paid that can scrape URLs for Price?
I have a list of URLs and need auto update on the price found on website. Are there any tools or 3rd parties - free or paid that can scrape URLs for Price?

I have a list of URLs and need auto update on the price found on website. Are there any tools or 3rd parties - free or paid that can scrape URLs for Price?


问:
How to configure a specific setting of ios or android phone in th background if my react native app is open in foreground?
First of all I'm new as React-Native programmer. Currently I want to  add a button to my React-Native(Expo) app, in which the user can turn off or on a setting. Is this possible and if so, how can I do that? For example in Android > Settings > Mobile Networks > Turn off mobile roaming?

Thank you in advance

I have tried to use HeadlessJS or a module called background actions. But there are no well documented examples and I also don't know if those modules answer my question. Because my task is more "straightforward" since I keep the app running in the foreground.


问:
How to delete a graph when using FigureCanvasTkAgg
I used FigureCanvasTkAgg to make a graphic on the interface, but I don't know how to make the graph disappear from the screen.

```<code>def actualizarGrafico1():
    global comp
    comp = 1
    e1a1= int(e1.get())*12
    e2a1= int(e2.get())*285
    e3a1= int(e3.get())*8
    e4a1= int(e4.get())*20
    e5a1= int(e5.get())*12
    e6a1= int(e6.get())*15
    nombres = ["Lavarse las manos", "Usar lavadora", "Tirar cadena", "Ducharse", "Regar", "Lavar la loza"]
    tamaño = [e1a1, e2a1, e3a1, e4a1, e5a1, e6a1]
    coloresg =['lightcyan', 'powderblue','paleturquoise', 'lightsteelblue', 'lightskyblue', 'azure']
    explotar = [0.4,0.4,0.4,0.4,0.4,0.4]

    fig1, ax1= plt.subplots(dpi=50, facecolor ='white', figsize= (9,7))

    plt.title("Gráfico de consumo por actividad", size=25, family="Arial")

    ax1.pie(tamaño, explode=explotar, labels=nombres, colors=coloresg, autopct= "%0.1f%%", shadow=True, startangle=90, radius=0.9)

    ax1.axis('equal')

    global canvas1
    canvas1=FigureCanvasTkAgg(fig1, master=frame)
    canvas1.draw()
    canvas1.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
</code>```

I tried to use pack_forget() to make it stop showing and it didn't work. I also used delete to eliminate it, but when pressing the button associated with the function, the copy of the graph appears.

```<code>def cerrarGrafico1():
    bm.grid_remove()
    canvas1.get_tk_widget().delete("all")

    datacmenu.entryconfig("Ingresar",command=actualizarGrafico1())
</code>```

Body:
I used FigureCanvasTkAgg to make a graphic on the interface, but I don't know how to make the graph disappear from the screen.

def actualizarGrafico1():
    global comp
    comp = 1
    e1a1= int(e1.get())*12
    e2a1= int(e2.get())*285
    e3a1= int(e3.get())*8
    e4a1= int(e4.get())*20
    e5a1= int(e5.get())*12
    e6a1= int(e6.get())*15
    nombres = ["Lavarse las manos", "Usar lavadora", "Tirar cadena", "Ducharse", "Regar", "Lavar la loza"]
    tamaño = [e1a1, e2a1, e3a1, e4a1, e5a1, e6a1]
    coloresg =['lightcyan', 'powderblue','paleturquoise', 'lightsteelblue', 'lightskyblue', 'azure']
    explotar = [0.4,0.4,0.4,0.4,0.4,0.4]

    fig1, ax1= plt.subplots(dpi=50, facecolor ='white', figsize= (9,7))

    plt.title("Gráfico de consumo por actividad", size=25, family="Arial")

    ax1.pie(tamaño, explode=explotar, labels=nombres, colors=coloresg, autopct= "%0.1f%%", shadow=True, startangle=90, radius=0.9)

    ax1.axis('equal')

    global canvas1
    canvas1=FigureCanvasTkAgg(fig1, master=frame)
    canvas1.draw()
    canvas1.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

I tried to use pack_forget() to make it stop showing and it didn't work. I also used delete to eliminate it, but when pressing the button associated with the function, the copy of the graph appears.

def cerrarGrafico1():
    bm.grid_remove()
    canvas1.get_tk_widget().delete("all")

    datacmenu.entryconfig("Ingresar",command=actualizarGrafico1())


问:
Simulate pressing enter key using pytest
I have a function that I am trying to test using pytest. It prints a list of files and the output changes depending on the number of files ('this file is' for one file, 'these files are' for multiple files) and the user must press Enter for the function to exit. I am trying to test that the correct wording is used in the print statement. The issue is that the test hangs until Enter is pressed. How can I simulate pressing Enter from the test to automate it?

Function being tested:

```<code>def confirm_files(f_name, r_files):
    if len(r_files) == 1:
        text_f = 'this file is'
    else:
        text_f = 'these files are'

    print(f'\nTo process the {f_name} the following files are required:\n')

    for file in r_files:
        print(file)

    print(f'\nPlease make sure that {text_f} in the required folder and are '
          'updated correctly before proceeding.')

    input(f'\nPress the enter key to continue processing the {f_name} file '
          '--> ')
</code>```

Test function:

```<code>import pytest
import utils as ut

def test_single_file(self, capfd):
    f_name = 'Single File'
    files = ['One file']

    ut.confirm_files(f_name, files)

    out, err = capfd.readouterr()
    assert 'this file is' in out,\
        'Single item did not output this file is'
</code>```

Running pytest test_utils.py results in an OSError (reading from stdin while output is captured).

Running pytest test_utils -s causes the test to hang until Enter is pressed. Ideally the test would mock the Enter key being pressed and move to the next test. Most of the answers I have seen are regarding asserting the return value when mocking the input but I just want the test to complete.

Using python 3.9.4 on Windows 10.

Body:
I have a function that I am trying to test using pytest. It prints a list of files and the output changes depending on the number of files ('this file is' for one file, 'these files are' for multiple files) and the user must press Enter for the function to exit. I am trying to test that the correct wording is used in the print statement. The issue is that the test hangs until Enter is pressed. How can I simulate pressing Enter from the test to automate it?

Function being tested:

def confirm_files(f_name, r_files):
    if len(r_files) == 1:
        text_f = 'this file is'
    else:
        text_f = 'these files are'

    print(f'\nTo process the {f_name} the following files are required:\n')

    for file in r_files:
        print(file)

    print(f'\nPlease make sure that {text_f} in the required folder and are '
          'updated correctly before proceeding.')

    input(f'\nPress the enter key to continue processing the {f_name} file '
          '--> ')

Test function:

import pytest
import utils as ut

def test_single_file(self, capfd):
    f_name = 'Single File'
    files = ['One file']

    ut.confirm_files(f_name, files)

    out, err = capfd.readouterr()
    assert 'this file is' in out,\
        'Single item did not output this file is'

Running pytest test_utils.py results in an OSError (reading from stdin while output is captured).

Running pytest test_utils -s causes the test to hang until Enter is pressed. Ideally the test would mock the Enter key being pressed and move to the next test. Most of the answers I have seen are regarding asserting the return value when mocking the input but I just want the test to complete.

Using python 3.9.4 on Windows 10.


问:
Grafana JSON API datasource - parse response
I succesfully get data from datasource using plugin: https://grafana.github.io/grafana-json-datasource/
And my response looks like this (I see that in Chrome console log):

```<code>{
"count": 4,
"results": [
    {
        "time": "2022-12-06T17:52:30.142Z",
        "deviceId": "3021EF",
        "humidity": 49,
        "messageId": "1ed82601-e98a-4b78-a580-0c8a5ddd1e99"
    },
    {
        "time": "2022-12-06T17:52:30.142Z",
        "humidity": 45,
        "deviceId": "3021EF",
        "messageId": "1ed82601-e98a-4b78-a580-0c8a5ddd1e98"
    },
    {
        "time": "2022-12-06T18:27:34.768Z",
        "deviceId": "3021EF",
        "humidity": 49,
        "messageId": "1ed82601-e98a-4b78-a580-0c8a5ddd1e97"
    },
    {
        "time": "2022-12-06T18:27:34.768Z",
        "deviceId": "3021EF",
        "temperature": 21.6,
        "messageId": "1ed82601-e98a-4b78-a580-0c8a5ddd1e96"
    }
],
"fields": [
    "time",
    "deviceId",
    "humidity",
    "messageId"
    ]
}
</code>```

But I can not parse this data using explore:

What is wrong?

Body:
I succesfully get data from datasource using plugin: https://grafana.github.io/grafana-json-datasource/
And my response looks like this (I see that in Chrome console log):

{
"count": 4,
"results": [
    {
        "time": "2022-12-06T17:52:30.142Z",
        "deviceId": "3021EF",
        "humidity": 49,
        "messageId": "1ed82601-e98a-4b78-a580-0c8a5ddd1e99"
    },
    {
        "time": "2022-12-06T17:52:30.142Z",
        "humidity": 45,
        "deviceId": "3021EF",
        "messageId": "1ed82601-e98a-4b78-a580-0c8a5ddd1e98"
    },
    {
        "time": "2022-12-06T18:27:34.768Z",
        "deviceId": "3021EF",
        "humidity": 49,
        "messageId": "1ed82601-e98a-4b78-a580-0c8a5ddd1e97"
    },
    {
        "time": "2022-12-06T18:27:34.768Z",
        "deviceId": "3021EF",
        "temperature": 21.6,
        "messageId": "1ed82601-e98a-4b78-a580-0c8a5ddd1e96"
    }
],
"fields": [
    "time",
    "deviceId",
    "humidity",
    "messageId"
    ]
}

But I can not parse this data using explore:

What is wrong?


问:
AsyncImage in LazyColumn Kotlin Compose
I have a list of photos from the internet and I want to load them into a LazyColumn. The problem is that some of them are loading faster than others so the photos appear in random order.
Here is the code:

```<code>val state = viewModel.photos.collectAsState()
val lastIndex = state.value.lastIndex
LazyColumn {
    itemsIndexed(state.value) { i, photo ->

        AsyncImage(
            model = photo.urls.regular,
            contentDescription = null,
            modifier = Modifier.fillMaxWidth(),
        )

        if (i >= lastIndex-1 && !viewModel.isLoading.value) {
            viewModel.getPhotos(6)
        }
    }
}
</code>```

Sometimes image with LastIndex-1 occurs first and it triggers viewModel to get new data.
How can I make a handler for loading a list of images? Or maybe any suggestions on how to make a preloading screen which will end after loading all images into LazyColumn
I also have a Coil version too:

```<code>val model = ImageRequest.Builder(LocalContext.current)
            .data(photo.urls.regular)
            .size(Size.ORIGINAL)
            .crossfade(true)
            .build()

        val painter = rememberAsyncImagePainter(model)

        Image(
            painter = painter,
            contentDescription = null,
            modifier = Modifier.fillMaxWidth(),
        )
</code>```

Title: AsyncImage in LazyColumn Kotlin Compose

Body:
I have a list of photos from the internet and I want to load them into a LazyColumn. The problem is that some of them are loading faster than others so the photos appear in random order.
Here is the code:

val state = viewModel.photos.collectAsState()
val lastIndex = state.value.lastIndex
LazyColumn {
    itemsIndexed(state.value) { i, photo ->

        AsyncImage(
            model = photo.urls.regular,
            contentDescription = null,
            modifier = Modifier.fillMaxWidth(),
        )

        if (i >= lastIndex-1 && !viewModel.isLoading.value) {
            viewModel.getPhotos(6)
        }
    }
}

Sometimes image with LastIndex-1 occurs first and it triggers viewModel to get new data.
How can I make a handler for loading a list of images? Or maybe any suggestions on how to make a preloading screen which will end after loading all images into LazyColumn
I also have a Coil version too:

val model = ImageRequest.Builder(LocalContext.current)
            .data(photo.urls.regular)
            .size(Size.ORIGINAL)
            .crossfade(true)
            .build()

        val painter = rememberAsyncImagePainter(model)

        Image(
            painter = painter,
            contentDescription = null,
            modifier = Modifier.fillMaxWidth(),
        )


问:
Get output for each id in sql
I wrote a logic for getting the difference in days for present status a next status for a particular sub status and application.

```<code>select * from (
   select datediff(day,presentstatusdate,nextstatusdate)
   from timeline
   where type="status'
   and application='a123' ) as a
where sub_status='docs'
</code>```

Here it is giving the expected result.

I am struggling to understand the logic, where if I need daysdiff for all applications. i.e If i remove the application field from the query, it is not giving expected result.

```<code>select * from (
   select datediff(day,presentstatusdate,nextstatusdate)
   from timeline
   where type="status'
   and application=(
      select distinct application
      from timline
      where timeline.application=a.application )
    ) as a
where sub_status='docs'
</code>```

Title: Get output for each id in sql

Body:
I wrote a logic for getting the difference in days for present status a next status for a particular sub status and application.

select * from (
   select datediff(day,presentstatusdate,nextstatusdate)
   from timeline
   where type="status'
   and application='a123' ) as a
where sub_status='docs'

Here it is giving the expected result.

I am struggling to understand the logic, where if I need daysdiff for all applications. i.e If i remove the application field from the query, it is not giving expected result.

select * from (
   select datediff(day,presentstatusdate,nextstatusdate)
   from timeline
   where type="status'
   and application=(
      select distinct application
      from timline
      where timeline.application=a.application )
    ) as a
where sub_status='docs'


问:
Understadning Krige.bayes() output
I am struggling with the Krige.bayes() function in the GeoR package. I was hoping to create a map with my output from the function but I can't seem to find a way to do this. The online pdf (https://cran.r-project.org/web/packages/geoR/geoR.pdf) of the geoR package indicates that you can make an image using geoR::image.kriging however I get the error code 'image.kriging' is not an exported object from 'namespace:geoR' when I do this. When using ls("package:geoR") this function does not appear indicating that it has been depriocated and just not taken off the package information. This leaves me with just the output from the Krige.bayes() function and some variomodels that I have created as well. I can see that I can modify the output output.control, however I'm not sure what I can change in there to make the output more comprehendable to me. The output thaty I am getting from the Krige.bayes() is as follows.

```<code>             Only samples of the posterior for the parameters will be returned.
krige.bayes: computing the discrete posterior of phi/tausq.rel
krige.bayes: argument `phi.discrete` not provided, using default values
krige.bayes: computing the posterior probabilities.
             Number of parameter sets:  50
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50

krige.bayes: sampling from posterior distribution
krige.bayes: sample from the (joint) posterior of phi and tausq.rel

                  [,1]        [,2]        [,3]
phi       1.869439e-03 0.003738877 0.007477755
tausq.rel 0.000000e+00 0.000000000 0.000000000
frequency 9.940000e+02 5.000000000 1.000000000
</code>```

Am I misunderstnading this output, the next step or somethign else? Thanks in advance for the help

Title: Understadning Krige.bayes() output

Body:
I am struggling with the Krige.bayes() function in the GeoR package. I was hoping to create a map with my output from the function but I can't seem to find a way to do this. The online pdf (https://cran.r-project.org/web/packages/geoR/geoR.pdf) of the geoR package indicates that you can make an image using geoR::image.kriging however I get the error code 'image.kriging' is not an exported object from 'namespace:geoR' when I do this. When using ls("package:geoR") this function does not appear indicating that it has been depriocated and just not taken off the package information. This leaves me with just the output from the Krige.bayes() function and some variomodels that I have created as well. I can see that I can modify the output output.control, however I'm not sure what I can change in there to make the output more comprehendable to me. The output thaty I am getting from the Krige.bayes() is as follows.

             Only samples of the posterior for the parameters will be returned.
krige.bayes: computing the discrete posterior of phi/tausq.rel
krige.bayes: argument `phi.discrete` not provided, using default values
krige.bayes: computing the posterior probabilities.
             Number of parameter sets:  50
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50

krige.bayes: sampling from posterior distribution
krige.bayes: sample from the (joint) posterior of phi and tausq.rel

                  [,1]        [,2]        [,3]
phi       1.869439e-03 0.003738877 0.007477755
tausq.rel 0.000000e+00 0.000000000 0.000000000
frequency 9.940000e+02 5.000000000 1.000000000

Am I misunderstnading this output, the next step or somethign else? Thanks in advance for the help


问:
Which SDK version of firebase-ads that is working?
I am implementing ads to my kivy application now, but my ads weren't showing up. I think the issue of it is because of the firebase-ads version of android gradle dependencies.

When I tried the older version, I managed to convert my python-kivy code into apk but my ads weren't showing up. (Android API = 30)

```<code>android.gradle_dependencies = 'com.google.firebase:firebase-ads:10.2.0'
</code>```

Therefore, I changed the version to the latest one, but when I tried to convert my python-kivy code into apk, an error occurred because the firebase-ads version of android gradle dependencies is not working.
(Android API = 31)

```<code>android.gradle_dependencies = 'com.google.firebase:firebase-ads:21.3.0'
</code>```

Any idea of which firebase-ads version of android gradle dependencies is working now?
My targeting android API is 31.

Body:
I am implementing ads to my kivy application now, but my ads weren't showing up. I think the issue of it is because of the firebase-ads version of android gradle dependencies.

When I tried the older version, I managed to convert my python-kivy code into apk but my ads weren't showing up. (Android API = 30)

android.gradle_dependencies = 'com.google.firebase:firebase-ads:10.2.0'

Therefore, I changed the version to the latest one, but when I tried to convert my python-kivy code into apk, an error occurred because the firebase-ads version of android gradle dependencies is not working.
(Android API = 31)

android.gradle_dependencies = 'com.google.firebase:firebase-ads:21.3.0'

Any idea of which firebase-ads version of android gradle dependencies is working now?
My targeting android API is 31.


问:
Pad trues in a binary matrix (more efficiently than with a binary dilation)
Problem statement:

I have a very large binary matrix, lets say with dimensions (1000000,500), for which I want to spread the existing trues along its columns.

More specifically, for each True in the matrix, I'd like to pad $N$ Trues along the column right after it.

One approach to solving this is with a binary_dilation from skimage or scipy.

For example, the following would pad two Trues after each True as desired.

import time
import numpy as np
from skimage import morphology

np.random.seed(0)
a = np.random.rand(1000000,500)

t1=time.time()

#in this case N=2
s = np.array([[0],
              [0],
              [1],
              [1],
              [1]])
out = morphology.binary_dilation(a > 0.95,s)

t2=time.time()

print(t2 - t1) #9.127300500869751

```

However, I suspect there's some redundancy in the operation performed by the dilation, since it's designed to solve a far more general problem. Moreover, the dilation's time scales linearly when increasing the number of columns, so I think there's got to be a faster way.

Any ideas for a more efficient approach?

Alternatively, a similar problem which I'm also interested in is the following:
Given a binary matrix, fill Trues between two Trues a distance of at most $N$ rows from each other and at most a single column from each other (if they are in neighboring columns, fill the column of the first true: the one with a smaller row number). I have used skimage.morphology.remove_small_holes iteratively over the columns, to partly solve this, but it doesn't handle neighboring columns, and again I think there's a more efficient approach.

Important context:

My goal here is to help connect nearby regions before labeling them with scipy.ndiamge.label or skimage.measure.label. Therefore, both the problems above are equivalent, since after labeling I can conjunct with the original binary matrix (the one before the padding) to remove all the trues that were not originally there.

Body:
Problem statement:

I have a very large binary matrix, lets say with dimensions (1000000,500), for which I want to spread the existing trues along its columns.

More specifically, for each True in the matrix, I'd like to pad $N$ Trues along the column right after it.

One approach to solving this is with a binary_dilation from skimage or scipy.

For example, the following would pad two Trues after each True as desired.

import time
import numpy as np
from skimage import morphology

np.random.seed(0)
a = np.random.rand(1000000,500)

t1=time.time()

#in this case N=2
s = np.array([[0],
              [0],
              [1],
              [1],
              [1]])
out = morphology.binary_dilation(a > 0.95,s)

t2=time.time()

print(t2 - t1) #9.127300500869751

However, I suspect there's some redundancy in the operation performed by the dilation, since it's designed to solve a far more general problem. Moreover, the dilation's time scales linearly when increasing the number of columns, so I think there's got to be a faster way.

Any ideas for a more efficient approach?

Alternatively, a similar problem which I'm also interested in is the following:
Given a binary matrix, fill Trues between two Trues a distance of at most $N$ rows from each other and at most a single column from each other (if they are in neighboring columns, fill the column of the first true: the one with a smaller row number). I have used skimage.morphology.remove_small_holes iteratively over the columns, to partly solve this, but it doesn't handle neighboring columns, and again I think there's a more efficient approach.

Important context:

My goal here is to help connect nearby regions before labeling them with scipy.ndiamge.label or skimage.measure.label. Therefore, both the problems above are equivalent, since after labeling I can conjunct with the original binary matrix (the one before the padding) to remove all the trues that were not originally there.


问:
LDAP + Active Directory session not refreshing
I can't share any code sadly, but I'm having the following problem and maybe someone could help me at least on how to google this exactly (there are a ton of sites but nothing specific)

I have a .NET api that gets the current user by cookies, using LDAP system

The problem is, when user 1 works and creates requests, sometimes they get saved as by user 2

I believe I'm having the following problem:

user 1 connects and works normally

user 2 connects and LDAP information it's updated to that author

user 1 sends a request and it's saved as by user 2 (but just sometimes)

I don't even know how to search for this, not familiarized with this environment. Maybe I have to force a session clearance after logging?

Thanks!


问:
React error UseContext - Cannot destructure property 'menuActive' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined
I want to create a burger menu

My task is to transfer the **useState **from the "Button" component to the "Navigation" component

**When clicked, it should appear

My code
Main Context component

```<code>import React from "react"
export const Context = React.createContext()
</code>```

Button Component

```<code>import React,{useState, useContext} from 'react'
import {Context} from '../../../Context/Context' // I define context
import arrow from '../../../Assets/img/arrow_back.svg'
const Button = () => {
  const [menuActive, setMenuActive] = useState(false)
  return (
    <Context.Provider value={{ // I define context
      menuActive,setMenuActive
    }}>
    <div className='w-11 h-11 border-2 border-[#191619] rounded grid place-items-center'>
        <a href="/" onClick={() => setMenuActive(!menuActive)}><img src={arrow} className="w-full flex" alt="" /></a>
    </div>
    </Context.Provider>
  )
}
export default Button
</code>```

App JS

```<code>import React,{useContext} from 'react'
import {Context} from './Context/Context'
import Header from "./Components/Header/Header";
import Navigation from "./Components/Navigation/Navigation";
function App() {
const {menuActive,setMenuActive} = useContext(Context)
  return (
    <div className="App">
      <Header/>
      <Navigation active={menuActive} setActive={setMenuActive}/> I define context and i pass the props to the block Navigation
    </div>
  );
}
export default App;
</code>```

Navigation

```<code>return (
    <div className={active ? 'menu active' : 'menu'}> // Just checking and adding a class
      <div className="blur" />
      <div className="menu__content">
        <div className="menu__header"></div>
        <ul>
          {
            items.map(item =>
              <li className='flex p-3'>
                <span class="material-symbols-outlined text-white">{item.icon}</span>
                <a className='text-white pl-3' href={item.href}>{item.value}</a>
                <span className='material-icons'></span>
              </li>
            )
          }
        </ul>
      </div>
    </div>
  )
</code>```

Body:
I want to create a burger menu

My task is to transfer the **useState **from the "Button" component to the "Navigation" component

**When clicked, it should appear

My code
Main Context component

import React from "react"
export const Context = React.createContext()

Button Component

import React,{useState, useContext} from 'react'
import {Context} from '../../../Context/Context' // I define context
import arrow from '../../../Assets/img/arrow_back.svg'
const Button = () => {
  const [menuActive, setMenuActive] = useState(false)
  return (
    <Context.Provider value={{ // I define context
      menuActive,setMenuActive
    }}>

         setMenuActive(!menuActive)}>

    </Context.Provider>
  )
}
export default Button

App JS

import React,{useContext} from 'react'
import {Context} from './Context/Context'
import Header from "./Components/Header/Header";
import Navigation from "./Components/Navigation/Navigation";
function App() {
const {menuActive,setMenuActive} = useContext(Context)
  return (

      <Navigation active={menuActive} setActive={setMenuActive}/> I define context and i pass the props to the block Navigation

  );
}
export default App;

Navigation

return (

 // Just checking and adding a class

          {
            items.map(item =>

                {item.icon}
                {item.value}

            )
          }

  )


问:
Two columns end with .x and .y after merged in R
I merged two dataframe in R, both have id and date columns. I decide to merge by id, after merging there are two date columns, one is date.x and the other is date.y. But I only need one date column

I have searched online for solutions but find none.


问:
Eclipse plugin vs Java 17
I'm working on updating a large old Java application to Java 17.
It was on Java 11.  Note that we build in Eclipse, and all the projects that are part of this application have Java 1.8 compatibility turned on.

Now that I've updated it all to Java 17 (and updated the truckload of .jar files we use to their latest versions as well), I'm getting a problem with a code generator plugin we wrote.

I was able to rebuild the plugin .jar and it seems to be valid.  The problem is that when it runs, it fails With this msg:

```<code>The method parse(File) from the type DataModelParser refers to the missing type ParserConfigurationException
</code>```

Since the class definitely exists, I'm assuming it's running into the issue where Java doesn't like being able to find the class in 2 places.
using Ctrl-Shift-T, I find the class available from Java 17 (expected) and "C:\Users\JohnLuss.p2\pool\plugins\javax.xml_1.3.4.v201005080400.jar"

That jar is part of Eclipse - so why does Eclipse have jars that conflict with java 17?
HOW can I make this work?  Is there any way to exclude the Eclipse jar?

Title: Eclipse plugin vs Java 17

Body:
I'm working on updating a large old Java application to Java 17.
It was on Java 11.  Note that we build in Eclipse, and all the projects that are part of this application have Java 1.8 compatibility turned on.

Now that I've updated it all to Java 17 (and updated the truckload of .jar files we use to their latest versions as well), I'm getting a problem with a code generator plugin we wrote.

I was able to rebuild the plugin .jar and it seems to be valid.  The problem is that when it runs, it fails With this msg:

The method parse(File) from the type DataModelParser refers to the missing type ParserConfigurationException

Since the class definitely exists, I'm assuming it's running into the issue where Java doesn't like being able to find the class in 2 places.
using Ctrl-Shift-T, I find the class available from Java 17 (expected) and "C:\Users\JohnLuss.p2\pool\plugins\javax.xml_1.3.4.v201005080400.jar"

That jar is part of Eclipse - so why does Eclipse have jars that conflict with java 17?
HOW can I make this work?  Is there any way to exclude the Eclipse jar?


问:
How to expand bars over the month on the x-axis while being the same width?
```<code></code>```

for i in range(len(basin)):

```<code>prefix = "URL here"
state = "OR"
basin_name = basin[i]
df_orig = pd.read_csv(f"{prefix}/{basin_name}.csv", index_col=0)

#---create date x-index

curr_wy_date_rng = pd.date_range(
    start=dt(curr_wy-1, 10, 1),
    end=dt(curr_wy, 9, 30),
    freq="D",
)

if not calendar.isleap(curr_wy):
    print("dropping leap day")
    df_orig.drop(["02-29"], inplace=True)

use_cols = ["Median ('91-'20)", f"{curr_wy}"]
df = pd.DataFrame(data=df_orig[use_cols].copy())

df.index = curr_wy_date_rng

#--create EOM percent of median values-------------------------------------

curr_wy_month_rng = pd.date_range(
    start=dt(curr_wy-1, 10, 1),
    end=dt(curr_wy, 6, 30),
    freq="M",
)
df_monthly_prec = pd.DataFrame(data=df_monthly_basin[basin[i]].copy())
df_monthly_prec.index = curr_wy_month_rng

df_monthly = df.groupby(pd.Grouper(freq="M")).max()
df_monthly["date"] = df_monthly.index
df_monthly["wy_date"] = df_monthly["date"].apply(lambda x: cal_to_wy(x))
df_monthly.index = pd.to_datetime(df_monthly["wy_date"])
df_monthly.index = df_monthly["date"]
df_monthly["month"] = df_monthly["date"].apply(
    lambda x: calendar.month_abbr[x.month]
)
df_monthly["wy"] = df_monthly["wy_date"].apply(lambda x: x.year)
df_monthly.sort_values(by="wy_date", axis=0, inplace=True)
df_monthly.drop(
    columns=[i for i in df_monthly.columns if "date" in i], inplace=True
)

# df_monthly.index = df_monthly['month']

df_merge = pd.merge(df_monthly,df_monthly_prec,how='inner', left_index=True, right_index=True)

#---Subplots---------------------------------------------------------------
fig, ax = plt.subplots(figsize=(8,4))

ax.plot(df_merge.index, df_merge["Median ('91-'20)"], color="green", linewidth="1", linestyle="dashed", label = 'Median Snowpack')
ax.plot(df_merge.index, df_merge[f'{curr_wy}'], color='red', linewidth='2',label='WY Current')
#------Seting x-axis range to expand bar width for ax2
ax.bar(df_merge.index,df_merge[basin[i]], color = 'blue', label = 'Monthly %')
#n = n + 1

#--format chart
ax.set_title(chart_name[w], fontweight = 'bold')
w = w + 1
ax.set_ylabel("Basin Precipitation Index")
ax.set_yticklabels([])
ax.margins(x=0)
ax.legend()
#plt.xlim(0,9)

#---Setting date format

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))

#---EXPORT
</code>```

plt.show()

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

End result desired: Plotting both the monthly dataframe (df_monthly_prec) with the daily dataframe charting only monthly values (df_monthly). The bars for the monthly DataFrame should ideally span the whole month on the chart.

I have tried creating a secondary axis, but had trouble aligning the times for the primary and secondary axes. Ideally, I would like to replace plotting df_monthly with df (showing all daily data instead of just the end-of-month values within the daily dataset).

Any assistance or pointers would be much appreciated! Apologies if additional clarification is needed.

Body:
for i in range(len(basin)):

prefix = "URL here"
state = "OR"
basin_name = basin[i]
df_orig = pd.read_csv(f"{prefix}/{basin_name}.csv", index_col=0)

#---create date x-index

curr_wy_date_rng = pd.date_range(
    start=dt(curr_wy-1, 10, 1),
    end=dt(curr_wy, 9, 30),
    freq="D",
)

if not calendar.isleap(curr_wy):
    print("dropping leap day")
    df_orig.drop(["02-29"], inplace=True)

use_cols = ["Median ('91-'20)", f"{curr_wy}"]
df = pd.DataFrame(data=df_orig[use_cols].copy())

df.index = curr_wy_date_rng

#--create EOM percent of median values-------------------------------------

curr_wy_month_rng = pd.date_range(
    start=dt(curr_wy-1, 10, 1),
    end=dt(curr_wy, 6, 30),
    freq="M",
)
df_monthly_prec = pd.DataFrame(data=df_monthly_basin[basin[i]].copy())
df_monthly_prec.index = curr_wy_month_rng

df_monthly = df.groupby(pd.Grouper(freq="M")).max()
df_monthly["date"] = df_monthly.index
df_monthly["wy_date"] = df_monthly["date"].apply(lambda x: cal_to_wy(x))
df_monthly.index = pd.to_datetime(df_monthly["wy_date"])
df_monthly.index = df_monthly["date"]
df_monthly["month"] = df_monthly["date"].apply(
    lambda x: calendar.month_abbr[x.month]
)
df_monthly["wy"] = df_monthly["wy_date"].apply(lambda x: x.year)
df_monthly.sort_values(by="wy_date", axis=0, inplace=True)
df_monthly.drop(
    columns=[i for i in df_monthly.columns if "date" in i], inplace=True
)

# df_monthly.index = df_monthly['month']

df_merge = pd.merge(df_monthly,df_monthly_prec,how='inner', left_index=True, right_index=True)

#---Subplots---------------------------------------------------------------
fig, ax = plt.subplots(figsize=(8,4))

ax.plot(df_merge.index, df_merge["Median ('91-'20)"], color="green", linewidth="1", linestyle="dashed", label = 'Median Snowpack')
ax.plot(df_merge.index, df_merge[f'{curr_wy}'], color='red', linewidth='2',label='WY Current')
#------Seting x-axis range to expand bar width for ax2
ax.bar(df_merge.index,df_merge[basin[i]], color = 'blue', label = 'Monthly %')
#n = n + 1

#--format chart
ax.set_title(chart_name[w], fontweight = 'bold')
w = w + 1
ax.set_ylabel("Basin Precipitation Index")
ax.set_yticklabels([])
ax.margins(x=0)
ax.legend()
#plt.xlim(0,9)

#---Setting date format

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))

#---EXPORT

plt.show()

End result desired: Plotting both the monthly dataframe (df_monthly_prec) with the daily dataframe charting only monthly values (df_monthly). The bars for the monthly DataFrame should ideally span the whole month on the chart.

I have tried creating a secondary axis, but had trouble aligning the times for the primary and secondary axes. Ideally, I would like to replace plotting df_monthly with df (showing all daily data instead of just the end-of-month values within the daily dataset).

Any assistance or pointers would be much appreciated! Apologies if additional clarification is needed.


问:
JQX Multiselect Combobox Not picking up selected value after search
A user searches for a term, they are able to select multiple values from Jquery/Database source in the backend. Once they enter 2 characters, it searches for it in the database. I am encountering an issue after the user search for the first term, selects it and then begins searching for the next term. The result comes in the drop down list, however the drop down menu disappears after selecting the desired value. For some reason the value is not picked up by the code, however it does get picked up after expanding the drop down menu and selecting the item again.

I need assistance on how to fix this issue.

```<code>So far i tried going through documentation from: [JQueryWidgit][1]
No luck on this.
While i was debugging the code i could see that the correct value was being passed in, its just not binding properly after selecting the item for the first time.

  [1]: https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxcombobox/index.htm#demos/jqxcombobox/multiselect.htm
</code>```

Body:
A user searches for a term, they are able to select multiple values from Jquery/Database source in the backend. Once they enter 2 characters, it searches for it in the database. I am encountering an issue after the user search for the first term, selects it and then begins searching for the next term. The result comes in the drop down list, however the drop down menu disappears after selecting the desired value. For some reason the value is not picked up by the code, however it does get picked up after expanding the drop down menu and selecting the item again.

I need assistance on how to fix this issue.

So far i tried going through documentation from: [JQueryWidgit][1]
No luck on this.
While i was debugging the code i could see that the correct value was being passed in, its just not binding properly after selecting the item for the first time.

  [1]: https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxcombobox/index.htm#demos/jqxcombobox/multiselect.htm


问:
How to deploy helm chart with dependencies from Rancher UI
I have troubles deploying some Helm charts with Rancher.
The git repo structure looks like :

/

app

version

charts/ (here are .tgz dependencies charts)

templates/

Chart.yaml

values.yaml

questions.yaml

In my Chart.yaml I have dependencies (Postgres operator + Postgres HA cluster). Doing via CLI "helm dependencies update" and "helm install", everything works great. All services are created it works like a charm.

But I would like to deliver to end user a graphic app catalog via rancher UI, and when I have dependencies, only the main chart is deployed and not dependencies..... I know it is a bit specific, deploying via UI, but does someone already came across this issue ?


问:
When can we expect the Tomcat EE version 10.x support for the Hazelcast Web Session Manager?
When can we expect the Tomcat EE version 10.x support for the Hazelcast Web Session Manager ?

We are using Hazelcast-WM version 4.x i the Tomcat 9.x with Spring 5.x.
We would like to upgrade to Tomcat 10.x with Spring 6.x, when can we expect the Hazelcast-WM support for Tomcat 10.x with Spring 6.x?

Thanks in advance.


问:
What should I do if I get an error message such as: "Connection failed: SQLSTATE[HY000] [2002] No such file or directory"?
I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. I have uploaded all the files in infinityfree for web hosting. I am using Xampp and the connection I am trying to use is this:

```<code>$host="localhost:3306";
$username="root";
$password="";
$dbname="moviedb";

try {
  $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
</code>```

The website appeared but I can't log in or register and there was a message that kept staying in the top left corner of the screen saying:

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

Any help regarding this issue would be really appreciated.

Body:
I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. I have uploaded all the files in infinityfree for web hosting. I am using Xampp and the connection I am trying to use is this:

$host="localhost:3306";
$username="root";
$password="";
$dbname="moviedb";

try {
  $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}

The website appeared but I can't log in or register and there was a message that kept staying in the top left corner of the screen saying:

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

Any help regarding this issue would be really appreciated.


问:
AttributeError: 'int' object has no attribute 'draw_line' in Python Tkinter
so I am trying to create the koch snowflake using python, at the moment I am debugging my code but I get keep getting this error when I try to draw a line. At the moment I am only trying to draw the first iteration of the koch snowflake, so there is no recursion yet.

This is the function for drawing a line on the canvas.

```<code>def draw_line(self, x0, y0, x1, y1):
    self.canv.create_line(x0, y0, x1, y1, fill=self.colour)
</code>```

This is for rotating the points using the rotation matrix by an angle of 60

```<code>def rotate_points(self, xa, ya, xb, yb, angle):
    sin, cos = math.sin(angle), 0.5
    x_c = cos*(xb-xa)-sin*(yb-ya) + xa
    y_c = sin*(xb-xa)+cos*(yb-ya) + ya
    return x_c, y_c
</code>```

This is for calculating the coordinates of the apex of the equilateral triangle of the koch triangle.

```<code>def trisection(self, x_0, y_0, x_1, y_1):
    # calculating one third and 2 thirds of the line segment (x_a, y_a) and (x_b, y_b)
    x_a = (2*x_0)/3 + x_1/3
    y_a = (2*y_0)/3 + y_1/3
    x_b = x_0/3 + (2*x_1)/3
    y_b = y_0/3 + (2*y_1)/3
    return x_a, y_a, x_b, y_b
</code>```

This is for drawing the first iteration of the koch snowflake/curve.

```<code>def draw_base(self):
    xa, ya, xb, yb = self.trisection(0, self.canv_length/2, 500, self.canv_length/2)
    c1, c2 = (xa, ya), (xb, yb)
    xc, yc = self.rotate_points(xa, ya, xb, yb, -60)
    self.canv.draw_line(x0, y0, xa, ya)
</code>```

The last line is where the error displays. But I don't know why. First three functions work perfectly, I have tested them as well, but last function is not.

Body:
so I am trying to create the koch snowflake using python, at the moment I am debugging my code but I get keep getting this error when I try to draw a line. At the moment I am only trying to draw the first iteration of the koch snowflake, so there is no recursion yet.

This is the function for drawing a line on the canvas.

def draw_line(self, x0, y0, x1, y1):
    self.canv.create_line(x0, y0, x1, y1, fill=self.colour)

This is for rotating the points using the rotation matrix by an angle of 60

def rotate_points(self, xa, ya, xb, yb, angle):
    sin, cos = math.sin(angle), 0.5
    x_c = cos*(xb-xa)-sin*(yb-ya) + xa
    y_c = sin*(xb-xa)+cos*(yb-ya) + ya
    return x_c, y_c

This is for calculating the coordinates of the apex of the equilateral triangle of the koch triangle.

def trisection(self, x_0, y_0, x_1, y_1):
    # calculating one third and 2 thirds of the line segment (x_a, y_a) and (x_b, y_b)
    x_a = (2*x_0)/3 + x_1/3
    y_a = (2*y_0)/3 + y_1/3
    x_b = x_0/3 + (2*x_1)/3
    y_b = y_0/3 + (2*y_1)/3
    return x_a, y_a, x_b, y_b

This is for drawing the first iteration of the koch snowflake/curve.

def draw_base(self):
    xa, ya, xb, yb = self.trisection(0, self.canv_length/2, 500, self.canv_length/2)
    c1, c2 = (xa, ya), (xb, yb)
    xc, yc = self.rotate_points(xa, ya, xb, yb, -60)
    self.canv.draw_line(x0, y0, xa, ya)

The last line is where the error displays. But I don't know why. First three functions work perfectly, I have tested them as well, but last function is not.


问:
Finding and element by ID with appium
i've just started using appium with python and i'm a bit confused about getting and element by ID. In the appium inspector, i have this elementID

Following appium's documentation, i tried this

```<code>fin = driver.find_elements(
                AppiumBy.ACCESSIBILITY_ID,
                "00000000-0000-03c4-ffff-ffff000000c5",
            )

            action_user.tap(fin).perform()
</code>```

But it didn't work. I also tried it as "android:id/00000000-0000-03c4-ffff-ffff000000c5". But nothing happen. Is there another way to get this element by the ID?

Title: Finding and element by ID with appium

Body:
i've just started using appium with python and i'm a bit confused about getting and element by ID. In the appium inspector, i have this elementID

Following appium's documentation, i tried this

fin = driver.find_elements(
                AppiumBy.ACCESSIBILITY_ID,
                "00000000-0000-03c4-ffff-ffff000000c5",
            )

            action_user.tap(fin).perform()

But it didn't work. I also tried it as "android:id/00000000-0000-03c4-ffff-ffff000000c5". But nothing happen. Is there another way to get this element by the ID?


问:
EF7 Upgrade - Create Database not working
I started to upgrade my .NET 5/6 applications to .NET 7, I also updated from EF6 to EF7, which seems to be more difficult than expected :-(

I managed to find out that there were breaking changes in the new SqlClient (5.0.1) library, which now forces you to turn off encryption or trust the server certificate:

```<code>Encrypt = false; or TrustServerCertificate = yes
</code>```

After I have set these properties in the connection string, I was again able to connect to my database.

BUT, I am using a code first approach, this means my app is creating / migrating the database if it does not exist or needs migration.

I am now running into the issue that my app is not able to create an empty database anymore. I am still getting an exception

Microsoft.Data.SqlClient.SqlException
Cannot open database "XXX" requested by the login. The login failed.
Login failed for user 'YYY\ZZZ'.

This only happens when I am trying to create a new database.

If I create an empty database (no scheme) manually on my SQL Server Express, all works fine, the scheme gets created and migrations applied. The issue is only the initial creation of the database itself.

Application and SQL Server Express are running on the same machine, SQL Server runs in mixed authentication mode. "Trusted Connection" is enabled in my connection string which looks like this:

```<code>Server =.\\SQLExpress; Database = TEST_DB; Trusted_Connection = Yes; Connection Timeout = 5; Encrypt = false;
</code>```

Before I updated to .NET 7 everything worked fine with the exact same connection string.

Any ideas?

Body:
I started to upgrade my .NET 5/6 applications to .NET 7, I also updated from EF6 to EF7, which seems to be more difficult than expected :-(

I managed to find out that there were breaking changes in the new SqlClient (5.0.1) library, which now forces you to turn off encryption or trust the server certificate:

Encrypt = false; or TrustServerCertificate = yes

After I have set these properties in the connection string, I was again able to connect to my database.

BUT, I am using a code first approach, this means my app is creating / migrating the database if it does not exist or needs migration.

I am now running into the issue that my app is not able to create an empty database anymore. I am still getting an exception

Microsoft.Data.SqlClient.SqlException
Cannot open database "XXX" requested by the login. The login failed.
Login failed for user 'YYY\ZZZ'.

This only happens when I am trying to create a new database.

If I create an empty database (no scheme) manually on my SQL Server Express, all works fine, the scheme gets created and migrations applied. The issue is only the initial creation of the database itself.

Application and SQL Server Express are running on the same machine, SQL Server runs in mixed authentication mode. "Trusted Connection" is enabled in my connection string which looks like this:

Server =.\\SQLExpress; Database = TEST_DB; Trusted_Connection = Yes; Connection Timeout = 5; Encrypt = false;

Before I updated to .NET 7 everything worked fine with the exact same connection string.

Any ideas?