问:
Laravel Nova - Let user chose which fields/columns are displayed on index
I'm using Laravel 9 and Nova 4 to create an admin panel and recently got the request you can see in the title.

Is there any way to let the user dynamically select which fields of the resource are shown on the index instead of hard-coding the visibility?

I want to show/hide full columns of the resource via the click of a button.

Maybe i searched for the wrong stuff I haven't found any information on this. Neither here on StackOverflow nor anywhere else.


来源: stackexchange

问:
KEDA autoscaler metric support
My current k8 hpa setup is a vanilla setup that uses a combination of 2 metrics.

a Pods Metric (each pod emits a metric related to a business logic value) and the target is an average of X (injected into prometheus and read from prometheus)

an External Metric that looks at SQS Queue Size (injected into prometheus and read from prometheus) and the target is an average of Y

the final pod count is the max suggested pod count of the 2 metrics. The question is, I want to use KEDA to have the scale to 0 feature, but will KEDA be able to support these same 2 metrics in the same way?

nothing yet...haven't tried anything, researching

ContentLicense: CC BY-SA 4.0

Title: KEDA autoscaler metric support


问:
Android app crashes when converting JSON using Gson and getting response with Volley
My app crashes whenever I try to get a location using the google places api. I'm using Volley to get a response from the URL and then using Gson to convert the JSON data.

I am getting a response from the URL however, I can't seem to figure out how to convert the JSON into usable text. Here I am trying to get the latitude of the place but the app crashes.

```<code>        btRestaurant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Instantiate the RequestQueue.
                RequestQueue queue = Volley.newRequestQueue(getActivity());
                String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=52.573012,-1.173310&radius=500&type=restaurant&key=KEY";

                // Request a string response from the provided URL.
                StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Toast.makeText(getActivity(), response, Toast.LENGTH_LONG).show();

                                Gson gson = new Gson();
                                Result result = gson.fromJson(response, Result.class);
                                Log.i("AJB", String.valueOf(result.getGeometry().getLocation().getLat()));

                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "Error occured", Toast.LENGTH_LONG).show();
                    }
                });

                // Add the request to the RequestQueue.
                queue.add(stringRequest);
            }
        });
</code>```

Here are the POJOS

```<code>public class Result {

    @SerializedName("business_status")
    @Expose
    private String businessStatus;
    @SerializedName("geometry")
    @Expose
    private Geometry geometry;
    @SerializedName("icon")
    @Expose
    private String icon;
    @SerializedName("icon_background_color")
    @Expose
    private String iconBackgroundColor;
    @SerializedName("icon_mask_base_uri")
    @Expose
    private String iconMaskBaseUri;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("opening_hours")
    @Expose
    private OpeningHours openingHours;
    @SerializedName("photos")
    @Expose
    private List<Photo> photos = null;
    @SerializedName("place_id")
    @Expose
    private String placeId;
    @SerializedName("plus_code")
    @Expose
    private PlusCode plusCode;
    @SerializedName("price_level")
    @Expose
    private Integer priceLevel;
    @SerializedName("rating")
    @Expose
    private Integer rating;
    @SerializedName("reference")
    @Expose
    private String reference;
    @SerializedName("scope")
    @Expose
    private String scope;
    @SerializedName("types")
    @Expose
    private List<String> types = null;
    @SerializedName("user_ratings_total")
    @Expose
    private Integer userRatingsTotal;
    @SerializedName("vicinity")
    @Expose
    private String vicinity;

    public String getBusinessStatus() {
        return businessStatus;
    }

    public void setBusinessStatus(String businessStatus) {
        this.businessStatus = businessStatus;
    }

    public Geometry getGeometry() {
        return geometry;
    }

    public void setGeometry(Geometry geometry) {
        this.geometry = geometry;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getIconBackgroundColor() {
        return iconBackgroundColor;
    }

    public void setIconBackgroundColor(String iconBackgroundColor) {
        this.iconBackgroundColor = iconBackgroundColor;
    }

    public String getIconMaskBaseUri() {
        return iconMaskBaseUri;
    }

    public void setIconMaskBaseUri(String iconMaskBaseUri) {
        this.iconMaskBaseUri = iconMaskBaseUri;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public OpeningHours getOpeningHours() {
        return openingHours;
    }

    public void setOpeningHours(OpeningHours openingHours) {
        this.openingHours = openingHours;
    }

    public List<Photo> getPhotos() {
        return photos;
    }

    public void setPhotos(List<Photo> photos) {
        this.photos = photos;
    }

    public String getPlaceId() {
        return placeId;
    }

    public void setPlaceId(String placeId) {
        this.placeId = placeId;
    }

    public PlusCode getPlusCode() {
        return plusCode;
    }

    public void setPlusCode(PlusCode plusCode) {
        this.plusCode = plusCode;
    }

    public Integer getPriceLevel() {
        return priceLevel;
    }

    public void setPriceLevel(Integer priceLevel) {
        this.priceLevel = priceLevel;
    }

    public Integer getRating() {
        return rating;
    }

    public void setRating(Integer rating) {
        this.rating = rating;
    }

    public String getReference() {
        return reference;
    }

    public void setReference(String reference) {
        this.reference = reference;
    }

    public String getScope() {
        return scope;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }

    public List<String> getTypes() {
        return types;
    }

    public void setTypes(List<String> types) {
        this.types = types;
    }

    public Integer getUserRatingsTotal() {
        return userRatingsTotal;
    }

    public void setUserRatingsTotal(Integer userRatingsTotal) {
        this.userRatingsTotal = userRatingsTotal;
    }

    public String getVicinity() {
        return vicinity;
    }

    public void setVicinity(String vicinity) {
        this.vicinity = vicinity;
    }

}
</code>```
```<code>public class Geometry {

    @SerializedName("location")
    @Expose
    private Location location;
    @SerializedName("viewport")
    @Expose
    private Viewport viewport;

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public Viewport getViewport() {
        return viewport;
    }

    public void setViewport(Viewport viewport) {
        this.viewport = viewport;
    }

}
</code>```
```<code>public class Location {

    @SerializedName("lat")
    @Expose
    private Double lat;
    @SerializedName("lng")
    @Expose
    private Double lng;

    public Double getLat() {
        return lat;
    }

    public void setLat(Double lat) {
        this.lat = lat;
    }

    public Double getLng() {
        return lng;
    }

    public void setLng(Double lng) {
        this.lng = lng;
    }

}
</code>```

Crash log

```<code>2023-01-04 17:56:35.951 14801-14801/aston.cs3mdd.pubgolf E/AndroidRuntime: FATAL EXCEPTION: main
    Process: aston.cs3mdd.pubgolf, PID: 14801
    java.lang.NullPointerException: Attempt to invoke virtual method 'aston.cs3mdd.pubgolf.ui.dashboard.Location aston.cs3mdd.pubgolf.ui.dashboard.Geometry.getLocation()' on a null object reference
        at aston.cs3mdd.pubgolf.ui.dashboard.DashboardFragment$3$1.onResponse(DashboardFragment.java:184)
        at aston.cs3mdd.pubgolf.ui.dashboard.DashboardFragment$3$1.onResponse(DashboardFragment.java:173)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
        at android.os.Handler.handleCallback(Handler.java:942)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7872)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
</code>```

SOLUTION

The right way to get data is to use result.getResults().get(index).getLocation().getLat()

Body:
My app crashes whenever I try to get a location using the google places api. I'm using Volley to get a response from the URL and then using Gson to convert the JSON data.

I am getting a response from the URL however, I can't seem to figure out how to convert the JSON into usable text. Here I am trying to get the latitude of the place but the app crashes.

        btRestaurant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Instantiate the RequestQueue.
                RequestQueue queue = Volley.newRequestQueue(getActivity());
                String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=52.573012,-1.173310&radius=500&type=restaurant&key=KEY";

                // Request a string response from the provided URL.
                StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Toast.makeText(getActivity(), response, Toast.LENGTH_LONG).show();

                                Gson gson = new Gson();
                                Result result = gson.fromJson(response, Result.class);
                                Log.i("AJB", String.valueOf(result.getGeometry().getLocation().getLat()));

                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "Error occured", Toast.LENGTH_LONG).show();
                    }
                });

                // Add the request to the RequestQueue.
                queue.add(stringRequest);
            }
        });

Here are the POJOS

public class Result {

    @SerializedName("business_status")
    @Expose
    private String businessStatus;
    @SerializedName("geometry")
    @Expose
    private Geometry geometry;
    @SerializedName("icon")
    @Expose
    private String icon;
    @SerializedName("icon_background_color")
    @Expose
    private String iconBackgroundColor;
    @SerializedName("icon_mask_base_uri")
    @Expose
    private String iconMaskBaseUri;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("opening_hours")
    @Expose
    private OpeningHours openingHours;
    @SerializedName("photos")
    @Expose
    private List<Photo> photos = null;
    @SerializedName("place_id")
    @Expose
    private String placeId;
    @SerializedName("plus_code")
    @Expose
    private PlusCode plusCode;
    @SerializedName("price_level")
    @Expose
    private Integer priceLevel;
    @SerializedName("rating")
    @Expose
    private Integer rating;
    @SerializedName("reference")
    @Expose
    private String reference;
    @SerializedName("scope")
    @Expose
    private String scope;
    @SerializedName("types")
    @Expose
    private List<String> types = null;
    @SerializedName("user_ratings_total")
    @Expose
    private Integer userRatingsTotal;
    @SerializedName("vicinity")
    @Expose
    private String vicinity;

    public String getBusinessStatus() {
        return businessStatus;
    }

    public void setBusinessStatus(String businessStatus) {
        this.businessStatus = businessStatus;
    }

    public Geometry getGeometry() {
        return geometry;
    }

    public void setGeometry(Geometry geometry) {
        this.geometry = geometry;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getIconBackgroundColor() {
        return iconBackgroundColor;
    }

    public void setIconBackgroundColor(String iconBackgroundColor) {
        this.iconBackgroundColor = iconBackgroundColor;
    }

    public String getIconMaskBaseUri() {
        return iconMaskBaseUri;
    }

    public void setIconMaskBaseUri(String iconMaskBaseUri) {
        this.iconMaskBaseUri = iconMaskBaseUri;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public OpeningHours getOpeningHours() {
        return openingHours;
    }

    public void setOpeningHours(OpeningHours openingHours) {
        this.openingHours = openingHours;
    }

    public List<Photo> getPhotos() {
        return photos;
    }

    public void setPhotos(List<Photo> photos) {
        this.photos = photos;
    }

    public String getPlaceId() {
        return placeId;
    }

    public void setPlaceId(String placeId) {
        this.placeId = placeId;
    }

    public PlusCode getPlusCode() {
        return plusCode;
    }

    public void setPlusCode(PlusCode plusCode) {
        this.plusCode = plusCode;
    }

    public Integer getPriceLevel() {
        return priceLevel;
    }

    public void setPriceLevel(Integer priceLevel) {
        this.priceLevel = priceLevel;
    }

    public Integer getRating() {
        return rating;
    }

    public void setRating(Integer rating) {
        this.rating = rating;
    }

    public String getReference() {
        return reference;
    }

    public void setReference(String reference) {
        this.reference = reference;
    }

    public String getScope() {
        return scope;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }

    public List<String> getTypes() {
        return types;
    }

    public void setTypes(List<String> types) {
        this.types = types;
    }

    public Integer getUserRatingsTotal() {
        return userRatingsTotal;
    }

    public void setUserRatingsTotal(Integer userRatingsTotal) {
        this.userRatingsTotal = userRatingsTotal;
    }

    public String getVicinity() {
        return vicinity;
    }

    public void setVicinity(String vicinity) {
        this.vicinity = vicinity;
    }

}

public class Geometry {

    @SerializedName("location")
    @Expose
    private Location location;
    @SerializedName("viewport")
    @Expose
    private Viewport viewport;

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public Viewport getViewport() {
        return viewport;
    }

    public void setViewport(Viewport viewport) {
        this.viewport = viewport;
    }

}

public class Location {

    @SerializedName("lat")
    @Expose
    private Double lat;
    @SerializedName("lng")
    @Expose
    private Double lng;

    public Double getLat() {
        return lat;
    }

    public void setLat(Double lat) {
        this.lat = lat;
    }

    public Double getLng() {
        return lng;
    }

    public void setLng(Double lng) {
        this.lng = lng;
    }

}

Crash log

2023-01-04 17:56:35.951 14801-14801/aston.cs3mdd.pubgolf E/AndroidRuntime: FATAL EXCEPTION: main
    Process: aston.cs3mdd.pubgolf, PID: 14801
    java.lang.NullPointerException: Attempt to invoke virtual method 'aston.cs3mdd.pubgolf.ui.dashboard.Location aston.cs3mdd.pubgolf.ui.dashboard.Geometry.getLocation()' on a null object reference
        at aston.cs3mdd.pubgolf.ui.dashboard.DashboardFragment$3$1.onResponse(DashboardFragment.java:184)
        at aston.cs3mdd.pubgolf.ui.dashboard.DashboardFragment$3$1.onResponse(DashboardFragment.java:173)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
        at android.os.Handler.handleCallback(Handler.java:942)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7872)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

SOLUTION

The right way to get data is to use result.getResults().get(index).getLocation().getLat()


问:
Can knitr be set up to bookmark lower heading levels in PDF?
So, i have an issue whereby knitr only bookmarks up to four levels of RMarkdown headings

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

Is there any way to extend the depth of headings that are being bookmarked in the PDF?

Body:
So, i have an issue whereby knitr only bookmarks up to four levels of RMarkdown headings

#
##
###
####
#####

Is there any way to extend the depth of headings that are being bookmarked in the PDF?


问:
PrimeFaces p:barChart settings
I'm trying to use the PrimeFaces chart bar component. I configured some settings, but I am having problems with some settings. I want to completely remove the part I put in the yellow box. I also want to shorten the area indicated by the green arrow. How can I do it?

The settings on the xhtml and bean side are as follows.

xhtml:

    <f:facet name="header">
        Toplam Kazancınız
        #{toplamKazancBean.kko.kazancToplam} TRY
    </f:facet>

```
<p>bean:</p>
<pre class="lang-java prettyprint-override"><code>private void chartSettings() {
    // values:
    stackedBarModel = new HorizontalBarChartModel();
    ChartData data = new ChartData();

    HorizontalBarChartDataSet barDataSet = new HorizontalBarChartDataSet();

    for (int i = 0; i < kko.getKazanclarList().size(); i++) {
        int oran = (int) Math.floor(kko.getKazanclarList().get(i).getTutar() / kko.getKazancToplam() * 100);

        barDataSet.setLabel(kko.getKazanclarList().get(i).getMetinAlani() + " %" + oran);
        barDataSet.setBackgroundColor(rgbArray[i]);
        List<Number> dataVal = new ArrayList<Number>();
        dataVal.add(kko.getKazanclarList().get(i).getTutar());
        barDataSet.setData(dataVal);

        data.addChartDataSet(barDataSet);
    }

    stackedBarModel.setData(data);

    // Options
    CartesianScaleLabel label = new CartesianScaleLabel();
    label.setDisplay(false);

    AxesGridLines gridLines = new AxesGridLines();
    gridLines.setDisplay(false);//ızgaralar kapandı

    CartesianLinearAxes linearAxes = new CartesianLinearAxes();
    linearAxes.setStacked(true);
    linearAxes.setGridLines(gridLines);
    linearAxes.setScaleLabel(label);

    CartesianScales cScales = new CartesianScales();
    cScales.addXAxesData(linearAxes);
    cScales.addYAxesData(linearAxes);
    cScales.setDisplay(true);

    Tooltip tooltip = new Tooltip();
    tooltip.setEnabled(false);

    BarChartOptions options = new BarChartOptions();
    options.setScales(cScales);
    options.setTooltip(tooltip);
    options.setOffsetGridLines(false);

    stackedBarModel.setOptions(options);
}
</code>```

Title: PrimeFaces p:barChart settings

Body:
I'm trying to use the PrimeFaces chart bar component. I configured some settings, but I am having problems with some settings. I want to completely remove the part I put in the yellow box. I also want to shorten the area indicated by the green arrow. How can I do it?

The settings on the xhtml and bean side are as follows.

xhtml:

    <f:facet name="header">
        Toplam Kazancınız
        #{toplamKazancBean.kko.kazancToplam} TRY
    </f:facet>

bean:

private void chartSettings() {
    // values:
    stackedBarModel = new HorizontalBarChartModel();
    ChartData data = new ChartData();

    HorizontalBarChartDataSet barDataSet = new HorizontalBarChartDataSet();

    for (int i = 0; i < kko.getKazanclarList().size(); i++) {
        int oran = (int) Math.floor(kko.getKazanclarList().get(i).getTutar() / kko.getKazancToplam() * 100);

        barDataSet.setLabel(kko.getKazanclarList().get(i).getMetinAlani() + " %" + oran);
        barDataSet.setBackgroundColor(rgbArray[i]);
        List<Number> dataVal = new ArrayList<Number>();
        dataVal.add(kko.getKazanclarList().get(i).getTutar());
        barDataSet.setData(dataVal);

        data.addChartDataSet(barDataSet);
    }

    stackedBarModel.setData(data);

    // Options
    CartesianScaleLabel label = new CartesianScaleLabel();
    label.setDisplay(false);

    AxesGridLines gridLines = new AxesGridLines();
    gridLines.setDisplay(false);//ızgaralar kapandı

    CartesianLinearAxes linearAxes = new CartesianLinearAxes();
    linearAxes.setStacked(true);
    linearAxes.setGridLines(gridLines);
    linearAxes.setScaleLabel(label);

    CartesianScales cScales = new CartesianScales();
    cScales.addXAxesData(linearAxes);
    cScales.addYAxesData(linearAxes);
    cScales.setDisplay(true);

    Tooltip tooltip = new Tooltip();
    tooltip.setEnabled(false);

    BarChartOptions options = new BarChartOptions();
    options.setScales(cScales);
    options.setTooltip(tooltip);
    options.setOffsetGridLines(false);

    stackedBarModel.setOptions(options);
}


问:
spring.profiles.active not working for all profiles
In my spring boot application, I have multiple profiles as below:

```<code>application.yml
application-dev.yml
application-local.yml
application-qa.yml
application-prod.yml
</code>```

Each profile will have its own datasource configured. For testing purpose, same datasource configuration are passed in all profiles.

In application.yml if I mention spring.profiles.active=dev it is connecting to DB successfully. But if I mention spring.profiles.active=local then on server startup local profile is getting active with below error

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (the profiles lcl are currently active).
</code>```

Below configuration passed in all profiles excluding application.yml

```<code>spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    password: root
    url: jdbc:mysql://localhost:3306/local_db?useSSL=false
    username: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  liquibase:
    change-log: classpath:db/changelog/db.changelog-master.json
</code>```

Body:
In my spring boot application, I have multiple profiles as below:

application.yml
application-dev.yml
application-local.yml
application-qa.yml
application-prod.yml

Each profile will have its own datasource configured. For testing purpose, same datasource configuration are passed in all profiles.

In application.yml if I mention spring.profiles.active=dev it is connecting to DB successfully. But if I mention spring.profiles.active=local then on server startup local profile is getting active with below error

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (the profiles lcl are currently active).

Below configuration passed in all profiles excluding application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    password: root
    url: jdbc:mysql://localhost:3306/local_db?useSSL=false
    username: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  liquibase:
    change-log: classpath:db/changelog/db.changelog-master.json


问:
Mac application not running from Launchpad
I have a self written application.

It runs OK when I start it from terminal via

```<code>/Applications/XXX.app/Contents/MacOS/xxx
</code>```

But it does not run from Launchpad

XXX.app/Contents/Info.plist

```<code>
<?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>CFBundleDevelopmentRegion</key>
    <string>English</string>
    <key>CFBundleExecutable</key>
    <string>xxx</string>
    <key>CFBundleIconFile</key>
    <string>icon.icns</string>
</dict>
</plist>
</code>```

Starting it from terminal with
open -a /Applications/XXX.app

Results in

```<code>LSOpenURLsWithRole() failed for the application /Applications/Portfolio.app with error -10810.
</code>```

The pkg file was build with

```<code>pkgbuild --identifier com.xxx.xxx --install-location /Applications/XXX.app --root /Users/uuuu/XXX.app XXX.pkg
</code>```

How do I find the reason for that?

Body:
I have a self written application.

It runs OK when I start it from terminal via

/Applications/XXX.app/Contents/MacOS/xxx

But it does not run from Launchpad

XXX.app/Contents/Info.plist

<?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>CFBundleDevelopmentRegion</key>
    <string>English</string>
    <key>CFBundleExecutable</key>
    <string>xxx</string>
    <key>CFBundleIconFile</key>
    <string>icon.icns</string>
</dict>
</plist>

Starting it from terminal with
open -a /Applications/XXX.app

Results in

LSOpenURLsWithRole() failed for the application /Applications/Portfolio.app with error -10810.

The pkg file was build with

pkgbuild --identifier com.xxx.xxx --install-location /Applications/XXX.app --root /Users/uuuu/XXX.app XXX.pkg

How do I find the reason for that?


问:
Any idea how to install chat-script for zsh I am unable to find it
Any idea how to install chat-script for zsh I am unable to find it

chatty-script >/dev/null

```<code>keychain id_rsa --agents ssh  # moved before instant prompt

# OK to perform console I/O before this point.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi
# From this point on, until zsh is fully initialized, console input won't work and
# console output may appear uncolored.

chatty-script >/dev/null      # spam output suppressed
</code>```

https://github.com/romkatv/powerlevel10k/blob/master/README.md?plain=1#L1033

Body:
Any idea how to install chat-script for zsh I am unable to find it

chatty-script >/dev/null

keychain id_rsa --agents ssh  # moved before instant prompt

# OK to perform console I/O before this point.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi
# From this point on, until zsh is fully initialized, console input won't work and
# console output may appear uncolored.

chatty-script >/dev/null      # spam output suppressed

https://github.com/romkatv/powerlevel10k/blob/master/README.md?plain=1#L1033


问:
Float to datetime or timestamp SSIS
does anyone know how to convert float to datetime or timestamp in SSIS? Please

Example, float = 0,25; time = 06:00:00

(DT_DBTIMESTAMP)[column float]

Title: Float to datetime or timestamp SSIS


问:
Pytorch model issues while running for multilabel classifications
I am working on a classification problem using (1D-CNN) the model I built and the data loaders are working perfectly. However, during the training and the validation loops I encounter an issue.
I have a multilabel classification problem and before training the model on all 4 labels I have, I did a splitting and encoding for the label data so that each label will trained individually. the code below shows the splitting and the encoding steps are shown in the first 12 lines in the for loop below.

executing the code above within the training loop did the job for me. However, when I move onto the training functions, the model will train the outputs to match the first label group only, and when I observe the values of the output for the second, third and fourth run, the values are the same. the code below shows the training step: (the code below is included in the for loop mentioned above):

```<code>for epoch in tqdm(range(50)):

    for batch, (features, labels) in enumerate(train_loader):
        #encoding the labels
        Ordinal_Labels = encoder.fit_transform(labels)
        y1 = torch.from_numpy(Ordinal_Labels)
        y2 = y1.to(torch.int64)
        y_train = functional.one_hot(y2)
        x1 = y_train[:, 0:1, :]
        x2 = y_train[:, 1:2, :]
        x3 = y_train[:, 2:3, :]
        x4 = y_train[:, 3:4, :]
        label1 = torch.squeeze(x1, 1).to(torch.float64)
        label2 = torch.squeeze(x2, 1).to(torch.float64)
        label3 = torch.squeeze(x3, 1).to(torch.float64)
        label4 = torch.squeeze(x4, 1).to(torch.float64)

        optimizer.zero_grad()

        #training the model
        output1= model(features)
        output2= model(features)
        output3= model(features)
        output4= model(features)

        #obtaining the loss for each label
        loss1= criterion(output1, label1)
        loss2= criterion(output2, label2)
        loss3= criterion(output3, label3)
        loss4= criterion(output4, label4)

        #backward pass tp update the model parameters
        loss1.backward()
        loss2.backward()
        loss3.backward()
        loss4.backward()
        #updating the grad parameters after the backward propagation
        optimizer.step()

        #obtaining the total loss value
        loss= loss4 #+ loss2 + loss3 + loss4

        epoch_loss.append(loss.item())
</code>```

I tried building separate functions for each label on which the model will be executed on a one label group, however, running all 4 function together in the same for loop gives the same error.

Any help in such a problem is much appreciated

Body:
I am working on a classification problem using (1D-CNN) the model I built and the data loaders are working perfectly. However, during the training and the validation loops I encounter an issue.
I have a multilabel classification problem and before training the model on all 4 labels I have, I did a splitting and encoding for the label data so that each label will trained individually. the code below shows the splitting and the encoding steps are shown in the first 12 lines in the for loop below.

executing the code above within the training loop did the job for me. However, when I move onto the training functions, the model will train the outputs to match the first label group only, and when I observe the values of the output for the second, third and fourth run, the values are the same. the code below shows the training step: (the code below is included in the for loop mentioned above):

for epoch in tqdm(range(50)):

    for batch, (features, labels) in enumerate(train_loader):
        #encoding the labels
        Ordinal_Labels = encoder.fit_transform(labels)
        y1 = torch.from_numpy(Ordinal_Labels)
        y2 = y1.to(torch.int64)
        y_train = functional.one_hot(y2)
        x1 = y_train[:, 0:1, :]
        x2 = y_train[:, 1:2, :]
        x3 = y_train[:, 2:3, :]
        x4 = y_train[:, 3:4, :]
        label1 = torch.squeeze(x1, 1).to(torch.float64)
        label2 = torch.squeeze(x2, 1).to(torch.float64)
        label3 = torch.squeeze(x3, 1).to(torch.float64)
        label4 = torch.squeeze(x4, 1).to(torch.float64)

        optimizer.zero_grad()

        #training the model
        output1= model(features)
        output2= model(features)
        output3= model(features)
        output4= model(features)

        #obtaining the loss for each label
        loss1= criterion(output1, label1)
        loss2= criterion(output2, label2)
        loss3= criterion(output3, label3)
        loss4= criterion(output4, label4)

        #backward pass tp update the model parameters
        loss1.backward()
        loss2.backward()
        loss3.backward()
        loss4.backward()
        #updating the grad parameters after the backward propagation
        optimizer.step()

        #obtaining the total loss value
        loss= loss4 #+ loss2 + loss3 + loss4

        epoch_loss.append(loss.item())

I tried building separate functions for each label on which the model will be executed on a one label group, however, running all 4 function together in the same for loop gives the same error.

Any help in such a problem is much appreciated


问:
How to bulk delete files from AWS S3 with PHP using the sdk?
I have a Laravel 9.x project with PHP 8.x.
My project has a database/table for media files and the actual media is stored on AWS S3.
I basically am using just one bucket and two folders inside the bucket /photos and /videos.

My logic needs to query my table for all the media that has expired and then it will delete the media files from S3.

If I use the Storage class and delete one file at a time (like example below) it works fine. Which leads me to think my credentials must be OK.

```<code>Storage::disk('s3')->delete($filename);
</code>```

However it takes way too long. For example when I ran the job last night it had to delete 148,000 files and it took 7.5 hours to run. Because I expect my volume will double every year for the next 3 - 5 years it will eventually have to run 24 hours a day and possibly not be able to keep up. Since the Laravel 9.x Storage class does not appear to support bulk deletes I am trying to write my own PHP and use the AWS SDK myself to delete multiple files from my bucket which is NOT versioned. The code I wrote below accepts an array of filenames as they would be inside the bucket and it breaks it into blocks of up to 999 (because the docs say 1,000 is the maximum).

```<code>    public static function awsBulkDelete($files)
{
    Log::info('============ awsBulkDelete ================');
    Log::info(json_encode($files, JSON_PRETTY_PRINT));
    Log::info('===========================================');
    $region = config('aws.s3.region');
    $bucket = config('aws.s3.bucket');
    $s3 = new S3Client(['region' => $region, 'version' => 'latest']);

    $objects = [] ;
    $count = 0;
    $remaining = count($files);
    foreach ($files as $file) {
        $count++;
        $remaining--;
        $objects[] = ['Key' => $file];
        if (($count == 999) || ($remaining == 0)) {
            $count = 0 ;
            $results = $s3->deleteObjects([
                'Bucket' => $bucket,
                'Delete' => ['Objects' => $objects,]
            ]);
            Log::info(json_encode($results->toArray(), JSON_PRETTY_PRINT));
            Log::info('===========================================');
            $objects = [];
        }
    }
}
</code>```

The code seems to be working except I am getting Access Denied for every file.
Below is a small example of the logs for listing the $files array:

```<code>[2023-01-04 11:37:56] production.INFO: ============ awsBulkDelete ================
[2023-01-04 11:37:56] production.INFO: [
"photos/37944311-ae803150d2.jpg",
"photos/37944311-ae803150d2-thumb.jpg",
"photos/37944321-4de38fa1d5.jpg",
"photos/37944321-4de38fa1d5-thumb.jpg",
"videos/37944366-967bb1a35a.mp4",
"photos/37944366-967bb1a35a.jpg",
"photos/37944366-967bb1a35a-thumb.jpg",
</code>```

And below is an example of what I am getting back for every request:

```<code>[2023-01-04 11:37:56] production.INFO: ===========================================
[2023-01-04 11:37:56] production.INFO: {
"RequestCharged": "",
"Errors": [
    {
        "Key": "photos/26956180-00df1a5087-thumb.jpg",
        "Code": "AccessDenied",
        "Message": "Access Denied"
    },
    {
        "Key": "photos/37992171-09773b703f-thumb.jpg",
        "Code": "AccessDenied",
        "Message": "Access Denied"
    },
    {
        "Key": "photos/37992186-6c9c589710-thumb.jpg",
        "Code": "AccessDenied",
        "Message": "Access Denied"
    },
</code>```

I can't figure out if this is a coding issue or if it is a permissions issue on my AWS account?  Any help would be greatly appreciated.

Edit: The IAM user that is being used has AmazonS3FullAccess permission but I noticed when I expand on that and go into the S3 portion it list like 100 permissions including DeleteObject

Body:
I have a Laravel 9.x project with PHP 8.x.
My project has a database/table for media files and the actual media is stored on AWS S3.
I basically am using just one bucket and two folders inside the bucket /photos and /videos.

My logic needs to query my table for all the media that has expired and then it will delete the media files from S3.

If I use the Storage class and delete one file at a time (like example below) it works fine. Which leads me to think my credentials must be OK.

Storage::disk('s3')->delete($filename);

However it takes way too long. For example when I ran the job last night it had to delete 148,000 files and it took 7.5 hours to run. Because I expect my volume will double every year for the next 3 - 5 years it will eventually have to run 24 hours a day and possibly not be able to keep up. Since the Laravel 9.x Storage class does not appear to support bulk deletes I am trying to write my own PHP and use the AWS SDK myself to delete multiple files from my bucket which is NOT versioned. The code I wrote below accepts an array of filenames as they would be inside the bucket and it breaks it into blocks of up to 999 (because the docs say 1,000 is the maximum).

    public static function awsBulkDelete($files)
{
    Log::info('============ awsBulkDelete ================');
    Log::info(json_encode($files, JSON_PRETTY_PRINT));
    Log::info('===========================================');
    $region = config('aws.s3.region');
    $bucket = config('aws.s3.bucket');
    $s3 = new S3Client(['region' => $region, 'version' => 'latest']);

    $objects = [] ;
    $count = 0;
    $remaining = count($files);
    foreach ($files as $file) {
        $count++;
        $remaining--;
        $objects[] = ['Key' => $file];
        if (($count == 999) || ($remaining == 0)) {
            $count = 0 ;
            $results = $s3->deleteObjects([
                'Bucket' => $bucket,
                'Delete' => ['Objects' => $objects,]
            ]);
            Log::info(json_encode($results->toArray(), JSON_PRETTY_PRINT));
            Log::info('===========================================');
            $objects = [];
        }
    }
}

The code seems to be working except I am getting Access Denied for every file.
Below is a small example of the logs for listing the $files array:

[2023-01-04 11:37:56] production.INFO: ============ awsBulkDelete ================
[2023-01-04 11:37:56] production.INFO: [
"photos/37944311-ae803150d2.jpg",
"photos/37944311-ae803150d2-thumb.jpg",
"photos/37944321-4de38fa1d5.jpg",
"photos/37944321-4de38fa1d5-thumb.jpg",
"videos/37944366-967bb1a35a.mp4",
"photos/37944366-967bb1a35a.jpg",
"photos/37944366-967bb1a35a-thumb.jpg",

And below is an example of what I am getting back for every request:

[2023-01-04 11:37:56] production.INFO: ===========================================
[2023-01-04 11:37:56] production.INFO: {
"RequestCharged": "",
"Errors": [
    {
        "Key": "photos/26956180-00df1a5087-thumb.jpg",
        "Code": "AccessDenied",
        "Message": "Access Denied"
    },
    {
        "Key": "photos/37992171-09773b703f-thumb.jpg",
        "Code": "AccessDenied",
        "Message": "Access Denied"
    },
    {
        "Key": "photos/37992186-6c9c589710-thumb.jpg",
        "Code": "AccessDenied",
        "Message": "Access Denied"
    },

I can't figure out if this is a coding issue or if it is a permissions issue on my AWS account?  Any help would be greatly appreciated.

Edit: The IAM user that is being used has AmazonS3FullAccess permission but I noticed when I expand on that and go into the S3 portion it list like 100 permissions including DeleteObject


问:
Vuevalidate optional validator is not working if you made it optional
Greetings I have project on vuejs3 and using vuelidate as validator library. I have form to validate users password. First user must enter tmp password send by server then new password.
Check is made if user entered correct tmp password or not.

I want validator what only works if it have some values(password input is not empty). Currently it launches if password field is empty. And as you expect it throws error on back-end because to end-point was passed String with null.(As back-end I am using C# mvc)

Validator itself

```<code>import userService from '@/services/user-service';
import { helpers } from '@vuelidate/validators';
const { withAsync } = helpers;

const isPasswordCorrect = helpers.withMessage(
    () => 'The requested password does not belong to this user',
    withAsync(async (value: string) => {
        return await userService.isPasswordCorrect(value); // call to end-point to check if password is correct
    })
);

export { isPasswordCorrect };
</code>```

What I tried to write optional validator as shown in docs click but it does not work. When I press btn to validate form it does nothing. Works as if there was no validator at all.

```<code>import userService from '@/services/user-service';
import { helpers } from '@vuelidate/validators';
const { withAsync } = helpers;

const isPasswordCorrect = (value: string) => !helpers.req(value) || helpers.withMessage(
    () => 'The requested password does not belong to this user',
    withAsync(async (value: string) => {
        return await userService.isPasswordCorrect(value);
    })
);

export { isPasswordCorrect };
</code>```

So any ideas how to write custom validator what is not "triggered" with empty value?

Body:
Greetings I have project on vuejs3 and using vuelidate as validator library. I have form to validate users password. First user must enter tmp password send by server then new password.
Check is made if user entered correct tmp password or not.

I want validator what only works if it have some values(password input is not empty). Currently it launches if password field is empty. And as you expect it throws error on back-end because to end-point was passed String with null.(As back-end I am using C# mvc)

Validator itself

import userService from '@/services/user-service';
import { helpers } from '@vuelidate/validators';
const { withAsync } = helpers;

const isPasswordCorrect = helpers.withMessage(
    () => 'The requested password does not belong to this user',
    withAsync(async (value: string) => {
        return await userService.isPasswordCorrect(value); // call to end-point to check if password is correct
    })
);

export { isPasswordCorrect };

What I tried to write optional validator as shown in docs click but it does not work. When I press btn to validate form it does nothing. Works as if there was no validator at all.

import userService from '@/services/user-service';
import { helpers } from '@vuelidate/validators';
const { withAsync } = helpers;

const isPasswordCorrect = (value: string) => !helpers.req(value) || helpers.withMessage(
    () => 'The requested password does not belong to this user',
    withAsync(async (value: string) => {
        return await userService.isPasswordCorrect(value);
    })
);

export { isPasswordCorrect };

So any ideas how to write custom validator what is not "triggered" with empty value?


问:
Multiples sites log on
We have several websites that use same authentication method. The account and authentication is via a third party system and we developed library to authenticate against in C#. The user would enter a user & password and C# library will pick it up and do the authentication.

Following is what we are asked to implement

A user logs into any one of the sites. At that time a token needs to be created it should be good for a period of time.

If the same user tries to access another of our site, user should automatically log in  because there is an unexpired token from step 1.

Is there a way to implement this? From what I know all the cookie and storage are per site and one site's cookie cannot be accessed by another one. If one site can access another ones   token that is a security breach to me. So is there anyway to achieve this?

Title: Multiples sites log on


问:
SmoothState function is not a function when bundling with Parcel
I'm using parcel to bundle and develop my website and want to use SmoothState for the page transitions. I've downloaded the jquery.smoothState.min.js and included it in my scripts folder. I installed jquery using npm and it has been working fine so far. I've included this in the head of my HTML page:

```
<p>And this is the contents of script.js</p>
<pre class="lang-js prettyprint-override"><code>var jquery = require("jquery");
window.$ = window.jQuery = jquery;

$(function() {
    $('#main').smoothState();
  });
</code>```

When everything gets bundled, I get the error:
jQuery.Deferred exception: $(...).smoothState is not a function

I've tried removing the jquery module import lines in script.js and including the Jquery Google CDN above the two script tags in the HTML file but it results in the same error message.

Body:
I'm using parcel to bundle and develop my website and want to use SmoothState for the page transitions. I've downloaded the jquery.smoothState.min.js and included it in my scripts folder. I installed jquery using npm and it has been working fine so far. I've included this in the head of my HTML page:

And this is the contents of script.js

var jquery = require("jquery");
window.$ = window.jQuery = jquery;

$(function() {
    $('#main').smoothState();
  });

When everything gets bundled, I get the error:
jQuery.Deferred exception: $(...).smoothState is not a function

I've tried removing the jquery module import lines in script.js and including the Jquery Google CDN above the two script tags in the HTML file but it results in the same error message.


问:
Policy changes in 2022 make it very difficult to try SMS sending functionality in AWS
It seems that, recently, Amazon changed its flow to send test SMS messages (to a US number):

You can only successfully send SMS messages to numbers added to SMS sandbox.

To add a phone number to the SMS sandbox, you have to first specify an origination entity

In the US, only originating numbers are supported

SMSs can only be sent from toll-free and 10DLC, both of which require registration due to recent changes (9/30/2022) in carriers' policies.

Registration requires providing company information.

The above makes it next to impossible to test sending SMS if you don't have a company (or if your company is unwilling to undergo the phone registration process). Is there a simpler way to do this or am I missing something?


问:
3 x 8 Contingency Table in Python using actual values from data frame, not counts between the 2 variables
I need a chart in python to display the following data in 3 by 8 form i.e B50, S50, B50-S50 as the rows and Sector as the columns. The crosstab() function gives the correlation or counts between variables, I just need a chart of the following data in 3 by 8 form.

```<code>   Sector B50      S50             B50 - S50
   x1     19.94    19.00              0.94
   x2     14.09    12.29              1.80
   x3     9.33    10.60              -1.27
   x4     15.63    12.01              3.62
   x5      8.25    17.61             -9.36
   x6      3.81    3.48               0.33
   x7     11.88    12.81             -0.93
   x8     17.25    12.16              5.09
</code>```

I tried searching for a python graph that just displays data, but I could not find one to accomplish this simple task.

Body:
I need a chart in python to display the following data in 3 by 8 form i.e B50, S50, B50-S50 as the rows and Sector as the columns. The crosstab() function gives the correlation or counts between variables, I just need a chart of the following data in 3 by 8 form.

   Sector B50      S50             B50 - S50
   x1     19.94    19.00              0.94
   x2     14.09    12.29              1.80
   x3     9.33    10.60              -1.27
   x4     15.63    12.01              3.62
   x5      8.25    17.61             -9.36
   x6      3.81    3.48               0.33
   x7     11.88    12.81             -0.93
   x8     17.25    12.16              5.09

I tried searching for a python graph that just displays data, but I could not find one to accomplish this simple task.


问:
Keycloak redirects too many times after login in Spring gateway cloud
I am building one spring cloud gateway and in that I am implementing Keycloak Security everything works fine but once login done on keycloak it is not redirecting back and showing error too many redirects I am not sure what I am missing?

Below are the dependencies which I am using:

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
</code>```

And my application Api gateway start application code is as below:

```<code>@SpringBootApplication
@ComponentScan(basePackages = {"com", "com.b","com.auth","com.security"})
public class APIGatewayApplication {
   public static void main(String[] args) {
        SpringApplication.run(APIGatewayApplication.class, args);
    }
   @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        return new PathBasedKeycloakConfigResolver();
    }
}
</code>```

Security Config http code is as below:

```<code>@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain (ServerHttpSecurity http) {

        http
                .authorizeExchange()
                .anyExchange()
                .authenticated()
                .and()
                .oauth2Login(); // to redirect to oauth2 login page.

        return http.build();
    }

}
</code>```

and in my application.yml file I am adding below configuration:

```<code>spring:
  security:
    oauth2:
      client:
        provider:
          my-keycloak-provider:
            issuer-uri: http://localhost:8280/auth/realms/Default
        registration:
          keycloak-spring-gateway-client:
            provider: my-keycloak-provider
            client-id: Default
            client-secret: 8ZRUH62Pfhfde6uqasD8dfgdhvqWt03K6
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/app'
  main:
    web-application-type: reactive
  application:
    name: app
  cloud:
    gateway:
      default-filters:
        - TokenRelay
</code>```

So when I start application it is running fine and it is getting redirected to the Keycloak login page and after login it shows error "localhost redirected you too many times." How to resolve it so once it is login it should redirected once only to main application? Please help.

Body:
I am building one spring cloud gateway and in that I am implementing Keycloak Security everything works fine but once login done on keycloak it is not redirecting back and showing error too many redirects I am not sure what I am missing?

Below are the dependencies which I am using:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

And my application Api gateway start application code is as below:

@SpringBootApplication
@ComponentScan(basePackages = {"com", "com.b","com.auth","com.security"})
public class APIGatewayApplication {
   public static void main(String[] args) {
        SpringApplication.run(APIGatewayApplication.class, args);
    }
   @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        return new PathBasedKeycloakConfigResolver();
    }
}

Security Config http code is as below:

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain (ServerHttpSecurity http) {

        http
                .authorizeExchange()
                .anyExchange()
                .authenticated()
                .and()
                .oauth2Login(); // to redirect to oauth2 login page.

        return http.build();
    }

}

and in my application.yml file I am adding below configuration:

spring:
  security:
    oauth2:
      client:
        provider:
          my-keycloak-provider:
            issuer-uri: http://localhost:8280/auth/realms/Default
        registration:
          keycloak-spring-gateway-client:
            provider: my-keycloak-provider
            client-id: Default
            client-secret: 8ZRUH62Pfhfde6uqasD8dfgdhvqWt03K6
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/app'
  main:
    web-application-type: reactive
  application:
    name: app
  cloud:
    gateway:
      default-filters:
        - TokenRelay

So when I start application it is running fine and it is getting redirected to the Keycloak login page and after login it shows error "localhost redirected you too many times." How to resolve it so once it is login it should redirected once only to main application? Please help.


问:
Avatar gives me an error when i try to call it
Processing cannot locate my class in the main method.

I tried looking for extra or missing brackets, but didn't find any.

The error reads "Cannot find a class or type named "Avatar"", and i'm not sure what the problem is. I am fairly confident that the class is set up correctly

```<code>class Avatar {

  int x1;  //location variables of the main body parts
  int y1;
  int x2;
  int y2;
  int x3;
  int y3;

  Avatar() {
    x1 = 300;
    y1 = 200;
    x2 = 300;
    y2 = 350;
    x3 = 300;
    y3 = 550;
  }//end of constructor

  void display() {
    //main body
    fill(255);  //white
    noStroke(); //no line on the outside
    ellipse(x1, y1, 150, 150);  //head
    ellipse(x2, y2, 200, 200);  //middle portion
    ellipse(x3, y3, 300, 300);  //bottom portion
    //additional parts

    //sunglasses
    rectMode(CENTER);  //sets all rectangles to draw from the center
    fill(0);
    rect(260, 190, 40, 25);
    rect(340, 190, 40, 25);
    ellipse(260, 200.5, 40, 19.5);
    ellipse(340, 200.5, 40, 19.5);
    stroke(0);
    line(240, 180, 350, 180);
    line(200, 155, 250, 180);
    line(400, 155, 359, 180);

    //Smile
    arc(float(300), float(211), float(65), float(75), float(0), PI);

    //Leather Jacket
    fill(0);
    ellipse(x2, y2, 200, 200);
    fill(175);
    ellipse(300, 300, 15, 15);
    ellipse(300, 350, 15, 15);
    ellipse(300, 400, 15, 15);

    //Arms
    strokeWeight(25);
    fill(0);
    line(100, 550, 205, 300);
    line(500, 550, 395, 300);
    ellipse(100, 550, 25, 25);
    ellipse(500, 550, 25, 25);

    //belt
    noStroke();
    rectMode(CENTER);
    fill(35);
    rect(x2, y2+90, 200, 60);
  }//end of display function
}//end of avatar class
</code>```

the main function is just:

```<code>Avatar p1Avatar;
Avatar p2Avatar;
</code>```

Body:
Processing cannot locate my class in the main method.

I tried looking for extra or missing brackets, but didn't find any.

The error reads "Cannot find a class or type named "Avatar"", and i'm not sure what the problem is. I am fairly confident that the class is set up correctly

class Avatar {

  int x1;  //location variables of the main body parts
  int y1;
  int x2;
  int y2;
  int x3;
  int y3;

  Avatar() {
    x1 = 300;
    y1 = 200;
    x2 = 300;
    y2 = 350;
    x3 = 300;
    y3 = 550;
  }//end of constructor

  void display() {
    //main body
    fill(255);  //white
    noStroke(); //no line on the outside
    ellipse(x1, y1, 150, 150);  //head
    ellipse(x2, y2, 200, 200);  //middle portion
    ellipse(x3, y3, 300, 300);  //bottom portion
    //additional parts

    //sunglasses
    rectMode(CENTER);  //sets all rectangles to draw from the center
    fill(0);
    rect(260, 190, 40, 25);
    rect(340, 190, 40, 25);
    ellipse(260, 200.5, 40, 19.5);
    ellipse(340, 200.5, 40, 19.5);
    stroke(0);
    line(240, 180, 350, 180);
    line(200, 155, 250, 180);
    line(400, 155, 359, 180);

    //Smile
    arc(float(300), float(211), float(65), float(75), float(0), PI);

    //Leather Jacket
    fill(0);
    ellipse(x2, y2, 200, 200);
    fill(175);
    ellipse(300, 300, 15, 15);
    ellipse(300, 350, 15, 15);
    ellipse(300, 400, 15, 15);

    //Arms
    strokeWeight(25);
    fill(0);
    line(100, 550, 205, 300);
    line(500, 550, 395, 300);
    ellipse(100, 550, 25, 25);
    ellipse(500, 550, 25, 25);

    //belt
    noStroke();
    rectMode(CENTER);
    fill(35);
    rect(x2, y2+90, 200, 60);
  }//end of display function
}//end of avatar class

the main function is just:

Avatar p1Avatar;
Avatar p2Avatar;


问:
Setting value maximum and minimum value of SpinBox in Qt Creator
How to set value of SpinBox in QT Creator with python, I mean set minimum and maximum value?

I tried that but I do not know how to relate SpinBox and my function.


问:
non-existent service "http_client" while upgrading symfony 4 to 6
I'm migrating a Symfony 4 app to Symfony 6. Symfony like change everything in next major version.

I'm supposing the problem come from api platform but not really sure.

```<code>!!
!!  In CheckExceptionOnInvalidReferenceBehaviorPass.php line 83:
!!
!!    The service "api_platform.http_cache.purger.varnish.ban" has a dependency o
!!    n a non-existent service "http_client".
!!
</code>```

I tryed searching "api_platform.http_cache.purger.varnish.ban" or "varnish.ban" or "http_client" with grep command but no results, like if this line isn't in any file of the app.

Body:
I'm migrating a Symfony 4 app to Symfony 6. Symfony like change everything in next major version.

I'm supposing the problem come from api platform but not really sure.

!!
!!  In CheckExceptionOnInvalidReferenceBehaviorPass.php line 83:
!!
!!    The service "api_platform.http_cache.purger.varnish.ban" has a dependency o
!!    n a non-existent service "http_client".
!!

I tryed searching "api_platform.http_cache.purger.varnish.ban" or "varnish.ban" or "http_client" with grep command but no results, like if this line isn't in any file of the app.


问:
jqueryvalidation's valid function missing in jQuery 3 Object
I have a sitation where a website is jqueryvalidation with jQuery 2.x - all works.

There's a small DIV which is powered by React and references the global jQuery validate plugin.

```<code>import { $ } from 'jquery';

// Expose jQuery to the global object
window.$ = $;

export default function validate(field, value) {
   console.log("inside validate")
   return window.$('#' + field.id).valid();
}
</code>```

When I upgraded the jQuery version from 2 to 3.6.1 and jquery.validate.js ver 1.19.5, the valid function neither gets called nor does it show an error like valid isn't a function.

I even inserted console.log inside the source valid() function and it isn't getting consoled.

I just can't seem to figure out what happened to valid.

console.log(window.$('#' + field.id)) shows valid in the jquery 2.x page but not on the 3.x page.

Only other difference I noticed is missing context and selector in jQuery version 3.

jQuery 2:

jQuery 3:

Body:
I have a sitation where a website is jqueryvalidation with jQuery 2.x - all works.

There's a small DIV which is powered by React and references the global jQuery validate plugin.

import { $ } from 'jquery';

// Expose jQuery to the global object
window.$ = $;

export default function validate(field, value) {
   console.log("inside validate")
   return window.$('#' + field.id).valid();
}

When I upgraded the jQuery version from 2 to 3.6.1 and jquery.validate.js ver 1.19.5, the valid function neither gets called nor does it show an error like valid isn't a function.

I even inserted console.log inside the source valid() function and it isn't getting consoled.

I just can't seem to figure out what happened to valid.

console.log(window.$('#' + field.id)) shows valid in the jquery 2.x page but not on the 3.x page.

Only other difference I noticed is missing context and selector in jQuery version 3.

jQuery 2:

jQuery 3:


问:
Data filtering query in Laravel many-to-many relationship
there is a table named products and another table named features that have a many-to-many relationship.

I want to write a query that returns products that, for example, have features 2, 3, and 11 at the same time. Now I wrote the following command

```<code>$params = [2,3,11];

            $products = Product::with('photos')
            ->whereHas('features', function ($q) use ($params) {
                    $q->whereIn('feature_id' , $params);

            })
            ->whereIn('category_id', $ids)
            ->orderByRaw($sortBy)
            ->paginate($paginate);
</code>```

when I use whereIn, it works in the form of OR and shows me products that either have the feature 2 or 3 or 11..
I want it to be in the form of AND, which means it will only find products that have all the desired features together

```<code>$products = Product::with('photos')
            ->whereHas('features', function ($q) use ($params) {
                foreach($params as $p) {
                    $q->where('feature_id', $p);
                }
            })
            ->whereIn('category_id', $ids)
            ->orderByRaw($sortBy)
            ->paginate($paginate);
</code>```

and this query that I wrote returns empty data.

Body:
there is a table named products and another table named features that have a many-to-many relationship.

I want to write a query that returns products that, for example, have features 2, 3, and 11 at the same time. Now I wrote the following command

$params = [2,3,11];

            $products = Product::with('photos')
            ->whereHas('features', function ($q) use ($params) {
                    $q->whereIn('feature_id' , $params);

            })
            ->whereIn('category_id', $ids)
            ->orderByRaw($sortBy)
            ->paginate($paginate);

when I use whereIn, it works in the form of OR and shows me products that either have the feature 2 or 3 or 11..
I want it to be in the form of AND, which means it will only find products that have all the desired features together

$products = Product::with('photos')
            ->whereHas('features', function ($q) use ($params) {
                foreach($params as $p) {
                    $q->where('feature_id', $p);
                }
            })
            ->whereIn('category_id', $ids)
            ->orderByRaw($sortBy)
            ->paginate($paginate);

and this query that I wrote returns empty data.


问:
How to programmatically configure keycloak with spring cloud gateway api?
I am building one spring cloud gateway and in that I am implementing Keycloak Security everything works fine but need to do programmatically instead of writing in yml file there can be multiple Realms.

Below are the dependencies which I am using:

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
</code>```

And my application Api gateway start application code is as below:

```<code>@SpringBootApplication
@ComponentScan(basePackages = {"com", "com.b","com.auth","com.security"})
public class APIGatewayApplication {
   public static void main(String[] args) {
        SpringApplication.run(APIGatewayApplication.class, args);
    }
   @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        return new PathBasedKeycloakConfigResolver();
    }
}
</code>```

Security Config http code is as below:

```<code>@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain (ServerHttpSecurity http) {

        http
                .authorizeExchange()
                .anyExchange()
                .authenticated()
                .and()
                .oauth2Login(); // to redirect to oauth2 login page.

        return http.build();
    }

}
</code>```

and in my application.yml file I am adding below configuration:

```<code>spring:
  security:
    oauth2:
      client:
        provider:
          my-keycloak-provider:
            issuer-uri: http://localhost:8280/auth/realms/Default
        registration:
          keycloak-spring-gateway-client:
            provider: my-keycloak-provider
            client-id: Default
            client-secret: 8ZRUH62Pfhfde6uqasD8dfgdhvqWt03K6
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/app'
  main:
    web-application-type: reactive
  application:
    name: app
  cloud:
    gateway:
      default-filters:
        - TokenRelay
</code>```

So we can in configuration file I am manually adding configs for one Realms but there can be multiple realms in that how to do it programmatically dynamic? .

Body:
I am building one spring cloud gateway and in that I am implementing Keycloak Security everything works fine but need to do programmatically instead of writing in yml file there can be multiple Realms.

Below are the dependencies which I am using:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

And my application Api gateway start application code is as below:

@SpringBootApplication
@ComponentScan(basePackages = {"com", "com.b","com.auth","com.security"})
public class APIGatewayApplication {
   public static void main(String[] args) {
        SpringApplication.run(APIGatewayApplication.class, args);
    }
   @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        return new PathBasedKeycloakConfigResolver();
    }
}

Security Config http code is as below:

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain (ServerHttpSecurity http) {

        http
                .authorizeExchange()
                .anyExchange()
                .authenticated()
                .and()
                .oauth2Login(); // to redirect to oauth2 login page.

        return http.build();
    }

}

and in my application.yml file I am adding below configuration:

spring:
  security:
    oauth2:
      client:
        provider:
          my-keycloak-provider:
            issuer-uri: http://localhost:8280/auth/realms/Default
        registration:
          keycloak-spring-gateway-client:
            provider: my-keycloak-provider
            client-id: Default
            client-secret: 8ZRUH62Pfhfde6uqasD8dfgdhvqWt03K6
            authorization-grant-type: authorization_code
            redirect-uri: '{baseUrl}/app'
  main:
    web-application-type: reactive
  application:
    name: app
  cloud:
    gateway:
      default-filters:
        - TokenRelay

So we can in configuration file I am manually adding configs for one Realms but there can be multiple realms in that how to do it programmatically dynamic? .


问:
Why are there connections between these points in chartjs?
I have an angular apllication I which I display a chart. The chart is filled with data from a database. The y axis displays sensordata and the x axis displays a timestamp. The timestamp is also a column in the database. When I start the app there are connections between some points that I don´t want and that don´t make sense! Why is that so?

```<code>ngOnInit(): void {
var chartOptions = {
            plugins: {
                legend: {
                    display: false
                }
            },
            responsive: true,
            maintainAspectRatio: false,
            animation: {duration: 0}
        };

 var tempChart = new Chart('tempChart', {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                data: [0],
                borderWidth: 1
            }]
        },
        options: chartOptions
    });

setInterval(() => {
        // API request
        this.service.getMesswerte().subscribe({
          next: data => {
                this.chartData = data;
                this.fillChartData(this.chartData);
          }
        })
       }, 1000)

 setInterval(() => {
        tempChart.data.datasets[0].data = this.tempArray;
        tempChart.update();
       }, 1000)
}
private fillChartData(chartData: Object)
{
    this.objects = Object.values(chartData);
    for(let row in this.objects)
    {
        this.tempObject = {
            x: this.objects[row].timestamp,
            y: this.objects[row].airtemp
        }

      this.tempArray.push(this.tempObject);
    }
}
</code>```

Body:
I have an angular apllication I which I display a chart. The chart is filled with data from a database. The y axis displays sensordata and the x axis displays a timestamp. The timestamp is also a column in the database. When I start the app there are connections between some points that I don´t want and that don´t make sense! Why is that so?

ngOnInit(): void {
var chartOptions = {
            plugins: {
                legend: {
                    display: false
                }
            },
            responsive: true,
            maintainAspectRatio: false,
            animation: {duration: 0}
        };

 var tempChart = new Chart('tempChart', {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                data: [0],
                borderWidth: 1
            }]
        },
        options: chartOptions
    });

setInterval(() => {
        // API request
        this.service.getMesswerte().subscribe({
          next: data => {
                this.chartData = data;
                this.fillChartData(this.chartData);
          }
        })
       }, 1000)

 setInterval(() => {
        tempChart.data.datasets[0].data = this.tempArray;
        tempChart.update();
       }, 1000)
}
private fillChartData(chartData: Object)
{
    this.objects = Object.values(chartData);
    for(let row in this.objects)
    {
        this.tempObject = {
            x: this.objects[row].timestamp,
            y: this.objects[row].airtemp
        }

      this.tempArray.push(this.tempObject);
    }
}


问:
Passing CoreData NSManagedObjects to a subview
I want to pass on an NSManagedObject (or an Array of those) from CoreData to a subview.
Is it correct, to pass the NSObject as Binding?

```<code>struct Main View {
  @ObservedObject var item : Item
  // some code
  SubView(tags: $item)
}

struct SubView {
  @Binding var item : Item
  // some code
}
</code>```

or is it better to pass the NSObject directly and declare it as @ObservableObject in the Subview?

```<code>struct Main View {
  @ObservedObject var item : Item
  // some code
  SubView(tags: item)
}

struct SubView {
  @ObservedObject var item : Item
  // some code
}
</code>```

Trying it with the "ObservableObject-Way", I get a problem, when I want to pass a to-many relationship to the Subview.

```<code>struct Main View {
  @ObservedObject var item : Item
  // some code
  SubView(tags: $item.tags)   // tags is an array, containig the related
                              // NSObjects Tag
}

struct SubView {
  @ObservedObject var tags : [Tag]  // Does not compile
  // some code
}
</code>```

@ObservedObject var tags : [Tag] does not compile with the error:

Generic struct 'ObservedObject' requires that '[Tag]' conform to 'ObservableObject.

Tag is a NSManagedObject, how can an Array of NSManagedObjects be passed to the SubView?

Body:
I want to pass on an NSManagedObject (or an Array of those) from CoreData to a subview.
Is it correct, to pass the NSObject as Binding?

struct Main View {
  @ObservedObject var item : Item
  // some code
  SubView(tags: $item)
}

struct SubView {
  @Binding var item : Item
  // some code
}

or is it better to pass the NSObject directly and declare it as @ObservableObject in the Subview?

struct Main View {
  @ObservedObject var item : Item
  // some code
  SubView(tags: item)
}

struct SubView {
  @ObservedObject var item : Item
  // some code
}

Trying it with the "ObservableObject-Way", I get a problem, when I want to pass a to-many relationship to the Subview.

struct Main View {
  @ObservedObject var item : Item
  // some code
  SubView(tags: $item.tags)   // tags is an array, containig the related
                              // NSObjects Tag
}

struct SubView {
  @ObservedObject var tags : [Tag]  // Does not compile
  // some code
}

@ObservedObject var tags : [Tag] does not compile with the error:

Generic struct 'ObservedObject' requires that '[Tag]' conform to 'ObservableObject.

Tag is a NSManagedObject, how can an Array of NSManagedObjects be passed to the SubView?


问:
How to populate a Bootstrap table using variable from Flask?
I have a Bootstrap table in which I need help to know how to populate data. Now is using data-URL to receive data but I would like to get the data from a variable that comes from Flask. I have already converted it as JSON but I don't know how to get both things together. Please, I really appreciate any help.

HTML

```<code><table
   id="table"
   data-toolbar="#toolbar"
   data-search="true"
   data-search-highlight="true"
   data-show-columns-search="true"
   data-show-toggle="true"
   data-show-fullscreen="true"
   data-show-columns="true"
   data-show-columns-toggle-all="true"
   data-detail-view="true"
   data-show-export="true"
   data-export-data-type="all"
   data-click-to-select="false"
   data-detail-formatter="detailFormatter"
   data-minimum-count-columns="2"
   data-show-pagination-switch="true"
   data-pagination="true"
   data-id-field="id"
   data-page-list="[10, 25, 50, 100, all]"
   data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data"
   data-side-pagination="server"
   data-response-handler="responseHandler"
   data-resizable="true"
   data-show-copy-rows="true"
   data-loading-template="loadingTemplate"
   data-advanced-search="true"
   data-filter-control="true"
   data-use-row-attr-func="true"
   data-reorderable-rows="true"
   data-show-refresh="true"
   data-buttons-class="primary">
</table>
</code>```

Javascript

```<code>// Table
let $table = $('#table')
let $remove = $('#remove')
let selections = []

function getIdSelections() {
  return $.map($table.bootstrapTable('getSelections'), function (row) {
    return row.id
  })
}

function responseHandler(res) {
  $.each(res.rows, function (i, row) {
    row.state = $.inArray(row.id, selections) !== -1
  })
  return res
}

function detailFormatter(index, row) {
  var html = []
  $.each(row, function (key, value) {
    html.push('<p><b>' + key + ':</b> ' + value + '</p>')
  })
  return html.join('')
}

$(function () {
  $('#toolbar').find('select').change(function () {
    $table.bootstrapTable('destroy').bootstrapTable({
      exportDataType: $(this).val(),
      exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel', 'pdf'],
      columns: [
        {
          field: 'state',
          checkbox: true,
          visible: $(this).val() === 'selected'
        },
        {
          field: 'id',
          title: 'ID',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        }, {
          field: 'name',
          title: 'Item Name',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        }, {
          field: 'price',
          title: 'Item Price',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        },
        {
          field: '',
          title: 'Item Price2',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        },
        {
          field: 'product',
          title: 'Item Price3',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        }
      ]
    })
  }).trigger('change')
});
</code>```

Body:
I have a Bootstrap table in which I need help to know how to populate data. Now is using data-URL to receive data but I would like to get the data from a variable that comes from Flask. I have already converted it as JSON but I don't know how to get both things together. Please, I really appreciate any help.

HTML

<table
   id="table"
   data-toolbar="#toolbar"
   data-search="true"
   data-search-highlight="true"
   data-show-columns-search="true"
   data-show-toggle="true"
   data-show-fullscreen="true"
   data-show-columns="true"
   data-show-columns-toggle-all="true"
   data-detail-view="true"
   data-show-export="true"
   data-export-data-type="all"
   data-click-to-select="false"
   data-detail-formatter="detailFormatter"
   data-minimum-count-columns="2"
   data-show-pagination-switch="true"
   data-pagination="true"
   data-id-field="id"
   data-page-list="[10, 25, 50, 100, all]"
   data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data"
   data-side-pagination="server"
   data-response-handler="responseHandler"
   data-resizable="true"
   data-show-copy-rows="true"
   data-loading-template="loadingTemplate"
   data-advanced-search="true"
   data-filter-control="true"
   data-use-row-attr-func="true"
   data-reorderable-rows="true"
   data-show-refresh="true"
   data-buttons-class="primary">

Javascript

// Table
let $table = $('#table')
let $remove = $('#remove')
let selections = []

function getIdSelections() {
  return $.map($table.bootstrapTable('getSelections'), function (row) {
    return row.id
  })
}

function responseHandler(res) {
  $.each(res.rows, function (i, row) {
    row.state = $.inArray(row.id, selections) !== -1
  })
  return res
}

function detailFormatter(index, row) {
  var html = []
  $.each(row, function (key, value) {
    html.push('
' + key + ': ' + value + '
')
  })
  return html.join('')
}

$(function () {
  $('#toolbar').find('select').change(function () {
    $table.bootstrapTable('destroy').bootstrapTable({
      exportDataType: $(this).val(),
      exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel', 'pdf'],
      columns: [
        {
          field: 'state',
          checkbox: true,
          visible: $(this).val() === 'selected'
        },
        {
          field: 'id',
          title: 'ID',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        }, {
          field: 'name',
          title: 'Item Name',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        }, {
          field: 'price',
          title: 'Item Price',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        },
        {
          field: '',
          title: 'Item Price2',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        },
        {
          field: 'product',
          title: 'Item Price3',
          sortable: true,
          filterControl: 'input',
          align: 'center',
          valign: 'middle'
        }
      ]
    })
  }).trigger('change')
});


问:
Dropzone.js won't attach file to be sent to upload.php
I'm trying to make a simple drag & drop to upload files with dropzone.js and i can't make it actualy attach the file to the input so i can then send it to my upload.php (Via form action).

I have linked everything and followed the documentation's steps.https://docs.dropzone.dev/

Thanks in advance!

Here is my html:

```<code><form action="/" method="post" target="_blank" class="dropzone" id="myAwesomeDropzone" data plugin="dropzone" data-previews-container="#file-previews"
data-upload-preview-template="#uploadPreviewTemplate">
    <div class="fallback">
        <input name="file" id="files" type="file" multiple />
    </div>

    <div class="dz-message needsclick">
        <i class="h1 text-muted ri-upload-cloud-2-line"></i>
        <h3>Drop files here or click to upload.</h3>
    </div>
</form>

<div class="dropzone-previews mt-3" id="file-previews"></div>
</code>```

Body:
I'm trying to make a simple drag & drop to upload files with dropzone.js and i can't make it actualy attach the file to the input so i can then send it to my upload.php (Via form action).

I have linked everything and followed the documentation's steps.https://docs.dropzone.dev/

Thanks in advance!

Here is my html:

<form action="/" method="post" target="_blank" class="dropzone" id="myAwesomeDropzone" data plugin="dropzone" data-previews-container="#file-previews"
data-upload-preview-template="#uploadPreviewTemplate">

        <input name="file" id="files" type="file" multiple />

Drop files here or click to upload.

</form>


问:
How to make Scrollable List of new page when I click Drop down Snipper in Kotlin
I want to make List for selecting region when user register on app.

So What I want to implement is if user click drop down menu

I want make it go another new page, not list dropped down below.

New page will have Scrollable list.

And I click this Scrollable list, I need to get this data.

So I guess I need to use RecyclerView to make Scrollable list of new page.

And Each component of RecyclerView should be button. (is that right?)

1) But what I don't know is how to make Dropdown Snipper as Clickable Button.

Snipper can't use setOnClickListener.

Should I make Button to have Text and Arrow manually?

In React Native It had some library for this purpose.

2) Is that correct Kotlin doesn't provide such library?


问:
Error when sink DataStream to JDBC in PyFlink after using map function
My Code:

```<code>from pyflink.datastream.connectors.jdbc import JdbcSink, JdbcExecutionOptions, JdbcConnectionOptions
from pyflink.common.typeinfo import Types
from pyflink.datastream import StreamExecutionEnvironment

JDBC_JAR_PATH = "file:///Users/jar_files/postgresql-42.5.0.jar"

env = StreamExecutionEnvironment.get_execution_environment()

env.add_jars(JDBC_JAR_PATH)
env.set_parallelism(1)

type_info = Types.ROW([Types.INT(), Types.STRING(), Types.STRING(), Types.INT()])
ds = env.from_collection(
    [(101, "Stream Processing with Apache Flink", "Fabian Hueske, Vasiliki Kalavri", 2019),
     (102, "Streaming Systems", "Tyler Akidau, Slava Chernyak, Reuven Lax", 2018),
     (103, "Designing Data-Intensive Applications", "Martin Kleppmann", 2017),
     (104, "Kafka: The Definitive Guide", "Gwen Shapira, Neha Narkhede, Todd Palino", 2017)
     ], type_info=type_info).name('Source')

def change_id(data):
    data[0] = data[0] + 100
    return data

ds1 = ds.map(change_id)

ds2 = ds1.add_sink(
    JdbcSink.sink(
        "insert into books(id, title, authors, year) values (?, ?, ?, ?)",
        type_info,
        JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
            .with_url('jdbc:postgresql://localhost:5432/nhan_su')
            .with_driver_name('org.postgresql.Driver')
            .with_user_name('psql')
            .with_password('psql')
            .build(),
        JdbcExecutionOptions.builder()
            .with_batch_interval_ms(1000)
            .with_batch_size(200)
            .with_max_retries(5)
            .build()
    ))
env.execute()
</code>```

Error:

Caused by: java.lang.ClassCastException: class [B cannot be cast to class org.apache.flink.types.Row ([B is in module java.base of loader 'bootstrap'; org.apache.flink.types.Row is in unnamed module of loader 'app') at org.apache.flink.connector.jdbc.internal.executor.SimpleBatchStatementExecutor.executeBatch(SimpleBatchStatementExecutor.java:70)

How to Sink DataStream to JDBC Sink after Using map function in PyFlink?

I tried to change the return type of map function to tuple, but the issue is still there.

Body:
My Code:

from pyflink.datastream.connectors.jdbc import JdbcSink, JdbcExecutionOptions, JdbcConnectionOptions
from pyflink.common.typeinfo import Types
from pyflink.datastream import StreamExecutionEnvironment

JDBC_JAR_PATH = "file:///Users/jar_files/postgresql-42.5.0.jar"

env = StreamExecutionEnvironment.get_execution_environment()

env.add_jars(JDBC_JAR_PATH)
env.set_parallelism(1)

type_info = Types.ROW([Types.INT(), Types.STRING(), Types.STRING(), Types.INT()])
ds = env.from_collection(
    [(101, "Stream Processing with Apache Flink", "Fabian Hueske, Vasiliki Kalavri", 2019),
     (102, "Streaming Systems", "Tyler Akidau, Slava Chernyak, Reuven Lax", 2018),
     (103, "Designing Data-Intensive Applications", "Martin Kleppmann", 2017),
     (104, "Kafka: The Definitive Guide", "Gwen Shapira, Neha Narkhede, Todd Palino", 2017)
     ], type_info=type_info).name('Source')

def change_id(data):
    data[0] = data[0] + 100
    return data

ds1 = ds.map(change_id)

ds2 = ds1.add_sink(
    JdbcSink.sink(
        "insert into books(id, title, authors, year) values (?, ?, ?, ?)",
        type_info,
        JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
            .with_url('jdbc:postgresql://localhost:5432/nhan_su')
            .with_driver_name('org.postgresql.Driver')
            .with_user_name('psql')
            .with_password('psql')
            .build(),
        JdbcExecutionOptions.builder()
            .with_batch_interval_ms(1000)
            .with_batch_size(200)
            .with_max_retries(5)
            .build()
    ))
env.execute()

Error:

Caused by: java.lang.ClassCastException: class [B cannot be cast to class org.apache.flink.types.Row ([B is in module java.base of loader 'bootstrap'; org.apache.flink.types.Row is in unnamed module of loader 'app') at org.apache.flink.connector.jdbc.internal.executor.SimpleBatchStatementExecutor.executeBatch(SimpleBatchStatementExecutor.java:70)

How to Sink DataStream to JDBC Sink after Using map function in PyFlink?

I tried to change the return type of map function to tuple, but the issue is still there.


问:
Can't authenticate using REST POST method
Basically i'm new to groovy, and i'm trying to use it to add a device to "netbox" using API, i tried some GET requests that needed authentication and they worked fine, but i couldn't make any POST request work, i'm always getting 403 no matter what method i try to authenticate Basic using creds or using API Token.

Here's the code i wrote for the POST request :

```<code>def url = "http://192.168.12.89:8000/api/dcim/devices"
def connection = url.toURL().openConnection()
def message = '{"name":"R4","device_type":"1","device_role":"1","site":"1"}'
connection.setRequestMethod("POST")
connection.setDoOutput(true)
connection.setDoInput(true)
connection.addRequestProperty("Accept", "application/json;charset=UTF-8")
connection.addRequestProperty("Content-Type", "application/json")

//def auth = "admin:admin".bytes.encodeBase64()
//connection.setRequestProperty("Authorization", "Basic ${auth}")
connection.setRequestProperty("Authorization", "Token 63091d94b00d40e9e0a4e1286e181c09deca6e89")

connection.getOutputStream().write(message.getBytes("UTF-8"))

def responseCode = connection.getResponseCode()
InputStream response = null
println "${responseCode}"
if (responseCode != 200) {
    response = connection.getErrorStream()
} else {
    response = connection.getInputStream()
}

def responseBody = response?.text
response?.close()
println responseBody

</code>```

My API key works fine with the get method and it has the write permissions included, also tried a python POST request works perfectly fine, so i guess the problem is in my groovy coding.

I hope i can get a bit of help cause i've been trying for two days :x
Thank you :x

Body:
Basically i'm new to groovy, and i'm trying to use it to add a device to "netbox" using API, i tried some GET requests that needed authentication and they worked fine, but i couldn't make any POST request work, i'm always getting 403 no matter what method i try to authenticate Basic using creds or using API Token.

Here's the code i wrote for the POST request :

def url = "http://192.168.12.89:8000/api/dcim/devices"
def connection = url.toURL().openConnection()
def message = '{"name":"R4","device_type":"1","device_role":"1","site":"1"}'
connection.setRequestMethod("POST")
connection.setDoOutput(true)
connection.setDoInput(true)
connection.addRequestProperty("Accept", "application/json;charset=UTF-8")
connection.addRequestProperty("Content-Type", "application/json")

//def auth = "admin:admin".bytes.encodeBase64()
//connection.setRequestProperty("Authorization", "Basic ${auth}")
connection.setRequestProperty("Authorization", "Token 63091d94b00d40e9e0a4e1286e181c09deca6e89")

connection.getOutputStream().write(message.getBytes("UTF-8"))

def responseCode = connection.getResponseCode()
InputStream response = null
println "${responseCode}"
if (responseCode != 200) {
    response = connection.getErrorStream()
} else {
    response = connection.getInputStream()
}

def responseBody = response?.text
response?.close()
println responseBody

My API key works fine with the get method and it has the write permissions included, also tried a python POST request works perfectly fine, so i guess the problem is in my groovy coding.

I hope i can get a bit of help cause i've been trying for two days :x
Thank you :x


问:
StoreContext.GetAppLicenseAsync().AddOnLicenses sometimes returns an empty list when the user has a license
I have an XBOX only app in the Microsoft Store that has been up for a while. The app has an add-on.

I use a very simple code to get the list of licenses in order to check if the user has add-on.
See below.

StoreAppLicense appLicense = await StoreContext.GetAppLicenseAsync();

var licenses = appLicense.AddOnLicenses.Select(item=> item.Value).ToList();

//Here I just save this in my log to see what is in the list
LogInfo("licenses: " + string.Join(',', licenses.Select(l => l.SkuStoreId).ToArray()));

```

Ok, so most of the time this code works fine. But there can be instances where the StoreAppLicense returns an empty list, even when  the user HAS the license.

This has been a problem that has happened sometimes since I published the add-on, but was always fixed by reinstalling the app. Lately, even after a reinstall; the issue reappears.

What is worst, this even happened to me two days ago. I reinstalled the app and it worked fine; but after restarting the app it happened again. Then after some hours when I came back home it "solved itself".

I also have the suspicion that sometimes the StoreContext.GetAppLicenseAsync() method never returns and that causes the app to "hang".

Needless to say, customers get upset at me and give me bad reviews for something that is beyond my control.

What should I do in this situation? Can you even trust the StoreContext library?
Has someone seen this happening before?

Body:
I have an XBOX only app in the Microsoft Store that has been up for a while. The app has an add-on.

I use a very simple code to get the list of licenses in order to check if the user has add-on.
See below.

StoreAppLicense appLicense = await StoreContext.GetAppLicenseAsync();

var licenses = appLicense.AddOnLicenses.Select(item=> item.Value).ToList();

//Here I just save this in my log to see what is in the list
LogInfo("licenses: " + string.Join(',', licenses.Select(l => l.SkuStoreId).ToArray()));

Ok, so most of the time this code works fine. But there can be instances where the StoreAppLicense returns an empty list, even when  the user HAS the license.

This has been a problem that has happened sometimes since I published the add-on, but was always fixed by reinstalling the app. Lately, even after a reinstall; the issue reappears.

What is worst, this even happened to me two days ago. I reinstalled the app and it worked fine; but after restarting the app it happened again. Then after some hours when I came back home it "solved itself".

I also have the suspicion that sometimes the StoreContext.GetAppLicenseAsync() method never returns and that causes the app to "hang".

Needless to say, customers get upset at me and give me bad reviews for something that is beyond my control.

What should I do in this situation? Can you even trust the StoreContext library?
Has someone seen this happening before?