问:
springboot download file, the bowser is loaded all at once into memory
In springboot,backend is cyclically written to the response outputstream,but the bowser is loaded all at once into memory and then written to the hard drive，why is exist this thing?

my code as follow:

```<code>File file = new File(filePath);
if (!file.exists()) {
    return ResponseDTO.wrap(FileResponseCodeConst.FILE_NOT_EXIST);
}
response.reset();
response.setContentLength((int) file.length());
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName + filePath.substring(filePath.lastIndexOf(".")), "UTF-8"));

response.setHeader("Access-Control-Allow-Origin", "*");
response.setBufferSize(64*1024);
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)))
{
    byte[] buff = new byte[1024];
    OutputStream os = response.getOutputStream();
    int i=0;
    while ((i = bis.read(buff)) != -1) {
        os.write(buff, 0, i);
        os.flush();
    }
    bis.close();
    os.close();
} catch (IOException e) {
    logger.error("{}", e);
    e.printStackTrace();
    return ResponseDTO.wrap(FileResponseCodeConst.FILE_DOWNLOAD_ERROR);
}

return ResponseDTO.succMsg(FileResponseCodeConst.FILE_DOWNLOAD_SUCCESS);
</code>```
```<code>export const getDownloadAxios = (url) => {
  return axios.get(url, { responseType: 'blob' });
};
</code>```

fix this bug,i did not find this problem

Body:
In springboot,backend is cyclically written to the response outputstream,but the bowser is loaded all at once into memory and then written to the hard drive，why is exist this thing?

my code as follow:

File file = new File(filePath);
if (!file.exists()) {
    return ResponseDTO.wrap(FileResponseCodeConst.FILE_NOT_EXIST);
}
response.reset();
response.setContentLength((int) file.length());
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName + filePath.substring(filePath.lastIndexOf(".")), "UTF-8"));

response.setHeader("Access-Control-Allow-Origin", "*");
response.setBufferSize(64*1024);
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)))
{
    byte[] buff = new byte[1024];
    OutputStream os = response.getOutputStream();
    int i=0;
    while ((i = bis.read(buff)) != -1) {
        os.write(buff, 0, i);
        os.flush();
    }
    bis.close();
    os.close();
} catch (IOException e) {
    logger.error("{}", e);
    e.printStackTrace();
    return ResponseDTO.wrap(FileResponseCodeConst.FILE_DOWNLOAD_ERROR);
}

return ResponseDTO.succMsg(FileResponseCodeConst.FILE_DOWNLOAD_SUCCESS);

export const getDownloadAxios = (url) => {
  return axios.get(url, { responseType: 'blob' });
};

fix this bug,i did not find this problem


来源: stackexchange

问:
How rewrite root path for static file of vue in the Nginx?
I have a packaged static file of Vue that directory structure like this:

```<code>public
   assets
      css
      js
      fonts
      img
   favicon.ico
   index.html
</code>```

And I want to use Nginx to implement when I access 'http://localhost:8080/min', it will handle the public directory. So I've written these configs,

```<code>
location /min {
     alias /opt/homebrew/var/www/public;
}

or
location /min {
     alias /opt/homebrew/var/www/public;
     try_files $uri $uri/ =404;
}

</code>```

but they are not working.
When I access http://localhost:8080/min, it shows me a blank page even though I've inspected it in the network panel, status of all static files is 200.

And then, try to direct access without min worked, like this:

```<code>location / {
    root /opt/homebrew/var/www/public;
}
</code>```

but this is not my expectation. I hope to append min to the URL.

I have no clue how to do this. Thank you for your help.

------------------------- update  -----------------

I find the nuance between displaying the blank and not the blank situation is the image not loaded when displaying blank, those images are referenced in css/app-xxxx.css by relative path(eg: ../../assets/img/xx.jpg). It seems to be a reason because actually, the blank page is not empty completely, it looks like just missing these images. So, Why do images cannot be loaded when using the alias?

ContentLicense: CC BY-SA 4.0

Body:
I have a packaged static file of Vue that directory structure like this:

public
   assets
      css
      js
      fonts
      img
   favicon.ico
   index.html

And I want to use Nginx to implement when I access 'http://localhost:8080/min', it will handle the public directory. So I've written these configs,

location /min {
     alias /opt/homebrew/var/www/public;
}

or
location /min {
     alias /opt/homebrew/var/www/public;
     try_files $uri $uri/ =404;
}

but they are not working.
When I access http://localhost:8080/min, it shows me a blank page even though I've inspected it in the network panel, status of all static files is 200.

And then, try to direct access without min worked, like this:

location / {
    root /opt/homebrew/var/www/public;
}

but this is not my expectation. I hope to append min to the URL.

I have no clue how to do this. Thank you for your help.

------------------------- update  -----------------

I find the nuance between displaying the blank and not the blank situation is the image not loaded when displaying blank, those images are referenced in css/app-xxxx.css by relative path(eg: ../../assets/img/xx.jpg). It seems to be a reason because actually, the blank page is not empty completely, it looks like just missing these images. So, Why do images cannot be loaded when using the alias?


问:
Flutter iOS Universal link only opens the app but is not handled

Using uni_links package;

Configured the app to use Universal link and Custom links. For Universal link added ios/Runner/Runner.entitlements which looks like as below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.associated-domains</key>
    <array>
        <string>applinks:myapp.page.link</string>
    </array>
</dict>
</plist>

```

Configured uriLinkStream and getInitialUri;

In the end, when I get from Firebase a link for verifying email, e.g. https://myapp.page.link/__/auth/action?mode=verifyEmail&.... I try to open this Universal link from some email app then iOS navigates me to my app, but the app does not get the link with uriLinkStream to handle it. But if I change the mentioned link into a Custom link as myapp://__/auth/action?mode=verifyEmail&.... my app handles the Custom link as expected.

Shortly,

tapping on Universal link only opens the app, but not handled for further processing.

Custom link is working as expected.

What could I be missing for Universal link?

Body:
Using uni_links package;

Configured the app to use Universal link and Custom links. For Universal link added ios/Runner/Runner.entitlements which looks like as below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.associated-domains</key>
    <array>
        <string>applinks:myapp.page.link</string>
    </array>
</dict>
</plist>

Configured uriLinkStream and getInitialUri;

In the end, when I get from Firebase a link for verifying email, e.g. https://myapp.page.link/__/auth/action?mode=verifyEmail&.... I try to open this Universal link from some email app then iOS navigates me to my app, but the app does not get the link with uriLinkStream to handle it. But if I change the mentioned link into a Custom link as myapp://__/auth/action?mode=verifyEmail&.... my app handles the Custom link as expected.

Shortly,

tapping on Universal link only opens the app, but not handled for further processing.

Custom link is working as expected.

What could I be missing for Universal link?


问:
Openresty nginx load balancing for Critical finanacial requests
I have been working with financial application and have used openresty nginx for load balancing,

my current upstream configuration is :

```<code>upstream backend
    {
        server a.example.com;
        server b.example.com;

        keepalive 512;
    }
</code>```

this configuration is doing load balance in simple round robin, i want to add timeout configuration for example, if request N1 is forwarded to a.example.com and there is no response for request N1 in 30s then request N1 should be failed and request N1 should not be forwarded to b.example.com and next request N2 should be forwarded to b.example.com as a.example.com is taking more than decided time to respond.

reason for this is, i am dealing with financial requests, if request is forwarded to a.example.com and there is no response for this request in 30 seconds due to any reason, i will consider it as Timeout request, but there is possibility that request reached to a.example.com and completed within 60 seconds so if same request is forwarded to b.example.com after initial 30 seconds there possibility of duplicate transaction.

Please suggest me configuration for this

Body:
I have been working with financial application and have used openresty nginx for load balancing,

my current upstream configuration is :

upstream backend
    {
        server a.example.com;
        server b.example.com;

        keepalive 512;
    }

this configuration is doing load balance in simple round robin, i want to add timeout configuration for example, if request N1 is forwarded to a.example.com and there is no response for request N1 in 30s then request N1 should be failed and request N1 should not be forwarded to b.example.com and next request N2 should be forwarded to b.example.com as a.example.com is taking more than decided time to respond.

reason for this is, i am dealing with financial requests, if request is forwarded to a.example.com and there is no response for this request in 30 seconds due to any reason, i will consider it as Timeout request, but there is possibility that request reached to a.example.com and completed within 60 seconds so if same request is forwarded to b.example.com after initial 30 seconds there possibility of duplicate transaction.

Please suggest me configuration for this


问:
linux - how to get a stack trace when a memory address is written to
I have a memory corruption in my c/c++ program which causes a segfault. this was reproduced a few times and the same address gets corrupted every time.

Is there any way I can call a function when this address is written to? I tried using hwbp_lib https://github.com/hawkinsw/hwbp_lib , but my callback doesn't get called when I write to the requested memory address after setting the breakpoint.

I am running on an x86 intel.


问:
Setting "this" in a class constructor
Similar to how you can call __init__ on anything in python

class Class():
    def __init__(self, a):
        self["a"] = a
dic = { "a": 0 } # create dict
Class.__init__(dic, 5); # "init" the dict
print(dic) # value "a" changes
```
<p>How would you call <code>constructor</code> on anything in javscript (ie change <code>this</code>, before calling the constructor)
The old way was apparently to use <code>.call</code></p>
<pre class="lang-js prettyprint-override"><code><class>.call(<new this>, <arguments>)
</code>```

However this no longer, works giving an error:

```<code>Class constructor <class> cannot be invoked without 'new'
</code>```

I have thought of a way to do this by creating the class normally with new then copying the key, pair values to this, but that seems incredibly slow.
I'm trying to get PhysiJS to run but it's an ancient codebase, and this is one of many offending lines of code which breaks it:

THREE.Scene.call( this );
```

Title: Setting "this" in a class constructor

Body:
Similar to how you can call __init__ on anything in python

class Class():
    def __init__(self, a):
        self["a"] = a
dic = { "a": 0 } # create dict
Class.__init__(dic, 5); # "init" the dict
print(dic) # value "a" changes

How would you call constructor on anything in javscript (ie change this, before calling the constructor)
The old way was apparently to use .call

<class>.call(<new this>, <arguments>)

However this no longer, works giving an error:

Class constructor <class> cannot be invoked without 'new'

I have thought of a way to do this by creating the class normally with new then copying the key, pair values to this, but that seems incredibly slow.
I'm trying to get PhysiJS to run but it's an ancient codebase, and this is one of many offending lines of code which breaks it:

THREE.Scene.call( this );


问:
Can I have the slow stochastic function to ignore bars during certain hours?
I would like to have a slow stochastic indicator with inputs of (13, 3, 1) in a 5-minute chart for regular sessions only.  To be specific, in my example with parameter (13, 3, 1), I want the 13 bars being counted as if the bars fall outside the regular sessions 0915-1630 does not exist.

I tried the below scripts but it does not work.  The first bar during regular session still takes the previous 13 bars which were within the night hours, which was not what I wanted.  I expected that the indicator's parameters "13" and "3" recent bars being counted as if the night hours does not exist.

Result of chart plotted

```<code>//@version=5
indicator(title="Stoch (Daytime)", shorttitle="Stoch (D)", format=format.price, precision=2, timeframe="", timeframe_gaps=true)

//@time condition (testing)
t = time(timeframe.period, "0915-1630")
time_cond = not na(t)

periodK = input.int(13, title="%K Length", minval=1)
smoothK = input.int(3, title="%K Smoothing", minval=1)
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
plot(time_cond ? k:na, title="%K", color=#ff7f29)
</code>```

Body:
I would like to have a slow stochastic indicator with inputs of (13, 3, 1) in a 5-minute chart for regular sessions only.  To be specific, in my example with parameter (13, 3, 1), I want the 13 bars being counted as if the bars fall outside the regular sessions 0915-1630 does not exist.

I tried the below scripts but it does not work.  The first bar during regular session still takes the previous 13 bars which were within the night hours, which was not what I wanted.  I expected that the indicator's parameters "13" and "3" recent bars being counted as if the night hours does not exist.

Result of chart plotted

//@version=5
indicator(title="Stoch (Daytime)", shorttitle="Stoch (D)", format=format.price, precision=2, timeframe="", timeframe_gaps=true)

//@time condition (testing)
t = time(timeframe.period, "0915-1630")
time_cond = not na(t)

periodK = input.int(13, title="%K Length", minval=1)
smoothK = input.int(3, title="%K Smoothing", minval=1)
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
plot(time_cond ? k:na, title="%K", color=#ff7f29)


问:
How to rate limit a route that contains url parameters in express js?
I use the npm package express-rate-limit to limit the routes of my Express.js app.

Routes that contain a URL parameter are limited regardless of the value of the paramter
is limited. For example, if I limit /api/posts/editPost/:postId to one request per 15 minutes, the following requests cannot be executed independently:

```<code>/api/posts/editPost/t3xEu

/api/posts/editPost/b4EH
</code>```

I have to wait 15 minutes before I can make the second request, even though the URL parameter and thus the entire path looks different.

Is there a way that only URL parameter specific paths are limited?

Here's how I used the Rate Limit middleware:

const oneTimeLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 1,
  message: { message: "Too Many Requests" },
  standardHeaders: true,
  legacyHeaders: false,
});

router.route("api/edit/:postId").put(oneTimeLimiter, async (req, res) =\> {});
```

Body:
I use the npm package express-rate-limit to limit the routes of my Express.js app.

Routes that contain a URL parameter are limited regardless of the value of the paramter
is limited. For example, if I limit /api/posts/editPost/:postId to one request per 15 minutes, the following requests cannot be executed independently:

/api/posts/editPost/t3xEu

/api/posts/editPost/b4EH

I have to wait 15 minutes before I can make the second request, even though the URL parameter and thus the entire path looks different.

Is there a way that only URL parameter specific paths are limited?

Here's how I used the Rate Limit middleware:

const oneTimeLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 1,
  message: { message: "Too Many Requests" },
  standardHeaders: true,
  legacyHeaders: false,
});

router.route("api/edit/:postId").put(oneTimeLimiter, async (req, res) =\> {});


问:
How can reduce the white space of the Salesforce object record detail page
How we do something like this?

This looks more good than regualr wide spaces of default org

I tried using Density Setting from User Interface but it didn't work as I expected


问:
Resource.NotFoundException even when drawable is present in all 6 drawable folder
I know there are a bunch of similar questions on stackoverflow but none of them seem to solve my problem.

The problems previously mentioned always have some place where the drawable is missing. Which is not the case with this project.

The line number being pointed in error log leads me to this textView which has a 9-patch image as a background

The Layout

<TextView
    android:clickable="true"
    android:focusable="true"
    android:id="@+id/update_available"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|start"
    android:background="@drawable/tab_white_left_9"
    android:text="@string/update_available"
    android:textColor="@android:color/white"
    android:backgroundTint="@color/lead_color"
    app:drawableStartCompat="@drawable/ic_download"
    android:drawablePadding="@dimen/margin_5"
    android:paddingStart="@dimen/margin_5"
    style="@style/text_bold_11"
    app:drawableTint="@android:color/white"
    android:visibility="gone"/>
```
<p><strong>Drawable Locations</strong></p>
<ul>
<li>res/drawable-ldpi/tab_white_left_9.9.png</li>
<li>res/drawable-mdpi/tab_white_left_9.9.png</li>
<li>res/drawable-hdpi/tab_white_left_9.9.png</li>
<li>res/drawable-xhdpi/tab_white_left_9.9.png</li>
<li>res/drawable-xxhdpi/tab_white_left_9.9.png</li>
<li>res/drawable-xxxhdpi/tab_white_left_9.9.png</li>
</ul>
<p><strong>Error Logs</strong></p>
```Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{in.callific.quickinsure/in.callific.quickinsure.activity.HomeScreenActivityV2}: android.view.InflateException: Binary XML file line #16 in in.callific.quickinsure:layout/activity_home_screen_v2: Binary XML file line #580 in in.callific.quickinsure:layout/content_home_screen_activity_v2: Error inflating class TextView
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3813)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3975)
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2377)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:233)
       at android.os.Looper.loop(Looper.java:344)
       at android.app.ActivityThread.main(ActivityThread.java:8204)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)
```
```Caused by android.view.InflateException: Binary XML file line #16 in in.callific.quickinsure:layout/activity_home_screen_v2: Binary XML file line #580 in in.callific.quickinsure:layout/content_home_screen_activity_v2: Error inflating class TextView

Caused by android.view.InflateException: Binary XML file line #580 in in.callific.quickinsure:layout/content_home_screen_activity_v2: Error inflating class TextView

Caused by android.content.res.Resources$NotFoundException: Drawable (missing name) with resource ID #0x7f0802ba

Caused by android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f0802ba
       at android.content.res.ResourcesImpl.getResourceName(ResourcesImpl.java:296)
       at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:895)
       at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:735)
       at android.content.res.Resources.loadDrawable(Resources.java:1012)
       at android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:1007)
       at android.content.res.TypedArray.getDrawable(TypedArray.java:982)
       at android.view.View.<init>(View.java:5559)
       at android.widget.TextView.<init>(TextView.java:1054)
       at android.widget.TextView.<init>(TextView.java:1048)
       at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:108)
       at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:103)
       at androidx.appcompat.app.AppCompatViewInflater.createTextView(AppCompatViewInflater.java:201)
       at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:121)
       at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1569)
       at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1620)
       at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1071)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1001)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1144)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1147)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1147)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1284)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1140)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1284)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1140)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
       at in.callific.quickinsure.databinding.ActivityHomeScreenV2Binding.inflate(ActivityHomeScreenV2Binding.java:59)
       at in.callific.quickinsure.databinding.ActivityHomeScreenV2Binding.inflate(ActivityHomeScreenV2Binding.java:53)
       at in.callific.quickinsure.activity.HomeScreenActivity.onCreate(HomeScreenActivity.kt:174)
       at in.callific.quickinsure.activity.HomeScreenActivityV2.onCreate(HomeScreenActivityV2.kt:83)
       at android.app.Activity.performCreate(Activity.java:8130)
       at android.app.Activity.performCreate(Activity.java:8110)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1343)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3975)
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2377)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:233)
       at android.os.Looper.loop(Looper.java:344)
       at android.app.ActivityThread.main(ActivityThread.java:8204)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)
```

When similar exceptions were raised for other drawables in this project, I switched to using vector drawables for those images, but this drawable being a 9-patch image cannot be converted to a vector image.

Edit:

Placing a low-res tab_white_left_9 in the default drawable folder /res/drawable solved this issue, still, a better solution for this problem would be appreciated as now there are duplicate drawables present for any particular resolution.

Body:
I know there are a bunch of similar questions on stackoverflow but none of them seem to solve my problem.

The problems previously mentioned always have some place where the drawable is missing. Which is not the case with this project.

The line number being pointed in error log leads me to this textView which has a 9-patch image as a background

The Layout

<TextView
    android:clickable="true"
    android:focusable="true"
    android:id="@+id/update_available"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|start"
    android:background="@drawable/tab_white_left_9"
    android:text="@string/update_available"
    android:textColor="@android:color/white"
    android:backgroundTint="@color/lead_color"
    app:drawableStartCompat="@drawable/ic_download"
    android:drawablePadding="@dimen/margin_5"
    android:paddingStart="@dimen/margin_5"
    style="@style/text_bold_11"
    app:drawableTint="@android:color/white"
    android:visibility="gone"/>

Drawable Locations

res/drawable-ldpi/tab_white_left_9.9.png

res/drawable-mdpi/tab_white_left_9.9.png

res/drawable-hdpi/tab_white_left_9.9.png

res/drawable-xhdpi/tab_white_left_9.9.png

res/drawable-xxhdpi/tab_white_left_9.9.png

res/drawable-xxxhdpi/tab_white_left_9.9.png

Error Logs

Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{in.callific.quickinsure/in.callific.quickinsure.activity.HomeScreenActivityV2}: android.view.InflateException: Binary XML file line #16 in in.callific.quickinsure:layout/activity_home_screen_v2: Binary XML file line #580 in in.callific.quickinsure:layout/content_home_screen_activity_v2: Error inflating class TextView
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3813)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3975)
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2377)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:233)
       at android.os.Looper.loop(Looper.java:344)
       at android.app.ActivityThread.main(ActivityThread.java:8204)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)

Caused by android.view.InflateException: Binary XML file line #16 in in.callific.quickinsure:layout/activity_home_screen_v2: Binary XML file line #580 in in.callific.quickinsure:layout/content_home_screen_activity_v2: Error inflating class TextView

Caused by android.view.InflateException: Binary XML file line #580 in in.callific.quickinsure:layout/content_home_screen_activity_v2: Error inflating class TextView

Caused by android.content.res.Resources$NotFoundException: Drawable (missing name) with resource ID #0x7f0802ba

Caused by android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f0802ba
       at android.content.res.ResourcesImpl.getResourceName(ResourcesImpl.java:296)
       at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:895)
       at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:735)
       at android.content.res.Resources.loadDrawable(Resources.java:1012)
       at android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:1007)
       at android.content.res.TypedArray.getDrawable(TypedArray.java:982)
       at android.view.View.<init>(View.java:5559)
       at android.widget.TextView.<init>(TextView.java:1054)
       at android.widget.TextView.<init>(TextView.java:1048)
       at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:108)
       at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:103)
       at androidx.appcompat.app.AppCompatViewInflater.createTextView(AppCompatViewInflater.java:201)
       at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:121)
       at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1569)
       at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1620)
       at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1071)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1001)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1144)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1147)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1147)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1284)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1140)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1284)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:1140)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1105)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
       at in.callific.quickinsure.databinding.ActivityHomeScreenV2Binding.inflate(ActivityHomeScreenV2Binding.java:59)
       at in.callific.quickinsure.databinding.ActivityHomeScreenV2Binding.inflate(ActivityHomeScreenV2Binding.java:53)
       at in.callific.quickinsure.activity.HomeScreenActivity.onCreate(HomeScreenActivity.kt:174)
       at in.callific.quickinsure.activity.HomeScreenActivityV2.onCreate(HomeScreenActivityV2.kt:83)
       at android.app.Activity.performCreate(Activity.java:8130)
       at android.app.Activity.performCreate(Activity.java:8110)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1343)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3975)
       at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
       at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
       at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2377)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:233)
       at android.os.Looper.loop(Looper.java:344)
       at android.app.ActivityThread.main(ActivityThread.java:8204)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)

When similar exceptions were raised for other drawables in this project, I switched to using vector drawables for those images, but this drawable being a 9-patch image cannot be converted to a vector image.

Edit:

Placing a low-res tab_white_left_9 in the default drawable folder /res/drawable solved this issue, still, a better solution for this problem would be appreciated as now there are duplicate drawables present for any particular resolution.


问:
Plotly - how to fill area of trace1 up to the y value of trace0 when they use different y axis
In plotly, I am plotting two traces.
trace0 is temperature: This has auto-range on the y axis and continious values say 14-20 in the y axis. x axis is continious time. Yaxis0 is drawn on the left side.

trace1 is a binary input that is either 0 or 100 in the y axis. x axis also time. I use yaxis1 on the right side.

What I want to do in plotly is similar to this image:

Here trace1 is presented as a fill without a line starting from 0, and it has been bounded on the upper side by the Y value of trace0.

I would appreciate any help on how to re-create this style of graph in plotly.
Either to auto-range each value so that 100 maps to the trace0 max for each trace1 value, or to cut-off the fill up to trace1 y in some way.

I have tried creating a stacked graph but I cant get it work correctly.


问:
Number of cache accesses when miss occurs
In case of a cache miss, the cache is accessed a second time, when the data will be available.

If I want to compute the miss-rate, do I have to consider this second access in the total accesses to the cache?

Because it leads to two possible scenarios:

Second access is considered: 1 access + 1 miss + 1 access -> miss-rate = 0.5

Second access is NOT considered: 1 access + 1 miss -> miss-rate = 1


问:
flutter when i run the razor pay throw build error
i'm creating a payment gateway in my app using razor pay but app build faild

```<code>`FAILURE: Build failed with an exception.
</code>```

What went wrong:
Execution failed for task ':app:mergeDebugAssets'.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Could not resolve com.razorpay:checkout:1.6.+.
Required by:
project :app > project :razorpay_flutter
> Failed to list versions for com.razorpay:checkout.
> Unable to load Maven meta-data from https://www.jitpack.io/com/razorpay/checkout/maven-metadata.xml.
> Could not GET 'https://www.jitpack.io/com/razorpay/checkout/maven-metadata.xml'. Received status code 521 from server:

Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 53s
Exception: Gradle task assembleDebug failed with exit code 1`

Body:
i'm creating a payment gateway in my app using razor pay but app build faild

`FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:mergeDebugAssets'.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Could not resolve com.razorpay:checkout:1.6.+.
Required by:
project :app > project :razorpay_flutter
> Failed to list versions for com.razorpay:checkout.
> Unable to load Maven meta-data from https://www.jitpack.io/com/razorpay/checkout/maven-metadata.xml.
> Could not GET 'https://www.jitpack.io/com/razorpay/checkout/maven-metadata.xml'. Received status code 521 from server:

Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 53s
Exception: Gradle task assembleDebug failed with exit code 1`


问:
Is it possible in Javascript to get data only with a callback function?
I am new to Javascript so maybe the question even doesn't make sense, but I wonder, before Promise and Fetch, how could one bring a data from another site?</p>


问:
Unable to download maven fmt-maven-plugin dependency
I am trying to add fmt-maven-plugin (https://mvnrepository.com/artifact/com.coveo/fmt-maven-plugin/2.13) as dependency so I added below code in my POM xml file

```<code><dependency>
    <groupId>com.coveo</groupId>
    <artifactId>fmt-maven-plugin</artifactId>
    <version>2.13</version>
</dependency>
</code>```

Also I have below repo details in my settings.xml

```<code><profile>
  <id>maven-https</id>
  <activation>
      <activeByDefault>true</activeByDefault>
  </activation>
  <repositories>
      <repository>
          <id>central</id>
          <url>https://repo1.maven.org/maven2</url>
          <snapshots>
              <enabled>false</enabled>
          </snapshots>
      </repository>
  </repositories>
  <pluginRepositories>
      <pluginRepository>
          <id>central</id>
          <url>https://repo1.maven.org/maven2</url>
          <snapshots>
              <enabled>false</enabled>
          </snapshots>
      </pluginRepository>
  </pluginRepositories>
</code>```

But I get below error while running build,

[ERROR] Plugin com.spotify.fmt:fmt-maven-plugin:2.13 or one of its dependencies could not be resolved: Could not find artifact com.spotify.fmt:fmt-maven-plugin:jar:2.13 in central (https://repo1.maven.org/maven2) -> [Help 1]

My understanding is maven could not download fmt-maven-plugin:2.13 from given https://repo1.maven.org/maven2 repo but I am not sure what repo to add in order to download fmt-maven-plugin. Can anyone suggest me?

Body:
I am trying to add fmt-maven-plugin (https://mvnrepository.com/artifact/com.coveo/fmt-maven-plugin/2.13) as dependency so I added below code in my POM xml file

<dependency>
    <groupId>com.coveo</groupId>
    <artifactId>fmt-maven-plugin</artifactId>
    <version>2.13</version>
</dependency>

Also I have below repo details in my settings.xml

<profile>
  <id>maven-https</id>
  <activation>
      <activeByDefault>true</activeByDefault>
  </activation>
  <repositories>
      <repository>
          <id>central</id>
          <url>https://repo1.maven.org/maven2</url>
          <snapshots>
              <enabled>false</enabled>
          </snapshots>
      </repository>
  </repositories>
  <pluginRepositories>
      <pluginRepository>
          <id>central</id>
          <url>https://repo1.maven.org/maven2</url>
          <snapshots>
              <enabled>false</enabled>
          </snapshots>
      </pluginRepository>
  </pluginRepositories>

But I get below error while running build,

[ERROR] Plugin com.spotify.fmt:fmt-maven-plugin:2.13 or one of its dependencies could not be resolved: Could not find artifact com.spotify.fmt:fmt-maven-plugin:jar:2.13 in central (https://repo1.maven.org/maven2) -> [Help 1]

My understanding is maven could not download fmt-maven-plugin:2.13 from given https://repo1.maven.org/maven2 repo but I am not sure what repo to add in order to download fmt-maven-plugin. Can anyone suggest me?


问:
how can i select file with several directories below?
i'm very new to this so apologies for my simple question. I tried a few things but failed. Let's say I'm in directory a. I have files under my 2 directories that I need to select and process. but when i try to do it it says file not found.

The extension of the files is gz. by the way, the file name is also long and changes according to the directory it is in. This is the first step of what I have to do. After doing this, I need to do other things in the same loop.

```<code>#!/bin/bash

for k in {1..9}; do
rnxEditGde.py -data "y2019/d${k}/*.gz" -o dataRecordFile.Orig.gz
rinex2StaDb.py "y2019/d${k}/*.gz" -outFile sta.sta_db
done
</code>```

Body:
i'm very new to this so apologies for my simple question. I tried a few things but failed. Let's say I'm in directory a. I have files under my 2 directories that I need to select and process. but when i try to do it it says file not found.

The extension of the files is gz. by the way, the file name is also long and changes according to the directory it is in. This is the first step of what I have to do. After doing this, I need to do other things in the same loop.

#!/bin/bash

for k in {1..9}; do
rnxEditGde.py -data "y2019/d${k}/*.gz" -o dataRecordFile.Orig.gz
rinex2StaDb.py "y2019/d${k}/*.gz" -outFile sta.sta_db
done


问:
How do i retrieve a data from php in godot?
I'm trying to get a data from php in my local server. from godot side it just works fine I can download an image. but when I'm trying to make a connection to a php I always get a HTTP error 405.

I've setup my godot and everything, and this is my code.

get_data.php

<?php
    $item_db = file_get_contents("item_db.json");
    if (isset($_SERVER['HTTP_ORIGIN'])){
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Max-Age: 60");

        if ($_SERVER["REQUEST_METHOD"] === "OPTIONS"){
            header("Access-Control-Allow-Methods: POST, OPTIONS");
            header("Access-Control-Allow-Headers: Authorization,
            Content-Type, Accept, Origin, cache-control");
            http_response_code(200);
            die;
        }
    }
    if ($_SERVER['REQUEST_METHOD'] !== "POST"){
        http_response_code(405);
        die;
    }
    switch ($_REQUEST['command']){
        case "add":
            echo "add item";
        break;

        case "edit":
            echo "edit item";
        break;
    }
?>
```
<p><code>gdscript</code></p>
<pre class="lang-java prettyprint-override"><code>    $HTTPRequest.request("http://localhost/get_data.php",
    ["Content-Type: application/x-www-form-urlencoded",
        "Cache-Control: max-age=0"],
        false,
    HTTPClient.METHOD_POST,
    "command=edit"
    )
</code>```

Body:
I'm trying to get a data from php in my local server. from godot side it just works fine I can download an image. but when I'm trying to make a connection to a php I always get a HTTP error 405.

I've setup my godot and everything, and this is my code.

get_data.php

<?php
    $item_db = file_get_contents("item_db.json");
    if (isset($_SERVER['HTTP_ORIGIN'])){
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Max-Age: 60");

        if ($_SERVER["REQUEST_METHOD"] === "OPTIONS"){
            header("Access-Control-Allow-Methods: POST, OPTIONS");
            header("Access-Control-Allow-Headers: Authorization,
            Content-Type, Accept, Origin, cache-control");
            http_response_code(200);
            die;
        }
    }
    if ($_SERVER['REQUEST_METHOD'] !== "POST"){
        http_response_code(405);
        die;
    }
    switch ($_REQUEST['command']){
        case "add":
            echo "add item";
        break;

        case "edit":
            echo "edit item";
        break;
    }
?>

gdscript

    $HTTPRequest.request("http://localhost/get_data.php",
    ["Content-Type: application/x-www-form-urlencoded",
        "Cache-Control: max-age=0"],
        false,
    HTTPClient.METHOD_POST,
    "command=edit"
    )


问:
Chrome/Edge/Safari - HTTP2 Requests getting stalled for every 6th request for upto 2 mins on IIS 10
We have a .Net 5 WebAPI's deployed on IIS 10 server in a Window 2022 server. ReactJS front end application was developed to consume those WebAPI's.

While navigating through pages, every 6th request is taking upto 2 mins time to complete/provide a response and this is happening in Chrome/Edge/Safari browsers, but working fine on Firefox browser. On verifying the chrome developer tools, the stalled time is taking the 99% of the time consumed.NOTE: Each page has single HTTP request.

On further digging, we have found out that the IIS site has http2 protocol enabled. Once the http2 protocol is disabled, the application is working flawlessly.

For now, we have disabled the http2 protocol, but still wanted to understand what could be the issue with the http2 protocol enabled on the server.

Any help would be highly appreciated!


问:
Tkintermapview only show map with window.mainloop(), but i need to use wind.update()
My tkinter gui I made works like it should, but when I added a map with tkintermapview is doesn't show me the map. Instead it only shows me, under my standard GUI inputboxes, a zoom button with markers that I added, but no map. GUI with marks but no map

I found out where the problem is I use window.update to do other things in my code like logging the serial port. But when I use window.mainloop() the map does show, but I cant have an while loop any more. This because mainloop() works on an event and update() happens every iteration.

import tkinter
from tkintermapview import TkinterMapView

window = tkinter.Tk()
window.title("Salinity data logger")
frame = tkinter.Frame(window)
frame.pack()

user_info_frame = tkinter.LabelFrame(frame,text="Data storage")
user_info_frame.grid(row=0, column=0, padx=20, pady=10)

file_location_label = tkinter.Label(user_info_frame, text="File location")
file_location_label.grid(row=0, column=0)
file_name_label = tkinter.Label(user_info_frame, text="File name")
file_name_label.grid(row=0, column=1)

file_location_entry = tkinter.Entry(user_info_frame)
file_name_entry = tkinter.Entry(user_info_frame)
file_location_entry.grid(row=1, column=0)
file_name_entry.grid(row=1, column=1)

for widget in user_info_frame.winfo_children():
    widget.grid_configure(padx=20, pady=5)

# Part of the code for the map
map_frame = tkinter.Frame(frame)
map_frame.grid(row=5, column=0, padx=20, pady=10)
map_widget = TkinterMapView(window, width=600, height=400, corner_radius=0)
map_widget.pack(fill="both", expand=True)
map_widget.set_tile_server("https://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22)
map_widget.set_address("Berlin Germany", marker=True)
map_widget.set_address("Potsdam Germany", marker=True)

while True:
    window.update()
    # do some other things like reading serialport for data input
```


问:
Invalid Argument Error / Graph Execut ion Error by [[{{node CTCLoss/CTCLoss}}]] [Op:__inference_train_function_66347]

Anyperson can solve this problem in audio .Thank you in advance


问:
How to make an app in script editor that executes a javascript and also a shell script?
I have an app that is compiled in automator for MacOS.
it executes a javascript and then shell script. It is a bit slow though to execute and i noticed that apps compiled in script editor instead are faster to execute. how do i make an app in script that executes this javascript and shell script ?

#!/usr/bin/env osascript -l JavaScript
function run(input) {
    const app = Application.currentApplication();
    app.includeStandardAdditions = true;

    const obsidianJsonFilePath = app.pathTo("home folder") + "/Library/Application Support/obsidian/obsidian.json";
    const vaults = JSON.parse(app.read(obsidianJsonFilePath)).vaults;

    let openInObsi = false;
    const pathArray = input.toString().split(",");
    const toOpen = [];
    pathArray.forEach(filePath => {
        const isFileInObsidianVault = Object.values(vaults).some(v => filePath.startsWith(v.path));
        if (isFileInObsidianVault && !filePath.includes("/.")) { // second condition prevents the opening of files in .obsidian or .trash
            toOpen.push("obsidian://open?path=" + encodeURIComponent(filePath));
            openInObsi = true;
        }
        else toOpen.push(filePath);
    });
    return [openInObsi.toString(), ...toOpen];

}
```
<p>Shell Script</p>
<pre class="lang-bash prettyprint-override"><code>if $1 ; then
    open "$2"
else
    open -a "Obsidian" "${@:2}"
fi
</code>```

Didn't tried anything, because I am not familiar with this code.

Body:
I have an app that is compiled in automator for MacOS.
it executes a javascript and then shell script. It is a bit slow though to execute and i noticed that apps compiled in script editor instead are faster to execute. how do i make an app in script that executes this javascript and shell script ?

#!/usr/bin/env osascript -l JavaScript
function run(input) {
    const app = Application.currentApplication();
    app.includeStandardAdditions = true;

    const obsidianJsonFilePath = app.pathTo("home folder") + "/Library/Application Support/obsidian/obsidian.json";
    const vaults = JSON.parse(app.read(obsidianJsonFilePath)).vaults;

    let openInObsi = false;
    const pathArray = input.toString().split(",");
    const toOpen = [];
    pathArray.forEach(filePath => {
        const isFileInObsidianVault = Object.values(vaults).some(v => filePath.startsWith(v.path));
        if (isFileInObsidianVault && !filePath.includes("/.")) { // second condition prevents the opening of files in .obsidian or .trash
            toOpen.push("obsidian://open?path=" + encodeURIComponent(filePath));
            openInObsi = true;
        }
        else toOpen.push(filePath);
    });
    return [openInObsi.toString(), ...toOpen];

}

Shell Script

if $1 ; then
    open "$2"
else
    open -a "Obsidian" "${@:2}"
fi

Didn't tried anything, because I am not familiar with this code.


问:
Wordpress website lagging while scrolling
I have website built with Wordpress & gutenberg blocks. But I found that some people see lagging when scrolling, it looks like website is loading components: texts, images and it looks ugly. Please see video and give a diagnosis, maybe this is slow internet (I doubt).</p>


问:
IHttpClientFactory in .NET Framework without Dependency Injection
In a .NET Framework project without dependency injection, is it better to get an HttpClient instance through its constructor (new HttpClient) or through IHttpClientFactory? Which of the following two cases is better?

HttpClient constructor

```<code>    Public Shared Function GetHttpClient() As HttpClient
       Return new HttpClient
    End Function
</code>```

IHttpClientFactory

```<code>    Private Shared mHttpClientFactory As IHttpClientFactory
    Shared Sub New()
        Dim serviceProvider = New ServiceCollection().AddHttpClient().BuildServiceProvider()
        mHttpClientFactory = serviceProvider.GetService(Of IHttpClientFactory)
    End Sub
    Public Shared Function GetHttpClient() As HttpClient
        Return mHttpClientFactory.CreateClient
    End Function
</code>```

As I have read, it is recommended to reuse the HttpClient instance created in case 1.
Shall I reuse the HttpClient instance created in case 2, or may I repeatedly call GetHttpClient, without reusing the instance returned?

Body:
In a .NET Framework project without dependency injection, is it better to get an HttpClient instance through its constructor (new HttpClient) or through IHttpClientFactory? Which of the following two cases is better?

HttpClient constructor

    Public Shared Function GetHttpClient() As HttpClient
       Return new HttpClient
    End Function

IHttpClientFactory

    Private Shared mHttpClientFactory As IHttpClientFactory
    Shared Sub New()
        Dim serviceProvider = New ServiceCollection().AddHttpClient().BuildServiceProvider()
        mHttpClientFactory = serviceProvider.GetService(Of IHttpClientFactory)
    End Sub
    Public Shared Function GetHttpClient() As HttpClient
        Return mHttpClientFactory.CreateClient
    End Function

As I have read, it is recommended to reuse the HttpClient instance created in case 1.
Shall I reuse the HttpClient instance created in case 2, or may I repeatedly call GetHttpClient, without reusing the instance returned?


问:
Farming game in C# cant fix level system
I am making a Farming game in Unity and I tried to implement an EXP System. I can not implement a function where you can plant a crop from an X player level.

This Code manages the whole farm

```<code> using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FarmManager : MonoBehaviour
{
    [Header("Money Settings")]
    public PlantItem selectPlant;
    public bool isPlanting = false;
    public int money = 100;
    public Text moneyTxt;

    [Header("Button Color Settings")]
    public Color buyColor = Color.green;
    public Color cancelColor = Color.red;
    public Color lockedColor = Color.grey;

    [Header("Button Audio Settings")]
    public AudioSource clickSound;

    [Header("Cursor Settings")]
    public Texture2D cursorArrow;
    public Texture2D cursorPickaxe;

    [Header("XP Settings")]
    public int maxExp;
    public float updatedExp;
    public float plusXp;
    public Image ExpBar;
    public float expIncreasedPerSecond;
    public int playerLevel;
    public Text levelText;
    public Text xpLevel;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.SetCursor(cursorArrow, Vector2.zero, CursorMode.ForceSoftware);
        moneyTxt.text = "$"+money;
        playerLevel =1;
        expIncreasedPerSecond =5f;
        maxExp = 25;
        updatedExp = 0;
        plusXp = 0;

    }

    void Update () {
        //updatedExp += expIncreasedPerSecond * Time.deltaTime;

        ExpBar.fillAmount = updatedExp / maxExp;

        levelText.text = playerLevel + "";
        xpLevel.text = updatedExp + "/" + maxExp;

        if (updatedExp >= maxExp)
        {
            plusXp = updatedExp-maxExp;
            playerLevel++;
            updatedExp=0+plusXp;
            maxExp+=maxExp;
        }
    }

    public void SelectPlant(PlantItem newPlant)
    {
        if(selectPlant == newPlant)
        {
            Debug.Log("Deselected" + selectPlant.plant.plantName);
            selectPlant.btnImage.color = buyColor;
            selectPlant.btnTxt.text = "Buy";
            selectPlant = null;
            isPlanting = false;
            clickSound.Play();

        }
        else
        {
            if(selectPlant!=null)
            {
                selectPlant.btnImage.color = buyColor;
                selectPlant.btnTxt.text = "Buy";
            }

            selectPlant = newPlant;
            selectPlant.btnImage.color = cancelColor;
            selectPlant.btnTxt.text = "Cancel";
            Debug.Log("Selected" + selectPlant.plant.plantName);
            isPlanting = true;
            clickSound.Play();

        }
    }

    public void Transaction(int value)
    {
        money+=value;
        moneyTxt.text = "$"+money;
    }

    public void GiveXP (float value)
    {
        updatedExp += value;
    }

}

</code>```

And this is the code where I import the information from

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "New Plant", menuName ="Plant")]

public class PlantObject : ScriptableObject
{
    [Header("Plant settings")]
    public string plantName;
    public Sprite[] plantStages;
    public float timeBtwStages;
    [Header("Money Settings")]
    public int buyPrice;
    public int sellPrice;
    [Header("XP Settings")]
    public int xpAmount;
    public int levelNeeded;
    [Header("Plant Icon")]
    public Sprite icon;
}
</code>```

I tried doing it this way, but it would not fix my issue and would not disable the crop until the needed level was reached and it gave me a ton of errors.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FarmManager : MonoBehaviour
{
    [Header("Money Settings")]
    public PlantItem selectPlant;
    public bool isPlanting = false;
    public int money = 100;
    public Text moneyTxt;

    [Header("Button Color Settings")]
    public Color buyColor = Color.green;
    public Color cancelColor = Color.red;
    public Color lockedColor = Color.grey;

    [Header("Button Audio Settings")]
    public AudioSource clickSound;

    [Header("Cursor Settings")]
    public Texture2D cursorArrow;
    public Texture2D cursorPickaxe;

    [Header("XP Settings")]
    public int maxExp;
    public float updatedExp;
    public float plusXp;
    public Image ExpBar;
    public float expIncreasedPerSecond;
    public int playerLevel;
    public Text levelText;
    public Text xpLevel;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.SetCursor(cursorArrow, Vector2.zero, CursorMode.ForceSoftware);
        moneyTxt.text = "$"+money;
        playerLevel =1;
        expIncreasedPerSecond =5f;
        maxExp = 25;
        updatedExp = 0;
        plusXp = 0;

    }

    void Update () {
        //updatedExp += expIncreasedPerSecond * Time.deltaTime;

        ExpBar.fillAmount = updatedExp / maxExp;

        levelText.text = playerLevel + "";
        xpLevel.text = updatedExp + "/" + maxExp;

        if (updatedExp >= maxExp)
        {
            plusXp = updatedExp-maxExp;
            playerLevel++;
            updatedExp=0+plusXp;
            maxExp+=maxExp;
        }
    }

    public void SelectPlant(PlantItem newPlant)
    {
        if(selectPlant == newPlant)
        {
            Debug.Log("Deselected" + selectPlant.plant.plantName);
            selectPlant.btnImage.color = buyColor;
            selectPlant.btnTxt.text = "Buy";
            selectPlant = null;
            isPlanting = false;
            clickSound.Play();

        }
        else
        {
            if(selectPlant!=null)
            {
                selectPlant.btnImage.color = buyColor;
                selectPlant.btnTxt.text = "Buy";
            }

            selectPlant = newPlant;
            selectPlant.btnImage.color = cancelColor;
            selectPlant.btnTxt.text = "Cancel";
            Debug.Log("Selected" + selectPlant.plant.plantName);
            isPlanting = true;
            clickSound.Play();

        }
        if (selectPlant.plant.levelNeeded > playerLevel)
        {
            selectPlant.btnImage.color = lockedColor;

        }

    }

    public void Transaction(int value)
    {
        money+=value;
        moneyTxt.text = "$"+money;
    }

    public void GiveXP (float value)
    {
        updatedExp += value;
    }

}
</code>```

I have been stuck on this for weeks now any ideas?

Body:
I am making a Farming game in Unity and I tried to implement an EXP System. I can not implement a function where you can plant a crop from an X player level.

This Code manages the whole farm

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FarmManager : MonoBehaviour
{
    [Header("Money Settings")]
    public PlantItem selectPlant;
    public bool isPlanting = false;
    public int money = 100;
    public Text moneyTxt;

    [Header("Button Color Settings")]
    public Color buyColor = Color.green;
    public Color cancelColor = Color.red;
    public Color lockedColor = Color.grey;

    [Header("Button Audio Settings")]
    public AudioSource clickSound;

    [Header("Cursor Settings")]
    public Texture2D cursorArrow;
    public Texture2D cursorPickaxe;

    [Header("XP Settings")]
    public int maxExp;
    public float updatedExp;
    public float plusXp;
    public Image ExpBar;
    public float expIncreasedPerSecond;
    public int playerLevel;
    public Text levelText;
    public Text xpLevel;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.SetCursor(cursorArrow, Vector2.zero, CursorMode.ForceSoftware);
        moneyTxt.text = "$"+money;
        playerLevel =1;
        expIncreasedPerSecond =5f;
        maxExp = 25;
        updatedExp = 0;
        plusXp = 0;

    }

    void Update () {
        //updatedExp += expIncreasedPerSecond * Time.deltaTime;

        ExpBar.fillAmount = updatedExp / maxExp;

        levelText.text = playerLevel + "";
        xpLevel.text = updatedExp + "/" + maxExp;

        if (updatedExp >= maxExp)
        {
            plusXp = updatedExp-maxExp;
            playerLevel++;
            updatedExp=0+plusXp;
            maxExp+=maxExp;
        }
    }

    public void SelectPlant(PlantItem newPlant)
    {
        if(selectPlant == newPlant)
        {
            Debug.Log("Deselected" + selectPlant.plant.plantName);
            selectPlant.btnImage.color = buyColor;
            selectPlant.btnTxt.text = "Buy";
            selectPlant = null;
            isPlanting = false;
            clickSound.Play();

        }
        else
        {
            if(selectPlant!=null)
            {
                selectPlant.btnImage.color = buyColor;
                selectPlant.btnTxt.text = "Buy";
            }

            selectPlant = newPlant;
            selectPlant.btnImage.color = cancelColor;
            selectPlant.btnTxt.text = "Cancel";
            Debug.Log("Selected" + selectPlant.plant.plantName);
            isPlanting = true;
            clickSound.Play();

        }
    }

    public void Transaction(int value)
    {
        money+=value;
        moneyTxt.text = "$"+money;
    }

    public void GiveXP (float value)
    {
        updatedExp += value;
    }

}

And this is the code where I import the information from

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "New Plant", menuName ="Plant")]

public class PlantObject : ScriptableObject
{
    [Header("Plant settings")]
    public string plantName;
    public Sprite[] plantStages;
    public float timeBtwStages;
    [Header("Money Settings")]
    public int buyPrice;
    public int sellPrice;
    [Header("XP Settings")]
    public int xpAmount;
    public int levelNeeded;
    [Header("Plant Icon")]
    public Sprite icon;
}

I tried doing it this way, but it would not fix my issue and would not disable the crop until the needed level was reached and it gave me a ton of errors.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FarmManager : MonoBehaviour
{
    [Header("Money Settings")]
    public PlantItem selectPlant;
    public bool isPlanting = false;
    public int money = 100;
    public Text moneyTxt;

    [Header("Button Color Settings")]
    public Color buyColor = Color.green;
    public Color cancelColor = Color.red;
    public Color lockedColor = Color.grey;

    [Header("Button Audio Settings")]
    public AudioSource clickSound;

    [Header("Cursor Settings")]
    public Texture2D cursorArrow;
    public Texture2D cursorPickaxe;

    [Header("XP Settings")]
    public int maxExp;
    public float updatedExp;
    public float plusXp;
    public Image ExpBar;
    public float expIncreasedPerSecond;
    public int playerLevel;
    public Text levelText;
    public Text xpLevel;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.SetCursor(cursorArrow, Vector2.zero, CursorMode.ForceSoftware);
        moneyTxt.text = "$"+money;
        playerLevel =1;
        expIncreasedPerSecond =5f;
        maxExp = 25;
        updatedExp = 0;
        plusXp = 0;

    }

    void Update () {
        //updatedExp += expIncreasedPerSecond * Time.deltaTime;

        ExpBar.fillAmount = updatedExp / maxExp;

        levelText.text = playerLevel + "";
        xpLevel.text = updatedExp + "/" + maxExp;

        if (updatedExp >= maxExp)
        {
            plusXp = updatedExp-maxExp;
            playerLevel++;
            updatedExp=0+plusXp;
            maxExp+=maxExp;
        }
    }

    public void SelectPlant(PlantItem newPlant)
    {
        if(selectPlant == newPlant)
        {
            Debug.Log("Deselected" + selectPlant.plant.plantName);
            selectPlant.btnImage.color = buyColor;
            selectPlant.btnTxt.text = "Buy";
            selectPlant = null;
            isPlanting = false;
            clickSound.Play();

        }
        else
        {
            if(selectPlant!=null)
            {
                selectPlant.btnImage.color = buyColor;
                selectPlant.btnTxt.text = "Buy";
            }

            selectPlant = newPlant;
            selectPlant.btnImage.color = cancelColor;
            selectPlant.btnTxt.text = "Cancel";
            Debug.Log("Selected" + selectPlant.plant.plantName);
            isPlanting = true;
            clickSound.Play();

        }
        if (selectPlant.plant.levelNeeded > playerLevel)
        {
            selectPlant.btnImage.color = lockedColor;

        }

    }

    public void Transaction(int value)
    {
        money+=value;
        moneyTxt.text = "$"+money;
    }

    public void GiveXP (float value)
    {
        updatedExp += value;
    }

}

I have been stuck on this for weeks now any ideas?


问:
How can I solve an error at initialisation in JS?
I am trying cloud messaging and have just put this in my HTML:

```<code><script src="https://www.gstatic.com/firebasejs/9.14.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.14.0/firebase-auth-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.14.0/firebase-firestore-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.14.0/firebase-storage-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.14.0/firebase-messaging-compat.js"></script>
<script src="/firebase-config.js" type="module"></script>  <!--Firebase configuration-->
</code>```

I am using compat, because I can't figure out how to use the v9 sdk with namespace. I have another script firebase-config.js:

```<code>const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

firebase.initializeApp(firebaseConfig);

const auth = firebase.auth();
const db = firebase.firestore();
const pushMessaging = firebase.messaging();
</code>```

I have all the fields in firebaseConfig filled. And then run it too check for error at initialisation. And unfortunately there is, just at initialisation. Burghh. But here is it:

```<code>register.ts:49 Uncaught TypeError: Cannot read properties of undefined (reading 'addEventListener')
    at c.it [as instanceFactory] (register.ts:49:27)
    at E.getOrInitializeService (provider.ts:318:33)
    at E.getImmediate (provider.ts:115:21)
    at c.qt [as instanceFactory] (registerMessagingCompat.ts:46:42)
    at E.getOrInitializeService (provider.ts:318:33)
    at E.getImmediate (provider.ts:115:21)
    at Se._getService (firebaseApp.ts:138:21)
    at r.type.a.<computed> [as messaging] (firebaseNamespaceCore.ts:185:29)
    at Object.e [as messaging] (firebaseNamespaceCore.ts:166:32)
    at firebase-config.js:15:32
</code>```

I have done what there is stated in the documentation. The problem is

```<code>const pushMessaging = firebase.messaging();
</code>```

but it is what the documentation says. Soo don't know what to do.
Auth and firestore works and I am using plain JS.

Body:
I am trying cloud messaging and have just put this in my HTML:

I am using compat, because I can't figure out how to use the v9 sdk with namespace. I have another script firebase-config.js:

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

firebase.initializeApp(firebaseConfig);

const auth = firebase.auth();
const db = firebase.firestore();
const pushMessaging = firebase.messaging();

I have all the fields in firebaseConfig filled. And then run it too check for error at initialisation. And unfortunately there is, just at initialisation. Burghh. But here is it:

register.ts:49 Uncaught TypeError: Cannot read properties of undefined (reading 'addEventListener')
    at c.it [as instanceFactory] (register.ts:49:27)
    at E.getOrInitializeService (provider.ts:318:33)
    at E.getImmediate (provider.ts:115:21)
    at c.qt [as instanceFactory] (registerMessagingCompat.ts:46:42)
    at E.getOrInitializeService (provider.ts:318:33)
    at E.getImmediate (provider.ts:115:21)
    at Se._getService (firebaseApp.ts:138:21)
    at r.type.a.<computed> [as messaging] (firebaseNamespaceCore.ts:185:29)
    at Object.e [as messaging] (firebaseNamespaceCore.ts:166:32)
    at firebase-config.js:15:32

I have done what there is stated in the documentation. The problem is

const pushMessaging = firebase.messaging();

but it is what the documentation says. Soo don't know what to do.
Auth and firestore works and I am using plain JS.


问:
Test IHostedService with IHostApplicationLifetime
I'm trying to write unit tests for my application using IHostedService that contains IHostApplicationLifetime in constructor

Constructor of class that I tried to test:

```<code>public Princess(IServiceScopeFactory serviceScopeFactory, IHostApplicationLifetime hostApplicationLifetime, IOptions<OutputFilePrefix> options)
{
    _serviceScopeFactory = serviceScopeFactory;
    _hostApplicationLifetime = hostApplicationLifetime;
    Console.WriteLine(options.Value);
}
</code>```

Test that crushed:

```<code>IServiceCollection services = new ServiceCollection();
services.AddScoped<IContenderGenerator>(sp => stabGenerator);
services.AddScoped<IHall, Hall>();
services.AddScoped<IFriend, SimpleFriend>();
services.AddScoped<IResultSaver, FileResultSaver>();
services.AddHostedService<Princess>();

var serviceProvider = services.BuildServiceProvider();

var princess = serviceProvider.GetRequiredService<IHostedService>() as Princess;
Console.WriteLine(princess);
Assert.Greater(princess.ChooseContender().Rating, 10);
</code>```

Stacktrace of error appeared:

```<code>Unable to resolve service for type 'Microsoft.Extensions.Hosting.IHostApplicationLifetime' while attempting to activate 'pickyPride2.Princess'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
</code>```

How can I solve this problem?

I tried to manually add dependency of IHostApplicationLifetime but that doesn't work

Body:
I'm trying to write unit tests for my application using IHostedService that contains IHostApplicationLifetime in constructor

Constructor of class that I tried to test:

public Princess(IServiceScopeFactory serviceScopeFactory, IHostApplicationLifetime hostApplicationLifetime, IOptions<OutputFilePrefix> options)
{
    _serviceScopeFactory = serviceScopeFactory;
    _hostApplicationLifetime = hostApplicationLifetime;
    Console.WriteLine(options.Value);
}

Test that crushed:

IServiceCollection services = new ServiceCollection();
services.AddScoped<IContenderGenerator>(sp => stabGenerator);
services.AddScoped<IHall, Hall>();
services.AddScoped<IFriend, SimpleFriend>();
services.AddScoped<IResultSaver, FileResultSaver>();
services.AddHostedService<Princess>();

var serviceProvider = services.BuildServiceProvider();

var princess = serviceProvider.GetRequiredService<IHostedService>() as Princess;
Console.WriteLine(princess);
Assert.Greater(princess.ChooseContender().Rating, 10);

Stacktrace of error appeared:

Unable to resolve service for type 'Microsoft.Extensions.Hosting.IHostApplicationLifetime' while attempting to activate 'pickyPride2.Princess'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)

How can I solve this problem?

I tried to manually add dependency of IHostApplicationLifetime but that doesn't work


问:
Creating a Spring Boot project with JSF:questions about Servlets
I'm trying to migrate a whole Spring with JSF app to Spring boot (with JSF).
It hasn't work out great because of context and servlet initialization between Spring-boot and JSF.
I've read everywhere that this isn't a good idea, but I don't have much choice.
I managed to make something work but there is stille a few things I don't understand.

Right now I'm just trying to set up a simple project with Spring boot and JSF (a POC with a few class and pages) to see if that's even possible.

Project

I've been following this tutorial. It also uses "rewrite" lib for routing.

Here are the important parts of the project:

The web.xml:

```<code><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</code>```

With the main class:

```<code>@EnableAutoConfiguration
@ComponentScan({"com.auth0.samples.bootfaces"})
public class Application extends SpringBootServletInitializer {

private static final Logger logger = LoggerFactory.getLogger(Application.class);

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public ServletRegistrationBean servletRegistrationBean() {
    logger.info("Registration of Faces Servlet");
    FacesServlet servlet = new FacesServlet();
    //return new ServletRegistrationBean(servlet, "*.xhtml");
    return new ServletRegistrationBean(servlet, "*.jsf");
}

@Bean
public FilterRegistrationBean rewriteFilter() {
    FilterRegistrationBean rwFilter = new FilterRegistrationBean(new RewriteFilter());
    rwFilter.setDispatcherTypes(EnumSet.of(DispatcherType.FORWARD, DispatcherType.REQUEST,
                                           DispatcherType.ASYNC, DispatcherType.ERROR));
    rwFilter.addUrlPatterns("/*");
    return rwFilter;
}
}
</code>```

And the faces-config.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
              version="2.2">
    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>
</faces-config>
</code>```

The pom.xml has a the spring-boot-starter-parent as parent project (version 2.5.7) the spring-boot-starter-web and a <build> part with spring-boot-maven-plugin (and some other dependencies).

Question

This tutorial has a web.xml with Spring-boot, but doesn't build as
a war. So by default, the WEB-INF folder (with both web.xml and
faces-config.xml) isn't even copied in the final jar. Aren't these
files useless then ?

And technically, if I created a war application, then I would
need a tomcat to start it (which makes spring-boot partially
useless, but I could start with that). From what I understand
spring-boot "can" read web.xml. But is it possible without it being
a war file ? If so, do I need to tell maven to add this file in the
jar ?

It also declares a new Servlet programmaticaly in Application.java
so that every URL ending with .jsf will be served by the JSF's
JavaFaces servlet. Isn't that what's web.xml should already be
doing ?

Body:
I'm trying to migrate a whole Spring with JSF app to Spring boot (with JSF).
It hasn't work out great because of context and servlet initialization between Spring-boot and JSF.
I've read everywhere that this isn't a good idea, but I don't have much choice.
I managed to make something work but there is stille a few things I don't understand.

Right now I'm just trying to set up a simple project with Spring boot and JSF (a POC with a few class and pages) to see if that's even possible.

Project

I've been following this tutorial. It also uses "rewrite" lib for routing.

Here are the important parts of the project:

The web.xml:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

With the main class:

@EnableAutoConfiguration
@ComponentScan({"com.auth0.samples.bootfaces"})
public class Application extends SpringBootServletInitializer {

private static final Logger logger = LoggerFactory.getLogger(Application.class);

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public ServletRegistrationBean servletRegistrationBean() {
    logger.info("Registration of Faces Servlet");
    FacesServlet servlet = new FacesServlet();
    //return new ServletRegistrationBean(servlet, "*.xhtml");
    return new ServletRegistrationBean(servlet, "*.jsf");
}

@Bean
public FilterRegistrationBean rewriteFilter() {
    FilterRegistrationBean rwFilter = new FilterRegistrationBean(new RewriteFilter());
    rwFilter.setDispatcherTypes(EnumSet.of(DispatcherType.FORWARD, DispatcherType.REQUEST,
                                           DispatcherType.ASYNC, DispatcherType.ERROR));
    rwFilter.addUrlPatterns("/*");
    return rwFilter;
}
}

And the faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
              version="2.2">
    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>
</faces-config>

The pom.xml has a the spring-boot-starter-parent as parent project (version 2.5.7) the spring-boot-starter-web and a <build> part with spring-boot-maven-plugin (and some other dependencies).

Question

This tutorial has a web.xml with Spring-boot, but doesn't build as
a war. So by default, the WEB-INF folder (with both web.xml and
faces-config.xml) isn't even copied in the final jar. Aren't these
files useless then ?

And technically, if I created a war application, then I would
need a tomcat to start it (which makes spring-boot partially
useless, but I could start with that). From what I understand
spring-boot "can" read web.xml. But is it possible without it being
a war file ? If so, do I need to tell maven to add this file in the
jar ?

It also declares a new Servlet programmaticaly in Application.java
so that every URL ending with .jsf will be served by the JSF's
JavaFaces servlet. Isn't that what's web.xml should already be
doing ?


问:
Custom Json ResponseBody in Swagger Http error
In a Jhipster SpringBoot project I use swagger 2.0 ,

I want to have a static Json in this Http Error : 400

Custom Json wanted:

{ "ErrorID": -1 , "CustomMessage": "ERROR" }

I tried this in my file.yml

```<code>/path101:
    post:
      operationId: ID_OP
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - in: body
          name: body
          required: true
          schema:
            $ref: '#/definitions/Object_OP'
      responses:
        '200':
          description: Successful operation
          schema:
            $ref: '#/definitions/reponse_Object_OP'
        '400':
          description: Bad Request
          examples:
            application/json:
              ErrorID: -1
              CustomMessage: ERROR

</code>```

In I still have the Springboot Normal error:

```<code>{
    "timestamp": "2022-12-22T13:26:40.789+00:00",
    "status": 400,
    "error": "Bad Request",
    "path": "/api/xxx/v1/path101"
}
</code>```

I tried also updating api.yml file but I still have the same error:

```<code>    # API-first development with OpenAPI
    # This file will be used at compile time to generate Spring-MVC endpoint stubs using openapi-generator
    openapi: '3.0.1'
    info:
      title: 'MyApp'
      version: 0.0.1
    servers:
      - url: http://localhost:8082/api
        description: Development server
      - url: https://localhost:8082/api
        description: Development server with TLS Profile
    paths: {}
    components:
      responses:
#    Problem:
#      description: error occurred - see status code and problem object for more information.
#      content:
#        'application/problem+json':
#          schema:
#            $ref: 'https://opensource.zalando.com/problem/schema.yaml#/Problem'
     '400':
        description: Bad Request
        examples:
          application/json:
             ErrorID: -1
             CustomMessage: ERROR

  securitySchemes:
    jwt:
      type: http
      description: JWT Authentication
      scheme: bearer
      bearerFormat: JWT security:
  - jwt: []
</code>```

Body:
In a Jhipster SpringBoot project I use swagger 2.0 ,

I want to have a static Json in this Http Error : 400

Custom Json wanted:

{ "ErrorID": -1 , "CustomMessage": "ERROR" }

I tried this in my file.yml

/path101:
    post:
      operationId: ID_OP
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - in: body
          name: body
          required: true
          schema:
            $ref: '#/definitions/Object_OP'
      responses:
        '200':
          description: Successful operation
          schema:
            $ref: '#/definitions/reponse_Object_OP'
        '400':
          description: Bad Request
          examples:
            application/json:
              ErrorID: -1
              CustomMessage: ERROR

In I still have the Springboot Normal error:

{
    "timestamp": "2022-12-22T13:26:40.789+00:00",
    "status": 400,
    "error": "Bad Request",
    "path": "/api/xxx/v1/path101"
}

I tried also updating api.yml file but I still have the same error:

    # API-first development with OpenAPI
    # This file will be used at compile time to generate Spring-MVC endpoint stubs using openapi-generator
    openapi: '3.0.1'
    info:
      title: 'MyApp'
      version: 0.0.1
    servers:
      - url: http://localhost:8082/api
        description: Development server
      - url: https://localhost:8082/api
        description: Development server with TLS Profile
    paths: {}
    components:
      responses:
#    Problem:
#      description: error occurred - see status code and problem object for more information.
#      content:
#        'application/problem+json':
#          schema:
#            $ref: 'https://opensource.zalando.com/problem/schema.yaml#/Problem'
     '400':
        description: Bad Request
        examples:
          application/json:
             ErrorID: -1
             CustomMessage: ERROR

  securitySchemes:
    jwt:
      type: http
      description: JWT Authentication
      scheme: bearer
      bearerFormat: JWT security:
  - jwt: []


问:
How i can retrieve correct values when i make signal decomposition with FastICA - Sklearn?
I want to extract three components signal through FastICA. For this, I have three records in a data shape (3, 12000) and i retrieve same shape.Below show how data look  this process before.
Data before

With the next script in python i make the separation.

```<code>ica = FastICA(n_components=3, whiten="arbitrary-variance")

sig=sig.reshape(12000,3)

S_ = ica.fit_transform(sig)

#Plot in figure

ax1.plot(x,S_[:,0])
ax2.plot(x,S_[:,1])
ax3.plot(x,S_[:,2])
</code>```

This process return one image with this signals:
After process
The problem is the data after processing, because it have max values of amplitude less than 1 in comparative with original data that have values more than 3E3.

Body:
I want to extract three components signal through FastICA. For this, I have three records in a data shape (3, 12000) and i retrieve same shape.Below show how data look  this process before.
Data before

With the next script in python i make the separation.

ica = FastICA(n_components=3, whiten="arbitrary-variance")

sig=sig.reshape(12000,3)

S_ = ica.fit_transform(sig)

#Plot in figure

ax1.plot(x,S_[:,0])
ax2.plot(x,S_[:,1])
ax3.plot(x,S_[:,2])

This process return one image with this signals:
After process
The problem is the data after processing, because it have max values of amplitude less than 1 in comparative with original data that have values more than 3E3.


问:
How to create dropddb on windows
The error:

make: *** No rule to make target 'dropdb'.  Stop.
```
<p>My makefile:</p>
```createdb:
    docker exec -it postgres12 createdb --username= --owner= simple-bank

dropdb:
    docker exec -it postgres12 dropdb simple-bank

.PHONY:createdb
```

I expected it to create a drop

Title: How to create dropddb on windows

Body:
The error:

make: *** No rule to make target 'dropdb'.  Stop.

My makefile:

createdb:
    docker exec -it postgres12 createdb --username= --owner= simple-bank

dropdb:
    docker exec -it postgres12 dropdb simple-bank

.PHONY:createdb

I expected it to create a drop


问:
Constrain a 3D mesh to not have overlapping triangles when projected in a specific plane
I have a 3D polygon composed of points which are almost coplanar, vertically (which means the offset distances from those points which are not coplanar are orders of magnitude smaller than the distances between the points. They are due to numerical precision issue.).

I know the definition of the Euclidean plane of which they should be part of. But they are actually not part of it because of some numerical inaccuracies.

Is there a way, e.g. with Trimesh, to enforce a triangulation on these points so that the resulting triangles are never overlapping each other when seen from an orthogonal view which is perpendicular to the plane (said differently; when projected on the plane)?

#Python 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0]
import numpy as np # version 1.24.0
import trimesh # version 3.17.1
from shapely import wkt
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

A = wkt.loads('''POLYGON Z ((
    3094228.563000001 2220858.2252000012 58.66020000015850,
    3094228.563000001 2220858.2252000012 62.31250000034925,
    3094231.731899999 2220851.7289999984 62.31250000034925,
    3094231.731899999 2220851.7289999984 20.79300000029616,
    3094228.083999999 2220859.2069999985 20.79300000029616,
    3094228.083999999 2220859.2069999985 58.66020000015850,
    3094228.563000001 2220858.2252000012 58.66020000015850))
''')
a = np.array(A.exterior.coords)
x, y, z = a[:,0], a[:,1], a[:,2]

cloud = trimesh.PointCloud(a)
mesh = cloud.convex_hull

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='red', s=40)
ax.plot_trisurf(
    mesh.vertices[:,0],
    mesh.vertices[:,1],
    Z=mesh.vertices[:,2],
    triangles=mesh.faces,
    shade=True,
)
ax.view_init(azim=47, elev=3, roll=0)
plt.show()
```

But the resulting mesh seems to have overlapping triangles (it glitters when I rotate the plot):

(note that one of the points is not shown in this figure because it is somewhere "inside" the triangles soup in the top right part)

(I also only want to keep those triangles which are inside the initial polygon, which is concave, but this worth an other question imho)

Body:
I have a 3D polygon composed of points which are almost coplanar, vertically (which means the offset distances from those points which are not coplanar are orders of magnitude smaller than the distances between the points. They are due to numerical precision issue.).

I know the definition of the Euclidean plane of which they should be part of. But they are actually not part of it because of some numerical inaccuracies.

Is there a way, e.g. with Trimesh, to enforce a triangulation on these points so that the resulting triangles are never overlapping each other when seen from an orthogonal view which is perpendicular to the plane (said differently; when projected on the plane)?

#Python 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0]
import numpy as np # version 1.24.0
import trimesh # version 3.17.1
from shapely import wkt
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

A = wkt.loads('''POLYGON Z ((
    3094228.563000001 2220858.2252000012 58.66020000015850,
    3094228.563000001 2220858.2252000012 62.31250000034925,
    3094231.731899999 2220851.7289999984 62.31250000034925,
    3094231.731899999 2220851.7289999984 20.79300000029616,
    3094228.083999999 2220859.2069999985 20.79300000029616,
    3094228.083999999 2220859.2069999985 58.66020000015850,
    3094228.563000001 2220858.2252000012 58.66020000015850))
''')
a = np.array(A.exterior.coords)
x, y, z = a[:,0], a[:,1], a[:,2]

cloud = trimesh.PointCloud(a)
mesh = cloud.convex_hull

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='red', s=40)
ax.plot_trisurf(
    mesh.vertices[:,0],
    mesh.vertices[:,1],
    Z=mesh.vertices[:,2],
    triangles=mesh.faces,
    shade=True,
)
ax.view_init(azim=47, elev=3, roll=0)
plt.show()

But the resulting mesh seems to have overlapping triangles (it glitters when I rotate the plot):

(note that one of the points is not shown in this figure because it is somewhere "inside" the triangles soup in the top right part)

(I also only want to keep those triangles which are inside the initial polygon, which is concave, but this worth an other question imho)


问:
Why spark stream to stream join return empty result?
When I try to join 2 streams using pyspark streaming, I get an empty result.

I have the following parquet dataset stored in an S3 Bucket.

```<code>Table A:
ID_a,Ref_a,ts_a
1,X,2021-12-06 04:59:54.075 UTC
...
2,Y,2021-12-06 04:59:54.010 UTC

Table B:
ID_b,Ref_b,ts_b
1,X,2022-05-17 14:26:16.173 UTC
...
3,Z,2022-05-17 14:26:16.176 UTC
</code>```

I sorted the elements of both the tables by ts column, as you can notice, the time difference between each record of the same table, is just about few milliseconds, few times some record have also the same exact timestamp.

There is ~6 months difference in ts between the records of Table A and Table B.

I am trying to join those data as streams:

```<code>df_a = spark.readStream.schema(...).parquet("s3:...").withWatermark('ts', '1 minute')
df_b = spark.readStream.schema(...).parquet("s3:...").withWatermark('ts', '1 minute')

cond = expr("""
ID_a = ID_b AND
Ref_a = Ref_b AND
ts_a >= ts_b AND
ts_a <= ts_b
""")

a_joined_b = df_a.join(df_b, cond, 'outer')

def print_fn(batch_df, batch_id):
    batch_df.show(n=200, truncate=False)

stream_a_joined_b = a_joined_b.writeStream.trigger(processingTime='60 seconds').foreachBatch(print_fn).start()
</code>```

From the logs I can see that I am getting empty dataframe, for some reason spark is discarding the results.

Body:
When I try to join 2 streams using pyspark streaming, I get an empty result.

I have the following parquet dataset stored in an S3 Bucket.

Table A:
ID_a,Ref_a,ts_a
1,X,2021-12-06 04:59:54.075 UTC
...
2,Y,2021-12-06 04:59:54.010 UTC

Table B:
ID_b,Ref_b,ts_b
1,X,2022-05-17 14:26:16.173 UTC
...
3,Z,2022-05-17 14:26:16.176 UTC

I sorted the elements of both the tables by ts column, as you can notice, the time difference between each record of the same table, is just about few milliseconds, few times some record have also the same exact timestamp.

There is ~6 months difference in ts between the records of Table A and Table B.

I am trying to join those data as streams:

df_a = spark.readStream.schema(...).parquet("s3:...").withWatermark('ts', '1 minute')
df_b = spark.readStream.schema(...).parquet("s3:...").withWatermark('ts', '1 minute')

cond = expr("""
ID_a = ID_b AND
Ref_a = Ref_b AND
ts_a >= ts_b AND
ts_a <= ts_b
""")

a_joined_b = df_a.join(df_b, cond, 'outer')

def print_fn(batch_df, batch_id):
    batch_df.show(n=200, truncate=False)

stream_a_joined_b = a_joined_b.writeStream.trigger(processingTime='60 seconds').foreachBatch(print_fn).start()

From the logs I can see that I am getting empty dataframe, for some reason spark is discarding the results.


问:
calculate income on one table with price, buyer_id, seller_id
a table include the traded invoices with price, product_id, buyer_id, seller_id.

id
price
product_id
buyer_id
seller_id
trade_date

1
120
1
1
null
some_date

2
150
1
2
1
some_date

3
150
1
3
2
some_date

4
150
2
2
null
some_date

5
150
2
1
2
some_date

To calculate the profit for user_id(1) , need to sum the price with the seller_id is 1 (which is the total revenue) and then minus the price with the buyer_id is 1 (which is the total cost)

I tried this query buy i found is wrong

```<code>SELECT IFNULL(SUM(a.trade_price),0) cost,
IFNULL(SUM(b.trade_price),0) income
FROM invoice a
INNER JOIN invoice b ON a.product_id = b.product_id
AND b.seller = a.buyer
WHERE a.buyer = ?
</code>```

I want to join table because only the cost will be included if the product was sold. but I found join table will include the repeated row.

after run this query, i expected that the profit will be income minus cost.

Body:
a table include the traded invoices with price, product_id, buyer_id, seller_id.

id
price
product_id
buyer_id
seller_id
trade_date

1
120
1
1
null
some_date

2
150
1
2
1
some_date

3
150
1
3
2
some_date

4
150
2
2
null
some_date

5
150
2
1
2
some_date

To calculate the profit for user_id(1) , need to sum the price with the seller_id is 1 (which is the total revenue) and then minus the price with the buyer_id is 1 (which is the total cost)

I tried this query buy i found is wrong

SELECT IFNULL(SUM(a.trade_price),0) cost,
IFNULL(SUM(b.trade_price),0) income
FROM invoice a
INNER JOIN invoice b ON a.product_id = b.product_id
AND b.seller = a.buyer
WHERE a.buyer = ?

I want to join table because only the cost will be included if the product was sold. but I found join table will include the repeated row.

after run this query, i expected that the profit will be income minus cost.


问:
Puppeteer. Headless test for stripe
I wrote a test to subscribe to stripe on my site, it works fine in basic chrome, but when I add the --headless flag, I get a CORS error.

I tried this:

```<code>await stripe.confirmSetup({
        confirmParams: {return_url: `http://localhost:3000/plans`},
        elements,
})
</code>```

When chromium is headless, redirect and confirmSetup doesn't work. What is the difference between a headless request and a normal browser request?
Thanks.

I tried set pptr lunch flags:

```<code>'--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure',
'--no-sandbox',
'--disable-setuid-sandbox',
'disable-web-security',
'--disable-features=IsolateOrigins,site-per-process'
</code>```

Title: Puppeteer. Headless test for stripe

Body:
I wrote a test to subscribe to stripe on my site, it works fine in basic chrome, but when I add the --headless flag, I get a CORS error.

I tried this:

await stripe.confirmSetup({
        confirmParams: {return_url: `http://localhost:3000/plans`},
        elements,
})

When chromium is headless, redirect and confirmSetup doesn't work. What is the difference between a headless request and a normal browser request?
Thanks.

I tried set pptr lunch flags:

'--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure',
'--no-sandbox',
'--disable-setuid-sandbox',
'disable-web-security',
'--disable-features=IsolateOrigins,site-per-process'