问:
simplify the cubic spline with fewer points and few segments
I follow the idea in Does the order of points matter in spline interpolation in MatLab? to fit the given points into a smooth cubic spline. The original point set contains 27 x values and 27 y values and thus gives me 26 pieces of cubic polynomials. I am trying significantly reduce the number of segments but more or less keep the fitting curve smooth (at least each of the reduced segments should connect at the joints). I am looking up a solution but has no luck so I am trying the following not-very-good algorithm.

I try to fit the curve from the very first (SI) to the last segment (EI) to a new cubic polynomial

If the error of the new fit in 1) is acceptable, I will accept it as a new segment; if the error is no good, I move the EI backward by one and fit it again.

Repeat 2) until I got a new good fit from SI to EI.

Move SI to EI and EI to the very last segment and repeat 1) to 3).

Here is the code

```<code>clear all
clc
close all
x = [ -0.8103   -0.6740   -0.5599   -0.5120   -0.4936   -0.4530   -0.4494   -0.4494   -0.4494   -0.4751 -0.5157   -0.6409   -0.6667   -0.7772   -0.7772   -0.6998   -0.5304   -0.4641   -0.2431    0.0110 0.1142    0.1989    0.2836    0.3499    0.3499    0.4125    0.5267];
y = [0.8621    0.8388    0.7640    0.7547    0.7266    0.6472    0.5911    0.5257    0.4696    0.3668 0.2967    0.2360    0.2220    0.0724   -0.1472   -0.1939   -0.2874   -0.4743   -0.5304   -0.5257 -0.4930   -0.3668   -0.2967   -0.2593   -0.2593   -0.2827   -0.3715];

nx = [1:numel(x)];
ny = [1:numel(y)];

f3x = fit(nx',x','smoothingspline','Normalize','on', 'SmoothingParam', 0.985);
f3y = fit(ny',y','smoothingspline','Normalize','on', 'SmoothingParam', 0.985);
nxp = 0:0.001:max(nx)+1;
nyp = 0:0.001:max(ny)+1;
plot(f3x(nxp),f3y(nyp), 'y', 'linewidth', 5);
f3x.p
n = numel(f3x.p.breaks);
SI = 1;
EI = n-1;
fx = fittype('d + c*x + b*x^2 + a*x^3'); % use for refit
fy = fittype('d + c*x + b*x^2 + a*x^3'); % use for refit
hold on;

while (SI<EI) && (EI>1) && (EI<n)
    X = [];
    Y = [];
    for i=SI:EI
        xx = f3x.p.breaks(i):0.01:f3x.p.breaks(i+1);
        xs = xx-f3x.p.breaks(i);
        a = f3x.p.coefs(i,1);
        b = f3x.p.coefs(i,2);
        c = f3x.p.coefs(i,3);
        d = f3x.p.coefs(i,4);
        X = [X (d + c*xs + b*xs.^2 + a*xs.^3)];

        yy = f3y.p.breaks(i):0.01:f3y.p.breaks(i+1);
        ys = yy-f3y.p.breaks(i);
        a = f3y.p.coefs(i,1);
        b = f3y.p.coefs(i,2);
        c = f3y.p.coefs(i,3);
        d = f3y.p.coefs(i,4);
        Y = [Y (d + c*ys + b*ys.^2 + a*ys.^3)];
    end

    xx = linspace(f3x.p.breaks(SI), f3x.p.breaks(EI), numel(X));
    [fit1,gof1,fitinfo1] = fit(xx',X',fx,'StartPoint', f3x.p.coefs(SI,:));
    yy = linspace(f3y.p.breaks(SI), f3y.p.breaks(EI), numel(Y));
    [fit2,gof2,fitinfo2] = fit(yy',Y',fy,'StartPoint', f3y.p.coefs(SI,:));
    r = (gof1.rsquare + gof2.rsquare)/2;
    if (r>0.9995) % if the error is ok, accept it
        SI = EI;
        EI = n-1;
        xfit = fit1(xx);
        yfit = fit2(yy);
        plot(xfit, yfit, '-', 'linewidth', 2.5);
    else
        EI = EI - 1;
    end
end
</code>```

As you will see in the result (the thick yellow line is the original spline), I do find several new fits ROUGHLY do the work but I still want to know any way to fix the following issues

the endpoint of the last segment does not connect to the first point of the current segment.

is it possible to pick a few points from each of the new segments, such that I could use the new points to fit into a cubic spline that carries 5 segments connected smoothly? I am trying to pick the endpoints (P1, P2, P3, P4, P5, P6) of each segment and fit it as a smooth spline but end up with something totally different. Any idea?

Body:
I follow the idea in Does the order of points matter in spline interpolation in MatLab? to fit the given points into a smooth cubic spline. The original point set contains 27 x values and 27 y values and thus gives me 26 pieces of cubic polynomials. I am trying significantly reduce the number of segments but more or less keep the fitting curve smooth (at least each of the reduced segments should connect at the joints). I am looking up a solution but has no luck so I am trying the following not-very-good algorithm.

I try to fit the curve from the very first (SI) to the last segment (EI) to a new cubic polynomial

If the error of the new fit in 1) is acceptable, I will accept it as a new segment; if the error is no good, I move the EI backward by one and fit it again.

Repeat 2) until I got a new good fit from SI to EI.

Move SI to EI and EI to the very last segment and repeat 1) to 3).

Here is the code

clear all
clc
close all
x = [ -0.8103   -0.6740   -0.5599   -0.5120   -0.4936   -0.4530   -0.4494   -0.4494   -0.4494   -0.4751 -0.5157   -0.6409   -0.6667   -0.7772   -0.7772   -0.6998   -0.5304   -0.4641   -0.2431    0.0110 0.1142    0.1989    0.2836    0.3499    0.3499    0.4125    0.5267];
y = [0.8621    0.8388    0.7640    0.7547    0.7266    0.6472    0.5911    0.5257    0.4696    0.3668 0.2967    0.2360    0.2220    0.0724   -0.1472   -0.1939   -0.2874   -0.4743   -0.5304   -0.5257 -0.4930   -0.3668   -0.2967   -0.2593   -0.2593   -0.2827   -0.3715];

nx = [1:numel(x)];
ny = [1:numel(y)];

f3x = fit(nx',x','smoothingspline','Normalize','on', 'SmoothingParam', 0.985);
f3y = fit(ny',y','smoothingspline','Normalize','on', 'SmoothingParam', 0.985);
nxp = 0:0.001:max(nx)+1;
nyp = 0:0.001:max(ny)+1;
plot(f3x(nxp),f3y(nyp), 'y', 'linewidth', 5);
f3x.p
n = numel(f3x.p.breaks);
SI = 1;
EI = n-1;
fx = fittype('d + c*x + b*x^2 + a*x^3'); % use for refit
fy = fittype('d + c*x + b*x^2 + a*x^3'); % use for refit
hold on;

while (SI<EI) && (EI>1) && (EI<n)
    X = [];
    Y = [];
    for i=SI:EI
        xx = f3x.p.breaks(i):0.01:f3x.p.breaks(i+1);
        xs = xx-f3x.p.breaks(i);
        a = f3x.p.coefs(i,1);
        b = f3x.p.coefs(i,2);
        c = f3x.p.coefs(i,3);
        d = f3x.p.coefs(i,4);
        X = [X (d + c*xs + b*xs.^2 + a*xs.^3)];

        yy = f3y.p.breaks(i):0.01:f3y.p.breaks(i+1);
        ys = yy-f3y.p.breaks(i);
        a = f3y.p.coefs(i,1);
        b = f3y.p.coefs(i,2);
        c = f3y.p.coefs(i,3);
        d = f3y.p.coefs(i,4);
        Y = [Y (d + c*ys + b*ys.^2 + a*ys.^3)];
    end

    xx = linspace(f3x.p.breaks(SI), f3x.p.breaks(EI), numel(X));
    [fit1,gof1,fitinfo1] = fit(xx',X',fx,'StartPoint', f3x.p.coefs(SI,:));
    yy = linspace(f3y.p.breaks(SI), f3y.p.breaks(EI), numel(Y));
    [fit2,gof2,fitinfo2] = fit(yy',Y',fy,'StartPoint', f3y.p.coefs(SI,:));
    r = (gof1.rsquare + gof2.rsquare)/2;
    if (r>0.9995) % if the error is ok, accept it
        SI = EI;
        EI = n-1;
        xfit = fit1(xx);
        yfit = fit2(yy);
        plot(xfit, yfit, '-', 'linewidth', 2.5);
    else
        EI = EI - 1;
    end
end

As you will see in the result (the thick yellow line is the original spline), I do find several new fits ROUGHLY do the work but I still want to know any way to fix the following issues

the endpoint of the last segment does not connect to the first point of the current segment.

is it possible to pick a few points from each of the new segments, such that I could use the new points to fit into a cubic spline that carries 5 segments connected smoothly? I am trying to pick the endpoints (P1, P2, P3, P4, P5, P6) of each segment and fit it as a smooth spline but end up with something totally different. Any idea?


来源: stackexchange

问:
Navigation Link Runtime Error in building Countdown Timer
```<code>struct SlideFiveView: View {

    var time: Int

    @StateObject private var vm = ViewModel()
    private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    private let width: Double = 250

    var body: some View {
        VStack {
            SlideOne()
            Text("\(vm.time)")
                .font(.system(size: 70, weight: .medium, design: .rounded))
                .padding()
                .frame(width: width)
                .background(.thinMaterial)
                .cornerRadius(20)
                overlay(RoundedRectangle(cornerRadius: 20)
                    .stroke(Color.gray, lineWidth: 4))
                //.alert("Timer done!", isPresented: $vm.showingAlert)
        }

        HStack(spacing: 50) {
            Button("Start") {
                vm.start(minutes: Float(time))
            }
        }

        .onReceive(timer) { _ in
            vm.updateCountdown()
        }
    }
}
</code>```

I'm attempting create a timer in a View Structure, where the variable, time is passed from a percious View and becomes the set value for the starting time, and a navigation link is being used to get to the above view, but a Thread 1: EXC_BAD_ACCESS (code=2, address=0x16b0bbfdc), error occurs and the app crashes when the navigation link is pressed.

ContentLicense: CC BY-SA 4.0

Body:
struct SlideFiveView: View {

    var time: Int

    @StateObject private var vm = ViewModel()
    private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    private let width: Double = 250

    var body: some View {
        VStack {
            SlideOne()
            Text("\(vm.time)")
                .font(.system(size: 70, weight: .medium, design: .rounded))
                .padding()
                .frame(width: width)
                .background(.thinMaterial)
                .cornerRadius(20)
                overlay(RoundedRectangle(cornerRadius: 20)
                    .stroke(Color.gray, lineWidth: 4))
                //.alert("Timer done!", isPresented: $vm.showingAlert)
        }

        HStack(spacing: 50) {
            Button("Start") {
                vm.start(minutes: Float(time))
            }
        }

        .onReceive(timer) { _ in
            vm.updateCountdown()
        }
    }
}

I'm attempting create a timer in a View Structure, where the variable, time is passed from a percious View and becomes the set value for the starting time, and a navigation link is being used to get to the above view, but a Thread 1: EXC_BAD_ACCESS (code=2, address=0x16b0bbfdc), error occurs and the app crashes when the navigation link is pressed.


问:
Measure queue call effectiveness
Looking for a formula to measure effectiveness on the queue.  In order to assess how many agents we require, we assign queue schedules for our agents.  During the queue schedule times, agents are required to be on the queue, however if they need to call outbound, or receive inbound direct calls they are welcome to do so.  This creates a challenge as the effectiveness rate is based on many factors.  I wanted to see if anyone could help me with a formula to determine how effective an agent is on the queue.

Sample:
Agent A:
Schedule: 1:00PM to 2:00PM, 3:00 to 5:00PM
Agent is available on the queue from 1:19 to 1:38, 1:48 to 1:56, 2:09 to 3:32, 4:39 to 4:58
During the available times, the agent is also receiving inbound direct and making calls outbound.  For example for the above agent, the agent spends 19 minutes on inbound direct calls, 33 minutes on outbound calls, 42 minutes on queue talk time.

How can I determine if the agent is effective on the queue or are they spending too much time on "other" activities such as outbound and inbound direct calls and what would the formula look like?

How can I determine if the agent is effective on the queue or are they spending too much time on "other" activities such as outbound and inbound direct calls and what would the formula look like?

It is a bit more complex than the following:

([Queue Available Time] - [Queue Talk Time + Outbound Talk Time + Inbound Direct Time]) / [Queue Schedule Time]

The agent has multiple lines (2 at most) so they might contain more time than scheduled as they could be on a queue call call and on an outbound call. They do not receive queue calls while they are on a line with an outbound call, direct call, or queue call.

Title: Measure queue call effectiveness


问:
AWS CDk rds.ParameterGroup parameters type { [string]: string }
Hi i'm using the aws cdk in type script to create rds Databases.  I'm new at typescript.  To create a parameter group for my rds database I use :

```<code> const dbParameterGroup = new rds.ParameterGroup(this, 'ParameterGroup', {       engine: rds.DatabaseInstanceEngine.mysql({         version: engineVersion,       }),       parameters: { time_zone: 'US/Eastern',       binlog_cache_size: '204800' },     });
</code>```

It works but now I want this part : { time_zone: 'US/Eastern', binlog_cache_size: '204800' }
to be a variable so user can put the parameter he wants.  In the doc the type of the parameters properties is { [string]: string } :
https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-rds.ParameterGroupProps.html

I tried different things but I can't make it work.  Any help appreciated

I want a way to declare a variable with { [string]: string } and use it.

Body:
Hi i'm using the aws cdk in type script to create rds Databases.  I'm new at typescript.  To create a parameter group for my rds database I use :

 const dbParameterGroup = new rds.ParameterGroup(this, 'ParameterGroup', {       engine: rds.DatabaseInstanceEngine.mysql({         version: engineVersion,       }),       parameters: { time_zone: 'US/Eastern',       binlog_cache_size: '204800' },     });

It works but now I want this part : { time_zone: 'US/Eastern', binlog_cache_size: '204800' }
to be a variable so user can put the parameter he wants.  In the doc the type of the parameters properties is { [string]: string } :
https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-rds.ParameterGroupProps.html

I tried different things but I can't make it work.  Any help appreciated

I want a way to declare a variable with { [string]: string } and use it.


问:
Get pixel colors of a meshtriangle from its texture
Using Trimesh library (https://github.com/mikedh/trimesh),I'm trying to get the pixel colors of a mesh triangle from the texture loaded with the 3D mesh (.obj + .png +.mtl). In other words, given a vertex #0, I want to map the incident faces to the loaded texture and recover the pixels inside the mapped faces. For this I load the textured 3D mesh as :

```<code>    im = Image.open("cow_texture.png")
    im_arr=np.array(im)
    mesh= trimesh.load('cow.obj',process=False, maintain_order=False)
    tex = trimesh.visual.TextureVisuals(image=im)
    mesh.visual.texture = tex
</code>```

The problem is when try to get the incident faces of a vertex (let's take vertex n° 0), the function returns me a wrong number of incident faces (4 instead of 6(please see image below, vertex #0 in red)):

```<code>    mesh_false.vertex_faces[0] #prints array([3009, 3008, 2960,   -1,   -1,   -1,   -1,   -1])
</code>```

However, note that the call of the function trimesh.load is made with the parameter maintain_order=False . If the load is made with maintain_order=True, the number of incident faces is good, however the uv coordinates of adjacent neighboring vertices aren't good (they are far while they should be near).

How can I retrieve the the number right number of incident faces (or right number of neighboring adjacent vertices) when load a textured 3D mesh?

I tried to load a textured 3D mesh and find incident faces of a vertex #0.

Body:
Using Trimesh library (https://github.com/mikedh/trimesh),I'm trying to get the pixel colors of a mesh triangle from the texture loaded with the 3D mesh (.obj + .png +.mtl). In other words, given a vertex #0, I want to map the incident faces to the loaded texture and recover the pixels inside the mapped faces. For this I load the textured 3D mesh as :

    im = Image.open("cow_texture.png")
    im_arr=np.array(im)
    mesh= trimesh.load('cow.obj',process=False, maintain_order=False)
    tex = trimesh.visual.TextureVisuals(image=im)
    mesh.visual.texture = tex

The problem is when try to get the incident faces of a vertex (let's take vertex n° 0), the function returns me a wrong number of incident faces (4 instead of 6(please see image below, vertex #0 in red)):

    mesh_false.vertex_faces[0] #prints array([3009, 3008, 2960,   -1,   -1,   -1,   -1,   -1])

However, note that the call of the function trimesh.load is made with the parameter maintain_order=False . If the load is made with maintain_order=True, the number of incident faces is good, however the uv coordinates of adjacent neighboring vertices aren't good (they are far while they should be near).

How can I retrieve the the number right number of incident faces (or right number of neighboring adjacent vertices) when load a textured 3D mesh?

I tried to load a textured 3D mesh and find incident faces of a vertex #0.


问:
Method template specialization
Assume I have the following layout of my project where UtilsLib and DataLib are statically linked libraries:

```<code>// UtilsLib/SomeToolClass.h

class SomeToolClass
{

    template<typename Object>
    Object* doSomething()
    {
        // ...
        return new Object();
    }

    template<typename Object>
    void doSomethingElse()
    {
        // just here to show this class does a lot more than just doSomething()
    }

};

// DataLib/Thing.h

class Thing
{
    // ...
};

// MyProgram/main.cpp
#include "UtilsLib/SomeToolClass.h"
#include "DataLib/Thing.h"

int main()
{
    SomeToolClass<Thing> tool;
    tool.doSomething();

    SomeToolClass<AnotherThing> tool2;
    tool2.doSomething();
}
</code>```

What I want to do is have a specialization for SomeToolClass<Thing>::doSomething. For example, if the method was virtual, I could just create a class with SomeToolClass<Thing> as the base class and override the method. For the purposes of this question, please assume that is not an option. I'm also stuck with the library layout.

Can I define a template specialization in one library for a template class defined in another? How can I do this?

Title: Method template specialization

Body:
Assume I have the following layout of my project where UtilsLib and DataLib are statically linked libraries:

// UtilsLib/SomeToolClass.h

class SomeToolClass
{

    template<typename Object>
    Object* doSomething()
    {
        // ...
        return new Object();
    }

    template<typename Object>
    void doSomethingElse()
    {
        // just here to show this class does a lot more than just doSomething()
    }

};

// DataLib/Thing.h

class Thing
{
    // ...
};

// MyProgram/main.cpp
#include "UtilsLib/SomeToolClass.h"
#include "DataLib/Thing.h"

int main()
{
    SomeToolClass<Thing> tool;
    tool.doSomething();

    SomeToolClass<AnotherThing> tool2;
    tool2.doSomething();
}

What I want to do is have a specialization for SomeToolClass<Thing>::doSomething. For example, if the method was virtual, I could just create a class with SomeToolClass<Thing> as the base class and override the method. For the purposes of this question, please assume that is not an option. I'm also stuck with the library layout.

Can I define a template specialization in one library for a template class defined in another? How can I do this?


问:
gcp BigQuery for Dimensional Star Schema Data Warehouse build performance
Google states that BigQuery is for DWH'es that have append by and large and fewer updates.

For a star schema based DWH with optional fact table attributes that could be updated and dimensions that are historized, then is this a goer, or do we need the Redshift approach of small staging tables generated with the new or updated data that needs to be part of an UPSERT query?

Is this type of approach possible in BigQuery using Spark?

```<code>spark.sql(""" MERGE INTO CUSTOMERS_AT_REST
          USING CUST_DELTA
          ON CUSTOMERS_AT_REST.col_key = CUST_DELTA.col_key
            WHEN MATCHED THEN
              UPDATE SET *
            WHEN NOT MATCHED THEN
              INSERT *
      """)
</code>```

It is all good on delta on gcp cloud storage.

Body:
Google states that BigQuery is for DWH'es that have append by and large and fewer updates.

For a star schema based DWH with optional fact table attributes that could be updated and dimensions that are historized, then is this a goer, or do we need the Redshift approach of small staging tables generated with the new or updated data that needs to be part of an UPSERT query?

Is this type of approach possible in BigQuery using Spark?

spark.sql(""" MERGE INTO CUSTOMERS_AT_REST
          USING CUST_DELTA
          ON CUSTOMERS_AT_REST.col_key = CUST_DELTA.col_key
            WHEN MATCHED THEN
              UPDATE SET *
            WHEN NOT MATCHED THEN
              INSERT *
      """)

It is all good on delta on gcp cloud storage.


问:
How to edit headers in froala
how to edit request headers in froala

I know how to set request headers, but how do I change them later. For example, when you refresh an access token?

Title: How to edit headers in froala


问:
Python Compare datatype of a data file with metadata file
I am trying to compare datatype of all the columns in a CSV file vs a metadata json file.

Metadata json file contains datatype of all the columns of the csv file.

example: if customer_name in the json file = CHAR, I want to check the datatype of customer_name flied in csv is CHAR.

I tried using pandas to identify datatype of each CSV columns and compare against json file. but sometime pandas identifies datatype differently. Example: Customer_phone field is CHAR in json file, but panda identifies it as INTEGE. So, is there any better way to do this comparision in python?

Metadata json contains information like below :

```<code>{
   "DataType": {
    "customer_name": "CHAR",
    "customer_id": "INTEGER",
    "customer_address": "CHAR",
    "customer_phone": "CHAR"
    }
}
</code>```

CSV file data contains:

```<code>customer_name|customer_id|customer_address|customer_phone
abc|12345|abc street|0001234567
</code>```

Here is the function I have written:

def check_datatype(df, meta_dict):

```<code>try:

    datatype_issue = False

    file_datatype = df.dtypes.to_dict()

    # create compare keys from metadata file

    compare_keys = [k for k, v in meta_dict['DataType'].items()]

        for key in compare_keys:

            if file_datatype[key] == 'int64':

                file_datatype[key] = 'integer'.upper()

            if file_datatype[key] == 'object':

                file_datatype[key] = 'char'.upper()

            if file_datatype[key] == 'float64':

                file_datatype[key] = 'decimal'.upper()

        # check if the metadata data type matches with file column datatypes

            if file_datatype[key] == meta_dict['DataType'][key].lower():

            else:

                datatype_issue = True

            if not datatype_issue:

                print(f"No datatype issue found")

        return datatype_issue

except Exception as e:

    print(e)
</code>```

Body:
I am trying to compare datatype of all the columns in a CSV file vs a metadata json file.

Metadata json file contains datatype of all the columns of the csv file.

example: if customer_name in the json file = CHAR, I want to check the datatype of customer_name flied in csv is CHAR.

I tried using pandas to identify datatype of each CSV columns and compare against json file. but sometime pandas identifies datatype differently. Example: Customer_phone field is CHAR in json file, but panda identifies it as INTEGE. So, is there any better way to do this comparision in python?

Metadata json contains information like below :

{
   "DataType": {
    "customer_name": "CHAR",
    "customer_id": "INTEGER",
    "customer_address": "CHAR",
    "customer_phone": "CHAR"
    }
}

CSV file data contains:

customer_name|customer_id|customer_address|customer_phone
abc|12345|abc street|0001234567

Here is the function I have written:

def check_datatype(df, meta_dict):

try:

    datatype_issue = False

    file_datatype = df.dtypes.to_dict()

    # create compare keys from metadata file

    compare_keys = [k for k, v in meta_dict['DataType'].items()]

        for key in compare_keys:

            if file_datatype[key] == 'int64':

                file_datatype[key] = 'integer'.upper()

            if file_datatype[key] == 'object':

                file_datatype[key] = 'char'.upper()

            if file_datatype[key] == 'float64':

                file_datatype[key] = 'decimal'.upper()

        # check if the metadata data type matches with file column datatypes

            if file_datatype[key] == meta_dict['DataType'][key].lower():

            else:

                datatype_issue = True

            if not datatype_issue:

                print(f"No datatype issue found")

        return datatype_issue

except Exception as e:

    print(e)


问:
How to access nested data with spaces and quotes in Datatable?
I exported some QGIS data and I see one field was parsed incorrectly with a space.  Here it is a partial list from console.log();

```<code>properties:
    aa_lifts_count: 6
    aa_lifts_length: 3526.712152733529
    aa_pistes_count: 9
    "aa_pistes_length ": 4269.831629811177
    [snip]
</code>```

As you can see "aa_pistes_length " has quotes and a trailing space.  I do not know how to access this data in datatables.  For instance, to access aa_lift_length I do the following;

```<code>    {
        data: "properties.aa_lifts_length",
        defaultContent: "<i>Not set</i>",
        render: function ( data, type, row ) {
                    return (data/1000).toFixed(2);
                },
    },
</code>```

Based on this comment, I have tried;

```<code>    {
        data: 'properties.aa_pistes_length ', // added trailing space.
                                              // also tried, '"properties.aa_pistes_length "'
        defaultContent: "<i>Not set</i>",
        render: function ( data, type, row ) {
                    return (data/1000).toFixed(2);
                },
    },
</code>```

But I am unable to access the data.  How do I access it please?

Body:
I exported some QGIS data and I see one field was parsed incorrectly with a space.  Here it is a partial list from console.log();

properties:
    aa_lifts_count: 6
    aa_lifts_length: 3526.712152733529
    aa_pistes_count: 9
    "aa_pistes_length ": 4269.831629811177
    [snip]

As you can see "aa_pistes_length " has quotes and a trailing space.  I do not know how to access this data in datatables.  For instance, to access aa_lift_length I do the following;

    {
        data: "properties.aa_lifts_length",
        defaultContent: "Not set",
        render: function ( data, type, row ) {
                    return (data/1000).toFixed(2);
                },
    },

Based on this comment, I have tried;

    {
        data: 'properties.aa_pistes_length ', // added trailing space.
                                              // also tried, '"properties.aa_pistes_length "'
        defaultContent: "Not set",
        render: function ( data, type, row ) {
                    return (data/1000).toFixed(2);
                },
    },

But I am unable to access the data.  How do I access it please?


问:
Where Do I get Certificate For Heroku Wildcard Domain?
I am building an app and I want to use a wildcard domain (e.g. *.domain.com). In order to add this domain to Heroku, I need to obtain a wildcard SSL certificate and import it manually to Heroku. I am using Cloudflare as my domain provider. Where can I obtain a wildcard SSL certificate for this purpose, and how do I go about importing it to Heroku?


问:
Install vkt in Ubuntu
I would like to install Paraview in my laptop with Ubuntu 18.04.6 LTS. I'm following this post to install vkt 8.2.0 in Ubuntu 18.04 (https://discourse.vtk.org/t/installing-vtk-in-ubuntu-18-04/2147/4). When I use

```<code>sudo cmake -DCMAKE_INSTALL_PREFIX=$HOME/vtk-inst \
-DCMAKE_INSTALL_RPATH=$HOME/vtk-inst \
-DVTK_Group_Qt=ON \
-DVTK_QT_VERSION=5 \
-DVTK_Group_Imaging=ON \
-DVTK_Group_Views=ON \
-DModule_vtkRenderingFreeTypeFontConfig=ON \
-DVTK_WRAP_PYTHON=ON \
-DVTK_PYTHON_VERSION=3 \
-DPYTHON_EXECUTABLE=/usr/bin/python3 \
-DPYTHON_INCLUDE_DIR=/usr/include/python3.6 \
-DPYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.6m.so \
-DBUILD_TESTING=OFF \
-DVTK_USE_SYSTEM_LIBRARIES=ON \
-DVTK_USE_SYSTEM_LIBPROJ4=OFF \
-DVTK_USE_SYSTEM_GL2PS=OFF \
-DVTK_USE_SYSTEM_LIBHARU=OFF \
-DVTK_USE_SYSTEM_PUGIXML=OFF \
-DCMAKE_BUILD_TYPE=Release \
..
</code>```

Then I get the following error:

```<code>-- Could not use git to determine source version, using version
-- Could NOT find OpenGL (missing: OPENGL_opengl_LIBRARY OPENGL_glx_LIBRARY OpenGL)
CMake Error at CMake/vtkModule.cmake:4612 (message):
  Could not find the OpenGL external dependency.
Call Stack (most recent call first):
  CMake/vtkModule.cmake:5206 (vtk_module_find_package)
  Utilities/OpenGL/CMakeLists.txt:58 (vtk_module_third_party_external)
-- Configuring incomplete, errors occurred!
See also "$HOME/VTK-master/build/CMakeFiles/CMakeOutput.log".
See also "$HOME/VTK-master/build/CMakeFiles/CMakeError.log".
</code>```

I have tried to solve this problem using this post:

CMake could not find OpenGL in Ubuntu

but nothing happens after install "libgl1-mesa-dev" or "libegl1-mesa-dev"

Any hint of how to solve it?

Title: Install vkt in Ubuntu

Body:
I would like to install Paraview in my laptop with Ubuntu 18.04.6 LTS. I'm following this post to install vkt 8.2.0 in Ubuntu 18.04 (https://discourse.vtk.org/t/installing-vtk-in-ubuntu-18-04/2147/4). When I use

sudo cmake -DCMAKE_INSTALL_PREFIX=$HOME/vtk-inst \
-DCMAKE_INSTALL_RPATH=$HOME/vtk-inst \
-DVTK_Group_Qt=ON \
-DVTK_QT_VERSION=5 \
-DVTK_Group_Imaging=ON \
-DVTK_Group_Views=ON \
-DModule_vtkRenderingFreeTypeFontConfig=ON \
-DVTK_WRAP_PYTHON=ON \
-DVTK_PYTHON_VERSION=3 \
-DPYTHON_EXECUTABLE=/usr/bin/python3 \
-DPYTHON_INCLUDE_DIR=/usr/include/python3.6 \
-DPYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.6m.so \
-DBUILD_TESTING=OFF \
-DVTK_USE_SYSTEM_LIBRARIES=ON \
-DVTK_USE_SYSTEM_LIBPROJ4=OFF \
-DVTK_USE_SYSTEM_GL2PS=OFF \
-DVTK_USE_SYSTEM_LIBHARU=OFF \
-DVTK_USE_SYSTEM_PUGIXML=OFF \
-DCMAKE_BUILD_TYPE=Release \
..

Then I get the following error:

-- Could not use git to determine source version, using version
-- Could NOT find OpenGL (missing: OPENGL_opengl_LIBRARY OPENGL_glx_LIBRARY OpenGL)
CMake Error at CMake/vtkModule.cmake:4612 (message):
  Could not find the OpenGL external dependency.
Call Stack (most recent call first):
  CMake/vtkModule.cmake:5206 (vtk_module_find_package)
  Utilities/OpenGL/CMakeLists.txt:58 (vtk_module_third_party_external)
-- Configuring incomplete, errors occurred!
See also "$HOME/VTK-master/build/CMakeFiles/CMakeOutput.log".
See also "$HOME/VTK-master/build/CMakeFiles/CMakeError.log".

I have tried to solve this problem using this post:

CMake could not find OpenGL in Ubuntu

but nothing happens after install "libgl1-mesa-dev" or "libegl1-mesa-dev"

Any hint of how to solve it?


问:
Horizontally centering a flex div with Tailwind
I have a few items inside a div that I can't seem to get to center horizontally using Tailwind - I think it's due to how I'm using flex?

<Row>

        Create your account

We'll have you set up in a few short steps

      <Form
        data={{
          name: {
            label: "First Name",
            type: "text",
            required: true,
            errorMessage: "Please enter your first name",
          },
          email: {
            label: "Email",
            type: "email",
            required: true,
          },
        }}
      />

    Already registered?{" "}
    <Link
      url="/signin"
      className="text-pink-500 hover:text-pink-500 visited:text-pink-500"
      text="Sign In"
    />

</Row>
```

Here's how it looks - the space on the right shouldn't be there

Body:
I have a few items inside a div that I can't seem to get to center horizontally using Tailwind - I think it's due to how I'm using flex?

<Row>

        Create your account

We'll have you set up in a few short steps

      <Form
        data={{
          name: {
            label: "First Name",
            type: "text",
            required: true,
            errorMessage: "Please enter your first name",
          },
          email: {
            label: "Email",
            type: "email",
            required: true,
          },
        }}
      />

    Already registered?{" "}
    <Link
      url="/signin"
      className="text-pink-500 hover:text-pink-500 visited:text-pink-500"
      text="Sign In"
    />

</Row>

Here's how it looks - the space on the right shouldn't be there


问:
Can a Docker volume do transparent decompression for read-only files?
tl;dr What are best practices for exposing read-only data to a Dockerized app, with transparent decompression?

I have a Dockerized app which needs read-only access to a set of data files totalling 80 GB. Currently, I manually copy these to hosts, and expose them via a bind-mount. I would like to migrate these files to a Docker volume, but their size is an issue.

These files compress well, down to 15 GB. Is it possible to take advantage of that compression in the Docker volume, to avoid eagerly decompressing the full 80 GB to the host? For example, can a Docker volume use SquashFS or similar for on-demand decompression?

Things I've tried:

Using the btrfs storage driver, but this requires that the host be configured with a dedicated block device.

Using fuse-zip and mounting inside the container, but this is very hacky and requires extending additional SYS_ADMIN capabilities to the container.

In case it's relevant, the files are accessed linearly, not random-access. Thank you for any help!


问:
How do I render more than one image in my UI in an object of matched searches
I have a project I'm working on where the user has to search a tag or colour and if the stored image properties match the search then to render the list of images on the UI. I got it to partially work - but only one image loads even though the when I console log my function we can see that all matched images are returned. This leaves me to think my UI logic is off but after searching Stack Overflow and other Google searches. A push into the right direction would really be helpful.
one image renders with several matches</p>
```<code>   const matchSearchTerm = (searchTerm) => {
    let matchedImages = [];

    for (let image of images) {
        if (image.colours.includes(searchTerm) || image.tags.includes(searchTerm))  {
            matchedImages.push(image)
        }
    }
    console.log ("matches:", matchedImages)
    renderUI(matchedImages);
}

    const renderUI = (matchedImages) => {
    // console.log ("matchedImage:", matchedImages)
    // let matchedSearch = [];

       for (let matchedImage of matchedImages){
        //clearing the page on search
        const mainDiv = document.getElementById("mainDiv");
        mainDiv.innerHTML = '';

        // const matchedImage = images[0]

        // parent div
        const matchedSearchDiv = document.createElement("div");

        //image element
        const imageElement =  document.createElement("img");
        imageElement.src = matchedImage.fileName
        imageElement.setAttribute("class", "image");
        matchedSearchDiv.appendChild(imageElement);

        //p element
        const name = document.createElement("p");
        const nameText = document.createTextNode(matchedImage.title);
        name.appendChild(nameText);
        matchedSearchDiv.appendChild(name);

        // //a element
        const aTagElement = document.createElement("a");
        aTagElement.href = matchedImage.fileName
        aTagElement.setAttribute("download", "");

        matchedSearchDiv.appendChild(aTagElement);

        // button element
        const button = document.createElement("button");
        const buttonText = document.createTextNode("Get");
        button.setAttribute("class", "downloadButton");
        button.appendChild(buttonText)
        aTagElement.appendChild(button);

        //appending all the elements in the new div to the main div
        mainDiv.appendChild(matchedSearchDiv)

        // matchedSearch.push(matchedImage)
        }
}
</code>```

Body:
I have a project I'm working on where the user has to search a tag or colour and if the stored image properties match the search then to render the list of images on the UI. I got it to partially work - but only one image loads even though the when I console log my function we can see that all matched images are returned. This leaves me to think my UI logic is off but after searching Stack Overflow and other Google searches. A push into the right direction would really be helpful.
one image renders with several matches

   const matchSearchTerm = (searchTerm) => {
    let matchedImages = [];

    for (let image of images) {
        if (image.colours.includes(searchTerm) || image.tags.includes(searchTerm))  {
            matchedImages.push(image)
        }
    }
    console.log ("matches:", matchedImages)
    renderUI(matchedImages);
}

    const renderUI = (matchedImages) => {
    // console.log ("matchedImage:", matchedImages)
    // let matchedSearch = [];

       for (let matchedImage of matchedImages){
        //clearing the page on search
        const mainDiv = document.getElementById("mainDiv");
        mainDiv.innerHTML = '';

        // const matchedImage = images[0]

        // parent div
        const matchedSearchDiv = document.createElement("div");

        //image element
        const imageElement =  document.createElement("img");
        imageElement.src = matchedImage.fileName
        imageElement.setAttribute("class", "image");
        matchedSearchDiv.appendChild(imageElement);

        //p element
        const name = document.createElement("p");
        const nameText = document.createTextNode(matchedImage.title);
        name.appendChild(nameText);
        matchedSearchDiv.appendChild(name);

        // //a element
        const aTagElement = document.createElement("a");
        aTagElement.href = matchedImage.fileName
        aTagElement.setAttribute("download", "");

        matchedSearchDiv.appendChild(aTagElement);

        // button element
        const button = document.createElement("button");
        const buttonText = document.createTextNode("Get");
        button.setAttribute("class", "downloadButton");
        button.appendChild(buttonText)
        aTagElement.appendChild(button);

        //appending all the elements in the new div to the main div
        mainDiv.appendChild(matchedSearchDiv)

        // matchedSearch.push(matchedImage)
        }
}


问:
DBATools and Overload SQLCommand and a clean ISE session
I have an older server with Powershell ISE, where I can't easily install vscode.

I am trying to run DBATools.io's invoke-dbaquery using the ISE, but I get 'cannot find an overload for "sqlcommand"'.  Looking online (https://dba.stackexchange.com/questions/305582/invoke-dbaquery-not-working-on-new-server-cannot-find-an-overload-for-sqlcomma), it says it occurs if sqlserver or sqlps is loaded first.

The full error:

```<code>WARNING: [15:20:11][Invoke-DbaQuery] [myserver] Failed during execution | Cannot find an overload for "SqlCommand" and the argument count: "2".
</code>```

Looking at the various profiles below, they all say "this ps1 file", but none of the files exist.

$PROFILE.AllUsersCurrentHost

$PROFILE.CurrentUserAllHosts

$profile.CurrentUserCurrentHost

$PROFILE.AllUsersAllHosts

I have tried remove-module sqlserver and remove-module sqlps, and both return "no modules were removed".

If I open a blank powershell session the invoke-dbaquery works, but since i've got to do loops and a bunch of various commands, the ISE honestly is just a ton easier to use.

How do I get invoke-dbaquery to work in the ISE?

Body:
I have an older server with Powershell ISE, where I can't easily install vscode.

I am trying to run DBATools.io's invoke-dbaquery using the ISE, but I get 'cannot find an overload for "sqlcommand"'.  Looking online (https://dba.stackexchange.com/questions/305582/invoke-dbaquery-not-working-on-new-server-cannot-find-an-overload-for-sqlcomma), it says it occurs if sqlserver or sqlps is loaded first.

The full error:

WARNING: [15:20:11][Invoke-DbaQuery] [myserver] Failed during execution | Cannot find an overload for "SqlCommand" and the argument count: "2".

Looking at the various profiles below, they all say "this ps1 file", but none of the files exist.

$PROFILE.AllUsersCurrentHost

$PROFILE.CurrentUserAllHosts

$profile.CurrentUserCurrentHost

$PROFILE.AllUsersAllHosts

I have tried remove-module sqlserver and remove-module sqlps, and both return "no modules were removed".

If I open a blank powershell session the invoke-dbaquery works, but since i've got to do loops and a bunch of various commands, the ISE honestly is just a ton easier to use.

How do I get invoke-dbaquery to work in the ISE?


问:
Inserting Html, CSS and Javascript into the console to test a new block/feature
I have been tasked with creating a new feature/block of HTML & CSS that contains some light JS for controls (think a carousel). It is working as expected but two of the requirements are that it's one block of code and it can be run in the console and display on the web page(e.g. Chrome)

I have added the CSS and JS into the html file, so one block of code, I hope is solved, I then tried to create a little function using insertAdjacentHTML to run in the console but that doesn't work as it doesn't accept anything other than pure html (no class names or  tags etc)

I do not have access to the source code of the website they want to test it on, so apparently it has to be done in the console.

I also looked at extensions, to see if I can work out how they do it but not having much luck, happy if someone can recommend anyway in which I can display this new feature.

I understand why they want to do it this way as they will want to do quick demos of new features built, but still an unorthodox method imo. Happy to be told wrong.

Any help would be great.

TIA

EDIT: JS file - https://github.com/morphey-slavbard/product_slider/blob/main/main.js
HTML file - https://github.com/morphey-slavbard/product_slider/blob/main/index_2.html


问:
Tkinter does not display text in the grid after calling the method from another class
If I run the following code alone, it displays the text in the grid while running:

```<code>def solve_wumpus_world(master, world_file):
    world = World()
    world.generate_world(world_file)

    label_grid = [[Grid_Label(master, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
    agent = Agent(world, label_grid)

    # Agent Solving
    while agent.exited == False:
        agent.explore()
        if agent.found_gold == True:
            agent.leave_cave()
        break

    agent.repaint_world()
    agent.world_knowledge[agent.world.agent_row][agent.world.agent_col].remove('A')
    time.sleep(1.5)
    agent.repaint_world()

    # GUI
def aigui():
    game = Tk()
    game.title("Hunt the Wumpus")
    game.configure(bg="DarkOrchid4")
    game.geometry("2000x2000")
    game.iconbitmap(r'Images\Monster.ico')
    world = World()
    world.generate_world("world_1.txt")

    grid = LabelFrame(game, text="GRID", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 24")
    worldLabel = LabelFrame(game, text="MENU", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 20")

    label_grid = [[Grid_Label(grid, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]

    world_1 = Button(worldLabel, text="WORLD ONE", command=lambda: solve_wumpus_world(grid, "world_1.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_2 = Button(worldLabel, text="WORLD TWO", command=lambda: solve_wumpus_world(grid, "world_2.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_3 = Button(worldLabel, text="WORLD THREE", command=lambda: solve_wumpus_world(grid, "world_3.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_4 = Button(worldLabel, text="WORLD FOUR", command=lambda: solve_wumpus_world(grid, "world_4.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    quitButton = Button(worldLabel, text="QUIT", padx=40, font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green",
                                borderwidth=0, activeforeground="chartreuse2", activebackground="Indigo", command=lambda:game.destroy())

    grid.pack(padx=1,pady=1)
    worldLabel.pack(padx=5, pady=5)
    world_1.grid(row=0, column=0, padx=10, pady=10, sticky=EW)
    world_2.grid(row=0, column=1, padx=10, pady=10, sticky=EW)
    world_3.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
    world_4.grid(row=0, column=3, padx=10, pady=10, sticky=EW)
    quitButton.grid(row=1, column=1, columnspan=2, padx=10, pady=10, sticky=EW)

    game.mainloop()
</code>```

It shows the text inside the grid when gaming is being played

But when I call the above code from another class like a main class which has a main menu which further opens this game window, the game works fine and the boxes are also highlighted but the text isn't displayed. For example, the code below

```<code>def solve_wumpus_world(master, world_file):
    world = World()
    world.generate_world(world_file)

    label_grid = [[Grid_Label(master, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
    agent = Agent(world, label_grid)

    # Agent Solving
    while agent.exited == False:
        agent.explore()
        if agent.found_gold == True:
            agent.leave_cave()
        break

    agent.repaint_world()
    agent.world_knowledge[agent.world.agent_row][agent.world.agent_col].remove('A')
    time.sleep(1.5)
    agent.repaint_world()

    # GUI
def aigui():
    game = Tk()
    game.title("Hunt the Wumpus")
    game.configure(bg="DarkOrchid4")
    game.geometry("2000x2000")
    game.iconbitmap(r'Images\Monster.ico')
    world = World()
    world.generate_world("world_1.txt")

    grid = LabelFrame(game, text="GRID", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 24")
    worldLabel = LabelFrame(game, text="MENU", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 20")

    label_grid = [[Grid_Label(grid, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]

    world_1 = Button(worldLabel, text="WORLD ONE", command=lambda: solve_wumpus_world(grid, "world_1.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_2 = Button(worldLabel, text="WORLD TWO", command=lambda: solve_wumpus_world(grid, "world_2.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_3 = Button(worldLabel, text="WORLD THREE", command=lambda: solve_wumpus_world(grid, "world_3.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_4 = Button(worldLabel, text="WORLD FOUR", command=lambda: solve_wumpus_world(grid, "world_4.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    quitButton = Button(worldLabel, text="QUIT", padx=40, font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green",
                                borderwidth=0, activeforeground="chartreuse2", activebackground="Indigo", command=lambda:game.destroy())

    grid.pack(padx=1,pady=1)
    worldLabel.pack(padx=5, pady=5)
    world_1.grid(row=0, column=0, padx=10, pady=10, sticky=EW)
    world_2.grid(row=0, column=1, padx=10, pady=10, sticky=EW)
    world_3.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
    world_4.grid(row=0, column=3, padx=10, pady=10, sticky=EW)
    quitButton.grid(row=1, column=1, columnspan=2, padx=10, pady=10, sticky=EW)

    game.mainloop()

def maingui():
    root = Tk()
    root.geometry("600x600")
    root.title("Hunt the Wumpus - Game")
    root.configure(bg="DarkOrchid4")
    root.iconbitmap(r'Images\Monster.ico')

    # Label
    myLabel = LabelFrame(root, text="Hunt the Wumpus", fg="lawn green", bg="DarkOrchid4", padx=100, pady=100)
    textFont = ("Creepster", 24)
    myLabel.config(font=textFont)

    # Functions

    # Buttons
    buttonFont = ("Leichenhaus", 16)
    aiButton = Button(myLabel, text="GAME", fg="lawn green", bg="DarkViolet",
                    activeforeground="chartreuse2", activebackground="Indigo", padx=40, command=aigui)
    aiButton.config(font=buttonFont)
    creditButton = Button(myLabel, text="Credits", fg="lawn green", bg="DarkViolet",
                        activeforeground="chartreuse2", activebackground="Indigo", padx=40)
    creditButton.config(font=buttonFont)
    quitButton = Button(myLabel, text="Quit", fg="lawn green", bg="DarkViolet",
                        activeforeground="chartreuse2", activebackground="Indigo", padx=40, command=lambda: root.destroy())
    quitButton.config(font=buttonFont)

    # Packing on Screen
    myLabel.pack(padx=10, pady=10)
    aiButton.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
    creditButton.grid(row=1, column=2, padx=10, pady=10, sticky=EW)
    quitButton.grid(row=3, column=2, padx=10, pady=10, sticky=EW)

    root.mainloop()

maingui()
</code>```

This code calls the above code from a method when the button is pressed.

Text not being displayed but the game is working fine.

Body:
If I run the following code alone, it displays the text in the grid while running:

def solve_wumpus_world(master, world_file):
    world = World()
    world.generate_world(world_file)

    label_grid = [[Grid_Label(master, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
    agent = Agent(world, label_grid)

    # Agent Solving
    while agent.exited == False:
        agent.explore()
        if agent.found_gold == True:
            agent.leave_cave()
        break

    agent.repaint_world()
    agent.world_knowledge[agent.world.agent_row][agent.world.agent_col].remove('A')
    time.sleep(1.5)
    agent.repaint_world()

    # GUI
def aigui():
    game = Tk()
    game.title("Hunt the Wumpus")
    game.configure(bg="DarkOrchid4")
    game.geometry("2000x2000")
    game.iconbitmap(r'Images\Monster.ico')
    world = World()
    world.generate_world("world_1.txt")

    grid = LabelFrame(game, text="GRID", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 24")
    worldLabel = LabelFrame(game, text="MENU", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 20")

    label_grid = [[Grid_Label(grid, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]

    world_1 = Button(worldLabel, text="WORLD ONE", command=lambda: solve_wumpus_world(grid, "world_1.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_2 = Button(worldLabel, text="WORLD TWO", command=lambda: solve_wumpus_world(grid, "world_2.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_3 = Button(worldLabel, text="WORLD THREE", command=lambda: solve_wumpus_world(grid, "world_3.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_4 = Button(worldLabel, text="WORLD FOUR", command=lambda: solve_wumpus_world(grid, "world_4.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    quitButton = Button(worldLabel, text="QUIT", padx=40, font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green",
                                borderwidth=0, activeforeground="chartreuse2", activebackground="Indigo", command=lambda:game.destroy())

    grid.pack(padx=1,pady=1)
    worldLabel.pack(padx=5, pady=5)
    world_1.grid(row=0, column=0, padx=10, pady=10, sticky=EW)
    world_2.grid(row=0, column=1, padx=10, pady=10, sticky=EW)
    world_3.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
    world_4.grid(row=0, column=3, padx=10, pady=10, sticky=EW)
    quitButton.grid(row=1, column=1, columnspan=2, padx=10, pady=10, sticky=EW)

    game.mainloop()

It shows the text inside the grid when gaming is being played

But when I call the above code from another class like a main class which has a main menu which further opens this game window, the game works fine and the boxes are also highlighted but the text isn't displayed. For example, the code below

def solve_wumpus_world(master, world_file):
    world = World()
    world.generate_world(world_file)

    label_grid = [[Grid_Label(master, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]
    agent = Agent(world, label_grid)

    # Agent Solving
    while agent.exited == False:
        agent.explore()
        if agent.found_gold == True:
            agent.leave_cave()
        break

    agent.repaint_world()
    agent.world_knowledge[agent.world.agent_row][agent.world.agent_col].remove('A')
    time.sleep(1.5)
    agent.repaint_world()

    # GUI
def aigui():
    game = Tk()
    game.title("Hunt the Wumpus")
    game.configure(bg="DarkOrchid4")
    game.geometry("2000x2000")
    game.iconbitmap(r'Images\Monster.ico')
    world = World()
    world.generate_world("world_1.txt")

    grid = LabelFrame(game, text="GRID", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 24")
    worldLabel = LabelFrame(game, text="MENU", fg="lawn green", bg="DarkOrchid4", padx=10, pady=10, font="Creepster 20")

    label_grid = [[Grid_Label(grid, i, j) for j in range(world.num_cols)] for i in range(world.num_rows)]

    world_1 = Button(worldLabel, text="WORLD ONE", command=lambda: solve_wumpus_world(grid, "world_1.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_2 = Button(worldLabel, text="WORLD TWO", command=lambda: solve_wumpus_world(grid, "world_2.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_3 = Button(worldLabel, text="WORLD THREE", command=lambda: solve_wumpus_world(grid, "world_3.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    world_4 = Button(worldLabel, text="WORLD FOUR", command=lambda: solve_wumpus_world(grid, "world_4.txt"), padx=40,
                            font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green", borderwidth=0,
                            activeforeground="chartreuse2", activebackground="Indigo")
    quitButton = Button(worldLabel, text="QUIT", padx=40, font="Leichenhaus 16 bold", bg="DarkViolet", fg="lawn green",
                                borderwidth=0, activeforeground="chartreuse2", activebackground="Indigo", command=lambda:game.destroy())

    grid.pack(padx=1,pady=1)
    worldLabel.pack(padx=5, pady=5)
    world_1.grid(row=0, column=0, padx=10, pady=10, sticky=EW)
    world_2.grid(row=0, column=1, padx=10, pady=10, sticky=EW)
    world_3.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
    world_4.grid(row=0, column=3, padx=10, pady=10, sticky=EW)
    quitButton.grid(row=1, column=1, columnspan=2, padx=10, pady=10, sticky=EW)

    game.mainloop()

def maingui():
    root = Tk()
    root.geometry("600x600")
    root.title("Hunt the Wumpus - Game")
    root.configure(bg="DarkOrchid4")
    root.iconbitmap(r'Images\Monster.ico')

    # Label
    myLabel = LabelFrame(root, text="Hunt the Wumpus", fg="lawn green", bg="DarkOrchid4", padx=100, pady=100)
    textFont = ("Creepster", 24)
    myLabel.config(font=textFont)

    # Functions

    # Buttons
    buttonFont = ("Leichenhaus", 16)
    aiButton = Button(myLabel, text="GAME", fg="lawn green", bg="DarkViolet",
                    activeforeground="chartreuse2", activebackground="Indigo", padx=40, command=aigui)
    aiButton.config(font=buttonFont)
    creditButton = Button(myLabel, text="Credits", fg="lawn green", bg="DarkViolet",
                        activeforeground="chartreuse2", activebackground="Indigo", padx=40)
    creditButton.config(font=buttonFont)
    quitButton = Button(myLabel, text="Quit", fg="lawn green", bg="DarkViolet",
                        activeforeground="chartreuse2", activebackground="Indigo", padx=40, command=lambda: root.destroy())
    quitButton.config(font=buttonFont)

    # Packing on Screen
    myLabel.pack(padx=10, pady=10)
    aiButton.grid(row=0, column=2, padx=10, pady=10, sticky=EW)
    creditButton.grid(row=1, column=2, padx=10, pady=10, sticky=EW)
    quitButton.grid(row=3, column=2, padx=10, pady=10, sticky=EW)

    root.mainloop()

maingui()

This code calls the above code from a method when the button is pressed.

Text not being displayed but the game is working fine.


问:
I'm using onclick functionality inside a loop. How do I store the value of it?

for (var i = 0; i < 10; i++) {
  str = [str, "
"].join("");
  str = [str, "<input class=' wColor' name='inputId' id='inputId' onclick='c3lshow:cont_btn_" + i + "& c3lhide:cont_btn_" + k + "' align='right' width='100%' type='radio'  valign='middle'>.</input>"].join("");
  str = [str, "
"].join("");
}
```

I'm creating a multi-card interface where when you select one card, a continue button pops below it, and the same button hides for the other card (in case you selected a card previously). I want to use the value of 'i' of the previous card as the new value of 'k'.

Body:
for (var i = 0; i < 10; i++) {
  str = [str, "
"].join("");
  str = [str, "<input class=' wColor' name='inputId' id='inputId' onclick='c3lshow:cont_btn_" + i + "& c3lhide:cont_btn_" + k + "' align='right' width='100%' type='radio'  valign='middle'>.</input>"].join("");
  str = [str, "
"].join("");
}

I'm creating a multi-card interface where when you select one card, a continue button pops below it, and the same button hides for the other card (in case you selected a card previously). I want to use the value of 'i' of the previous card as the new value of 'k'.


问:
Change password field text color only when iOS password manager highlights the field yellow
I have a React site where the normal text color of my login / signup password fields is white.

When iOS password manager has a password suggestion for the sign up password field, it highlights the field yellow and the white password text is difficult to read.

As far as I can tell, the only way to prevent the yellow highlighting is to change the field type to 'one-time password', or by disabling autofill, both of which break normal password field behavior like password manager intervention, which is not good.

Is there a way to change the font color in the text field selectively, ie only when iOS password manager is taking over the box? Or is there another way to keep the normal white text color for most purposes but to make it more legible when iOS forces the yellow background when managing passwords?

screenshot of the issue

Edit: someone asked for code - this the current field

<input aria-invalid="false" autocomplete="current-password" id="password" name="password" required="" type="password" class="MuiInputBase-input MuiOutlinedInput-input css-h4os0j" value="">


问:
SDL2_image not showing up, getting instead a black screen
I am doing a game using SDL.

The problem is that instead of getting image I see a black screen without any errors. And the most interesting thing that I've made another test project to see if I'll get an image and this one works excellent. In test project I have only main.cpp which does the same (not sure as i am getting black screen in my main project) and not using headers and this stuff.

Here is my code:

main.cpp(game project)

```<code>#include <SDL2\SDL.h>
#include <SDL2\SDL_image.h>
#include <iostream>
#include <stdio.h>
#include "RenderWindow.hpp"

int main(int argc, char** argv){
    if (SDL_Init(SDL_INIT_VIDEO) > 0)
        std::cout << "SDL_init has crushed" << SDL_GetError() << std::endl; // ініціалізація сдл

    if (!(IMG_Init(IMG_INIT_PNG)))
        std::cout << "IMG_init has failed. Error: " << IMG_GetError() << std::endl;

    RenderWindow window("Game",640,480);

    SDL_Texture* grassTexture = window.loadTexture("images/ground_grass_1.png");

    bool gameRunning = true;

    SDL_Event event;

    while(gameRunning)
    {
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
                gameRunning = false;
        }

        window.clear();
        window.render(grassTexture);
        window.display();
    }

    window.cleanUp();
    IMG_Quit();
    SDL_Quit();

    return 0;
}
</code>```

RenderWindow.hpp

```<code>#pragma once
#include <SDL2\SDL.h>
#include <SDL2\SDL_image.h>

class RenderWindow
{
    public:
        RenderWindow(const char* p_title, int p_w, int p_h);
        SDL_Texture* loadTexture(const char* p_filePath);
        void cleanUp();
        void clear();
        void render(SDL_Texture* p_text);
        void display();
    private:
        SDL_Window* window;
        SDL_Renderer* renderer;
};
</code>```

renderwindow.cpp

```<code>#include <SDL2\SDL.h>
#include <SDL2\SDL_image.h>
#include <iostream>

#include "RenderWindow.hpp"

RenderWindow::RenderWindow(const char* p_title, int p_w, int p_h)
    :window(NULL), renderer(NULL) // присвоювання нульових поінтеров
{
    window = SDL_CreateWindow(p_title,SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,p_w,p_h,SDL_WINDOW_SHOWN); // ініціалізація вікна

    if(window == NULL)
        std::cout << "Window failed to init" << SDL_GetError() << std::endl;

    renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED); // ініціалізація рендера

    if(renderer == NULL)
        std::cout << "Renderer failed to init" << SDL_GetError() << std::endl;
}

SDL_Texture* RenderWindow::loadTexture(const char* p_filePath)
{
    SDL_Texture* texture = NULL;
    texture = IMG_LoadTexture(renderer,p_filePath);

    if(texture = NULL)
        std::cout << "Failed to load texture. Error: " << SDL_GetError() << std::endl;

    return texture;
}

void RenderWindow::cleanUp()
{
    SDL_DestroyWindow(window);
}

void RenderWindow::clear()
{
    SDL_RenderClear(renderer);
}

void RenderWindow::render(SDL_Texture* p_tex)
{
    SDL_RenderCopy(renderer,p_tex,NULL,NULL);
}

void RenderWindow::display()
{
    SDL_RenderPresent(renderer);
}
</code>```

and main.cpp(test project)

```<code>#include <SDL2/SDL.h>  // include the SDL library
#include <SDL2/SDL_image.h>  // include the SDL_image library for loading image files
#include <iostream>

int main(int argc, char* argv[]) {
  // initialize SDL
  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    std::cout << "SDL initialization failed: " << SDL_GetError() << std::endl;
    return 1;
  }

  // create the window
  SDL_Window* window = SDL_CreateWindow("My Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
  if (window == NULL) {
    std::cout << "Failed to create window: " << SDL_GetError() << std::endl;
    return 1;
  }

  // create the renderer
  SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
  if (renderer == NULL) {
    std::cout << "Failed to create renderer: " << SDL_GetError() << std::endl;
    return 1;
  }

  // load the image file
  SDL_Texture* texture = IMG_LoadTexture(renderer, "ground_grass_1.png");
  if (texture == NULL) {
    std::cout << "Failed to load image: " << SDL_GetError() << std::endl;
    return 1;
  }

  // render the image
  SDL_RenderCopy(renderer, texture, NULL, NULL);
  SDL_RenderPresent(renderer);

  // wait for 5 seconds
  SDL_Delay(5000);

  // clean up
  SDL_DestroyTexture(texture);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}
</code>```

Body:
I am doing a game using SDL.

The problem is that instead of getting image I see a black screen without any errors. And the most interesting thing that I've made another test project to see if I'll get an image and this one works excellent. In test project I have only main.cpp which does the same (not sure as i am getting black screen in my main project) and not using headers and this stuff.

Here is my code:

main.cpp(game project)

#include <SDL2\SDL.h>
#include <SDL2\SDL_image.h>
#include <iostream>
#include <stdio.h>
#include "RenderWindow.hpp"

int main(int argc, char** argv){
    if (SDL_Init(SDL_INIT_VIDEO) > 0)
        std::cout << "SDL_init has crushed" << SDL_GetError() << std::endl; // ініціалізація сдл

    if (!(IMG_Init(IMG_INIT_PNG)))
        std::cout << "IMG_init has failed. Error: " << IMG_GetError() << std::endl;

    RenderWindow window("Game",640,480);

    SDL_Texture* grassTexture = window.loadTexture("images/ground_grass_1.png");

    bool gameRunning = true;

    SDL_Event event;

    while(gameRunning)
    {
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
                gameRunning = false;
        }

        window.clear();
        window.render(grassTexture);
        window.display();
    }

    window.cleanUp();
    IMG_Quit();
    SDL_Quit();

    return 0;
}

RenderWindow.hpp

#pragma once
#include <SDL2\SDL.h>
#include <SDL2\SDL_image.h>

class RenderWindow
{
    public:
        RenderWindow(const char* p_title, int p_w, int p_h);
        SDL_Texture* loadTexture(const char* p_filePath);
        void cleanUp();
        void clear();
        void render(SDL_Texture* p_text);
        void display();
    private:
        SDL_Window* window;
        SDL_Renderer* renderer;
};

renderwindow.cpp

#include <SDL2\SDL.h>
#include <SDL2\SDL_image.h>
#include <iostream>

#include "RenderWindow.hpp"

RenderWindow::RenderWindow(const char* p_title, int p_w, int p_h)
    :window(NULL), renderer(NULL) // присвоювання нульових поінтеров
{
    window = SDL_CreateWindow(p_title,SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,p_w,p_h,SDL_WINDOW_SHOWN); // ініціалізація вікна

    if(window == NULL)
        std::cout << "Window failed to init" << SDL_GetError() << std::endl;

    renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED); // ініціалізація рендера

    if(renderer == NULL)
        std::cout << "Renderer failed to init" << SDL_GetError() << std::endl;
}

SDL_Texture* RenderWindow::loadTexture(const char* p_filePath)
{
    SDL_Texture* texture = NULL;
    texture = IMG_LoadTexture(renderer,p_filePath);

    if(texture = NULL)
        std::cout << "Failed to load texture. Error: " << SDL_GetError() << std::endl;

    return texture;
}

void RenderWindow::cleanUp()
{
    SDL_DestroyWindow(window);
}

void RenderWindow::clear()
{
    SDL_RenderClear(renderer);
}

void RenderWindow::render(SDL_Texture* p_tex)
{
    SDL_RenderCopy(renderer,p_tex,NULL,NULL);
}

void RenderWindow::display()
{
    SDL_RenderPresent(renderer);
}

and main.cpp(test project)

#include <SDL2/SDL.h>  // include the SDL library
#include <SDL2/SDL_image.h>  // include the SDL_image library for loading image files
#include <iostream>

int main(int argc, char* argv[]) {
  // initialize SDL
  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    std::cout << "SDL initialization failed: " << SDL_GetError() << std::endl;
    return 1;
  }

  // create the window
  SDL_Window* window = SDL_CreateWindow("My Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
  if (window == NULL) {
    std::cout << "Failed to create window: " << SDL_GetError() << std::endl;
    return 1;
  }

  // create the renderer
  SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
  if (renderer == NULL) {
    std::cout << "Failed to create renderer: " << SDL_GetError() << std::endl;
    return 1;
  }

  // load the image file
  SDL_Texture* texture = IMG_LoadTexture(renderer, "ground_grass_1.png");
  if (texture == NULL) {
    std::cout << "Failed to load image: " << SDL_GetError() << std::endl;
    return 1;
  }

  // render the image
  SDL_RenderCopy(renderer, texture, NULL, NULL);
  SDL_RenderPresent(renderer);

  // wait for 5 seconds
  SDL_Delay(5000);

  // clean up
  SDL_DestroyTexture(texture);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}


问:
nwj.s change webview http referrer
i have moved from electronjs to nwjs, and i want to change the http referer but does not work, i already did it in electronjs.. here is example..

```<code><webview
id="ref"
src="https://whatsmyreferer.com/"
httpreferrer="http://google.com"
useragent="Custom user agent"
</webview>
</code>```

In nw.js, I don't see httpreferrer and useragent parameters in webview, how can I do that in nw.js, I'm new on nwjs, please help?

thanks in advance..

Title: nwj.s change webview http referrer

Body:
i have moved from electronjs to nwjs, and i want to change the http referer but does not work, i already did it in electronjs.. here is example..

<webview
id="ref"
src="https://whatsmyreferer.com/"
httpreferrer="http://google.com"
useragent="Custom user agent"
</webview>

In nw.js, I don't see httpreferrer and useragent parameters in webview, how can I do that in nw.js, I'm new on nwjs, please help?

thanks in advance..


问:
How feasible would a 24 hour "rolling" API endpoint be?
I've been victim of users using my undocumented API endpoints for quite a while now. But I've been thinking of an idea for the past few weeks, where the endpoint that my webapp uses, changes every 24-48 hours. This would be to discourage these users from reverse-engineering and using my API, subsequently using up my server resources.

How feasible would this be? And do you think there would be a way to automate this?


问:
Redirecting Web browser tab on Windows
I would like to redirect web browser Url with a different specific URL. I believe I can do it by changing the Host file in Windows, however I would like to try a way to do it Winforms/C# app.

One way of doing it would be getting current tab process Id, closing it and open a new process for chrome, IE Explorer or firefox. Below code is working and it can get the active URL from any web browser. However it cannot get the Web browswer tab process id. It get the Main Chrome Process Id. How can I get that Tab info? Or can I do it a different way?

```<code>public readonly CUIAutomation _automation  = new CUIAutomation();
public void HandleFocusChangedEvent(IUIAutomationElement element)
    {
        if (element != null)
        {
            try
            {
                using (Process process = Process.GetProcessById(element.CurrentProcessId))
                {
                    try
                    {
                        if ((!process.ProcessName.Contains("chrome") || process.ProcessName.Contains("browswermsedge") || process.ProcessName.Contains("firefox"))) {
                            Debug.WriteLine("Action is not from a web browswer, " + process.ProcessName);
                            return;
                        }

                        IUIAutomationElement elm = _automation.ElementFromHandle(process.MainWindowHandle);
                        IUIAutomationCondition Cond = _automation.CreatePropertyCondition(30003, 50004);
                        IUIAutomationElementArray elm2 = elm.FindAll(TreeScope.TreeScope_Descendants, Cond);

                        for (int i = 0; i < elm2.Length; i++)
                        {
                            IUIAutomationElement elm3 = elm2.GetElement(i);
                            IUIAutomationValuePattern val = (IUIAutomationValuePattern)elm3.GetCurrentPattern(10002);
                            if (val == null)
                            {
                                continue;
                            }

                            if (val.CurrentValue != "" && val.CurrentValue.Contains(".com"))
                            {
                                Debug.WriteLine("An URL FOUND: " + val.CurrentValue);
                                // AN URL FOUND BUT CANNOT GET PROCESS ID WITH
                                // elm3.CurrentProcessId it gives main Chrome process Id
                            }
                        }
                    }
                    catch
                    {
                        Debug.WriteLine("Exception occured while getting active application URL");
                    }
                }
            }
            catch {
                Debug.WriteLine("Could not get process Information while getting the active URL");
            }
        }
    }
</code>```

Above code is from this stack overflow answer Btw I am open to any suggestion on redirecting URL on web browswer. I even tried below code which changes the URL in active tab, but it doesn't go that web site.

```<code>val.SetValue("SomeUrl.com")
</code>```

Title: Redirecting Web browser tab on Windows

Body:
I would like to redirect web browser Url with a different specific URL. I believe I can do it by changing the Host file in Windows, however I would like to try a way to do it Winforms/C# app.

One way of doing it would be getting current tab process Id, closing it and open a new process for chrome, IE Explorer or firefox. Below code is working and it can get the active URL from any web browser. However it cannot get the Web browswer tab process id. It get the Main Chrome Process Id. How can I get that Tab info? Or can I do it a different way?

public readonly CUIAutomation _automation  = new CUIAutomation();
public void HandleFocusChangedEvent(IUIAutomationElement element)
    {
        if (element != null)
        {
            try
            {
                using (Process process = Process.GetProcessById(element.CurrentProcessId))
                {
                    try
                    {
                        if ((!process.ProcessName.Contains("chrome") || process.ProcessName.Contains("browswermsedge") || process.ProcessName.Contains("firefox"))) {
                            Debug.WriteLine("Action is not from a web browswer, " + process.ProcessName);
                            return;
                        }

                        IUIAutomationElement elm = _automation.ElementFromHandle(process.MainWindowHandle);
                        IUIAutomationCondition Cond = _automation.CreatePropertyCondition(30003, 50004);
                        IUIAutomationElementArray elm2 = elm.FindAll(TreeScope.TreeScope_Descendants, Cond);

                        for (int i = 0; i < elm2.Length; i++)
                        {
                            IUIAutomationElement elm3 = elm2.GetElement(i);
                            IUIAutomationValuePattern val = (IUIAutomationValuePattern)elm3.GetCurrentPattern(10002);
                            if (val == null)
                            {
                                continue;
                            }

                            if (val.CurrentValue != "" && val.CurrentValue.Contains(".com"))
                            {
                                Debug.WriteLine("An URL FOUND: " + val.CurrentValue);
                                // AN URL FOUND BUT CANNOT GET PROCESS ID WITH
                                // elm3.CurrentProcessId it gives main Chrome process Id
                            }
                        }
                    }
                    catch
                    {
                        Debug.WriteLine("Exception occured while getting active application URL");
                    }
                }
            }
            catch {
                Debug.WriteLine("Could not get process Information while getting the active URL");
            }
        }
    }

Above code is from this stack overflow answer Btw I am open to any suggestion on redirecting URL on web browswer. I even tried below code which changes the URL in active tab, but it doesn't go that web site.

val.SetValue("SomeUrl.com")


问:
How to make the horizontal axis scale larger for matplotlib drawing without changing the data range？
The figure below is the line graph I drew. Now I want to make the x-axis longer, because I want to do the region splitting of the x-axis, and the x-axis is too short to see. I mean to make the scale of the x-axis bigger without changing the data range. Because my x-axis range is determined by the data plotted in the file. Please ask: How can I extend the x-axis so that it becomes visually longer?
enter image description here

code：

```<code>    self.xdata = BagData.loc[:,'%time'] / 1e9

    for i, iheader in enumerate(self.NumericList):
        columns = [col for col in BagData.columns if iheader in col]

        for j, column in enumerate(columns):
            y_data = BagData[column]
            plt.plot(self.xdata,y_data,color=f'C{j}',mec='r',mfc='w',label = column)
            #plt.legend()
            plt.xlabel(u'time',size=10)

        plt.ylabel(iheader,size=10)
        plt.title(iheader)
        plt.legend(bbox_to_anchor=(1.05, 0), loc=3, borderaxespad=0)
        plt.minorticks_on()
</code>```

self.data is horizontal axis data and y_data is vertical axis data.

How can I extend the x-axis so that it becomes visually longer?

Body:
The figure below is the line graph I drew. Now I want to make the x-axis longer, because I want to do the region splitting of the x-axis, and the x-axis is too short to see. I mean to make the scale of the x-axis bigger without changing the data range. Because my x-axis range is determined by the data plotted in the file. Please ask: How can I extend the x-axis so that it becomes visually longer?
enter image description here

code：

    self.xdata = BagData.loc[:,'%time'] / 1e9

    for i, iheader in enumerate(self.NumericList):
        columns = [col for col in BagData.columns if iheader in col]

        for j, column in enumerate(columns):
            y_data = BagData[column]
            plt.plot(self.xdata,y_data,color=f'C{j}',mec='r',mfc='w',label = column)
            #plt.legend()
            plt.xlabel(u'time',size=10)

        plt.ylabel(iheader,size=10)
        plt.title(iheader)
        plt.legend(bbox_to_anchor=(1.05, 0), loc=3, borderaxespad=0)
        plt.minorticks_on()

self.data is horizontal axis data and y_data is vertical axis data.

How can I extend the x-axis so that it becomes visually longer?


问:
Need Pine Script code to calculate the last two times a condition was met, get the Lows and color the bars on the chart with different colors
I need help with the following syntax for Pinescript v5.

Find the last two times a condition was met

Get the lows for those bars

Color the bars for those two bars on the chart with two different colors.


问:
TypeError: Singleton array cannot be considered a valid collection
Tried using k-cross validation from this link but with my own dataset and I got this error:

TypeError: Singleton array array(<BatchDataset element_spec=(TensorSpec(shape=(None, 180, 180, 3), dtype=tf.float32, name=None), TensorSpec(shape=(None,), dtype=tf.int32, name=None))>,
dtype=object) cannot be considered a valid collection.

Here is my code:

```<code>import numpy as np
import PIL
import tensorflow as tf
import os
from sklearn.model_selection import KFold
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential

import pathlib

num_folds = 10

acc_per_fold = []
loss_per_fold = []

tf.get_logger().setLevel('ERROR')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

dataset_path = "data"
fullPath = os.path.abspath("./" + dataset_path)
#data_dir = tf.keras.utils.get_file('photos', origin='file://'+dataset_path, extract=True)
data_dir = pathlib.Path(fullPath)

image_count = len(list(data_dir.glob('*/*.jpg')))+len(list(data_dir.glob('*/*.png')))
print(image_count)

#man = list(data_dir.glob('man/*'))
#im = PIL.Image.open(str(man[28]))
#im.show()

batch_size = 32
img_height = 180
img_width = 180

train_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  labels='inferred',
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

val_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  labels='inferred',
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

class_names = train_ds.class_names
print(class_names)

normalization_layer = layers.Rescaling(1./255)
# Define the K-fold Cross Validator
kfold = KFold(n_splits=num_folds, shuffle=True, random_state=42)

fold_no = 1
for train, test in kfold.split(train_ds, val_ds):

  # Define the model architecture
  model = Sequential()
  model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Flatten())
  model.add(Dense(256, activation='relu'))
  model.add(Dense(128, activation='relu'))
  model.add(Dense(no_classes, activation='softmax'))

  # Compile the model
  model.compile(loss=loss_function,
                optimizer=optimizer,
                metrics=['accuracy'])

  # Generate a print
  print('------------------------------------------------------------------------')
  print(f'Training for fold {fold_no} ...')

  # Fit data to model
  history = model.fit(inputs[train], targets[train],
              batch_size=batch_size,
              epochs=no_epochs,
              verbose=verbosity)
  # Generate generalization metrics
  scores = model.evaluate(inputs[test], targets[test], verbose=0)
  print(f'Score for fold {fold_no}: {model.metrics_names[0]} of {scores[0]}; {model.metrics_names[1]} of {scores[1]*100}%')
  acc_per_fold.append(scores[1] * 100)
  loss_per_fold.append(scores[0])

  # Increase fold number
  fold_no = fold_no + 1
# == Provide average scores ==
print('------------------------------------------------------------------------')
print('Score per fold')
for i in range(0, len(acc_per_fold)):
  print('------------------------------------------------------------------------')
  print(f'> Fold {i+1} - Loss: {loss_per_fold[i]} - Accuracy: {acc_per_fold[i]}%')
print('------------------------------------------------------------------------')
print('Average scores for all folds:')
print(f'> Accuracy: {np.mean(acc_per_fold)} (+- {np.std(acc_per_fold)})')
print(f'> Loss: {np.mean(loss_per_fold)}')
print('------------------------------------------------------------------------')
</code>```

Body:
Tried using k-cross validation from this link but with my own dataset and I got this error:

TypeError: Singleton array array(<BatchDataset element_spec=(TensorSpec(shape=(None, 180, 180, 3), dtype=tf.float32, name=None), TensorSpec(shape=(None,), dtype=tf.int32, name=None))>,
dtype=object) cannot be considered a valid collection.

Here is my code:

import numpy as np
import PIL
import tensorflow as tf
import os
from sklearn.model_selection import KFold
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential

import pathlib

num_folds = 10

acc_per_fold = []
loss_per_fold = []

tf.get_logger().setLevel('ERROR')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

dataset_path = "data"
fullPath = os.path.abspath("./" + dataset_path)
#data_dir = tf.keras.utils.get_file('photos', origin='file://'+dataset_path, extract=True)
data_dir = pathlib.Path(fullPath)

image_count = len(list(data_dir.glob('*/*.jpg')))+len(list(data_dir.glob('*/*.png')))
print(image_count)

#man = list(data_dir.glob('man/*'))
#im = PIL.Image.open(str(man[28]))
#im.show()

batch_size = 32
img_height = 180
img_width = 180

train_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  labels='inferred',
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

val_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  labels='inferred',
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

class_names = train_ds.class_names
print(class_names)

normalization_layer = layers.Rescaling(1./255)
# Define the K-fold Cross Validator
kfold = KFold(n_splits=num_folds, shuffle=True, random_state=42)

fold_no = 1
for train, test in kfold.split(train_ds, val_ds):

  # Define the model architecture
  model = Sequential()
  model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Flatten())
  model.add(Dense(256, activation='relu'))
  model.add(Dense(128, activation='relu'))
  model.add(Dense(no_classes, activation='softmax'))

  # Compile the model
  model.compile(loss=loss_function,
                optimizer=optimizer,
                metrics=['accuracy'])

  # Generate a print
  print('------------------------------------------------------------------------')
  print(f'Training for fold {fold_no} ...')

  # Fit data to model
  history = model.fit(inputs[train], targets[train],
              batch_size=batch_size,
              epochs=no_epochs,
              verbose=verbosity)
  # Generate generalization metrics
  scores = model.evaluate(inputs[test], targets[test], verbose=0)
  print(f'Score for fold {fold_no}: {model.metrics_names[0]} of {scores[0]}; {model.metrics_names[1]} of {scores[1]*100}%')
  acc_per_fold.append(scores[1] * 100)
  loss_per_fold.append(scores[0])

  # Increase fold number
  fold_no = fold_no + 1
# == Provide average scores ==
print('------------------------------------------------------------------------')
print('Score per fold')
for i in range(0, len(acc_per_fold)):
  print('------------------------------------------------------------------------')
  print(f'> Fold {i+1} - Loss: {loss_per_fold[i]} - Accuracy: {acc_per_fold[i]}%')
print('------------------------------------------------------------------------')
print('Average scores for all folds:')
print(f'> Accuracy: {np.mean(acc_per_fold)} (+- {np.std(acc_per_fold)})')
print(f'> Loss: {np.mean(loss_per_fold)}')
print('------------------------------------------------------------------------')


问:
Codesigning results in process being immediately killed
I am trying to manipulate an external process's memory through the mach.h API on MacOS.

The idea is to be able to run this code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <mach/mach_traps.h>
#include <mach/mach_init.h>
#include <mach/mach_error.h>

int main(int argc, char* argv[])
{
    task_t task;
    pid_t pid = argc >= 2 ? atoi(argv[1]) : 1;
    kern_return_t error = task_for_pid(current_task(), pid, &task);
    printf("%d -> %x [%d - %s]\n", pid, task, error, mach_error_string(error));
    return error;
}
</code>```

(after this is able to run using the vm_read/write should be trivial to manipulate memory)

However it seems that Apple has made it increasingly more difficult to use the task_for_pid over the years as it is a system vulnerability. Thankfully (as far as I understand), it has not been made impossible, however I can't seem to get it to work.

After attempting to compile the code using gcc and then codesigning it using the following snippet:

```<code>codesign --sign - \
    --entitlements Entitlements.plist \
    --deep main \
    --force
</code>```

And the Entitlements.plist:

```<code><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>com.apple.springboard.debugapplications</key>
        <true/>
        <key>get-task-allow</key>
        <true/>
        <key>task_for_pid-allow</key>
        <true/>
    </dict>
</plist>
</code>```

Running the process results in [1]    <pid> killed     ./main instantly.
Without the codesign, any PID will simply return 5 - (os/kern) failure even when run in root.

Does anybody know how to overcome this? Or any other possible solution for accessing foreign processes' memory from C that works as of now (I have found other Stack Overflow questions which answer this, such as task_for_pid always returns (os/kern) failure on darwin in C, but their methods don't seem to work anymore as they are over 10 years old).

I am essentially looking for a ReadProcessMemory/WriteProcessMemory equivalent on MacOS.

Any help or further insight is greatly appreciated.

Body:
I am trying to manipulate an external process's memory through the mach.h API on MacOS.

The idea is to be able to run this code:

#include <stdio.h>
#include <stdlib.h>
#include <mach/mach_traps.h>
#include <mach/mach_init.h>
#include <mach/mach_error.h>

int main(int argc, char* argv[])
{
    task_t task;
    pid_t pid = argc >= 2 ? atoi(argv[1]) : 1;
    kern_return_t error = task_for_pid(current_task(), pid, &task);
    printf("%d -> %x [%d - %s]\n", pid, task, error, mach_error_string(error));
    return error;
}

(after this is able to run using the vm_read/write should be trivial to manipulate memory)

However it seems that Apple has made it increasingly more difficult to use the task_for_pid over the years as it is a system vulnerability. Thankfully (as far as I understand), it has not been made impossible, however I can't seem to get it to work.

After attempting to compile the code using gcc and then codesigning it using the following snippet:

codesign --sign - \
    --entitlements Entitlements.plist \
    --deep main \
    --force

And the Entitlements.plist:

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>com.apple.springboard.debugapplications</key>
        <true/>
        <key>get-task-allow</key>
        <true/>
        <key>task_for_pid-allow</key>
        <true/>
    </dict>
</plist>

Running the process results in [1]    <pid> killed     ./main instantly.
Without the codesign, any PID will simply return 5 - (os/kern) failure even when run in root.

Does anybody know how to overcome this? Or any other possible solution for accessing foreign processes' memory from C that works as of now (I have found other Stack Overflow questions which answer this, such as task_for_pid always returns (os/kern) failure on darwin in C, but their methods don't seem to work anymore as they are over 10 years old).

I am essentially looking for a ReadProcessMemory/WriteProcessMemory equivalent on MacOS.

Any help or further insight is greatly appreciated.


问:
What is the best php option to connect to outlook imap with oAuth?
What would be the best option to connect to an outlook email account with PHP?
I´m not sure how to declare my credentials with oAuth, should I use my e-mail as username or the client Id key as username? Should I use client secret as password?

I've been trying the following solutions with no success:

https://github.com/javanile/php-imap2

```<code>include "inc/php-imap2/vendor/autoload.php";

// Start connection
$mailbox = "{smtp.office365.com:993/imap/ssl/novalidate-cert}";
$token = base64_encode("user=" . $email . "\1auth=Bearer " . $passw . "\1\1");
$imap = @imap2_open($mailbox, $email, $token, OP_XOAUTH2);

// List all mailboxes
if ($imap) {
    $mailboxes = imap2_getmailboxes($imap, $mailbox, '*');
    var_dump($mailboxes);
} else {
    $error = imap2_last_error();
    echo $error;
}
</code>```

Return

```<code>Can not authenticate to IMAP server: A0001 NO AUTHENTICATE failed.
</code>```

https://github.com/Webklex/php-imap

```<code>include "inc/php-imap/vendor/autoload.php";

use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Client;

$cm = new ClientManager($options = []);

$client = $cm->make([
    'host'          => "smtp.office365.com",
    'port'          => 993,
    'encryption'    => 'ssl',
    'validate_cert' => true,
    'username'      => $email,
    'password'      => $passw,
    'protocol'      => 'imap',
    'authentication' => 'oauth',
]);

//Connect to the IMAP Server
$client->connect();
</code>```

Return

```<code>got failure response: NO AUTHENTICATE failed.

PHP Fatal error:  Uncaught Webklex\PHPIMAP\Exceptions\AuthFailedException in C:\inetpub\wwwroot\inc\php-imap\src\Client.php:385
Stack trace:
#0 C:\inetpub\wwwroot\inc\php-imap\src\Client.php(371): Webklex\PHPIMAP\Client->authenticate()
#1 C:\inetpub\wwwroot\test.php(57): Webklex\PHPIMAP\Client->connect()
#2 {main}

Next Webklex\PHPIMAP\Exceptions\ConnectionFailedException: connection setup failed in C:\inetpub\wwwroot\inc\php-imap\src\Client.php:391
Stack trace:
#0 C:\inetpub\wwwroot\inc\php-imap\src\Client.php(371): Webklex\PHPIMAP\Client->authenticate()
#1 C:\inetpub\wwwroot\test.php(57): Webklex\PHPIMAP\Client->connect()
#2 {main}
  thrown in C:\inetpub\wwwroot\inc\php-imap\src\Client.php on line 391
</code>```

Any help is appreciated

Body:
What would be the best option to connect to an outlook email account with PHP?
I´m not sure how to declare my credentials with oAuth, should I use my e-mail as username or the client Id key as username? Should I use client secret as password?

I've been trying the following solutions with no success:

https://github.com/javanile/php-imap2

include "inc/php-imap2/vendor/autoload.php";

// Start connection
$mailbox = "{smtp.office365.com:993/imap/ssl/novalidate-cert}";
$token = base64_encode("user=" . $email . "\1auth=Bearer " . $passw . "\1\1");
$imap = @imap2_open($mailbox, $email, $token, OP_XOAUTH2);

// List all mailboxes
if ($imap) {
    $mailboxes = imap2_getmailboxes($imap, $mailbox, '*');
    var_dump($mailboxes);
} else {
    $error = imap2_last_error();
    echo $error;
}

Return

Can not authenticate to IMAP server: A0001 NO AUTHENTICATE failed.

https://github.com/Webklex/php-imap

include "inc/php-imap/vendor/autoload.php";

use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Client;

$cm = new ClientManager($options = []);

$client = $cm->make([
    'host'          => "smtp.office365.com",
    'port'          => 993,
    'encryption'    => 'ssl',
    'validate_cert' => true,
    'username'      => $email,
    'password'      => $passw,
    'protocol'      => 'imap',
    'authentication' => 'oauth',
]);

//Connect to the IMAP Server
$client->connect();

Return

got failure response: NO AUTHENTICATE failed.

PHP Fatal error:  Uncaught Webklex\PHPIMAP\Exceptions\AuthFailedException in C:\inetpub\wwwroot\inc\php-imap\src\Client.php:385
Stack trace:
#0 C:\inetpub\wwwroot\inc\php-imap\src\Client.php(371): Webklex\PHPIMAP\Client->authenticate()
#1 C:\inetpub\wwwroot\test.php(57): Webklex\PHPIMAP\Client->connect()
#2 {main}

Next Webklex\PHPIMAP\Exceptions\ConnectionFailedException: connection setup failed in C:\inetpub\wwwroot\inc\php-imap\src\Client.php:391
Stack trace:
#0 C:\inetpub\wwwroot\inc\php-imap\src\Client.php(371): Webklex\PHPIMAP\Client->authenticate()
#1 C:\inetpub\wwwroot\test.php(57): Webklex\PHPIMAP\Client->connect()
#2 {main}
  thrown in C:\inetpub\wwwroot\inc\php-imap\src\Client.php on line 391

Any help is appreciated