问:
TransientDataAccessResourceException - R2DBC pgdb connection remains in idle in transaction
I have a spring-boot application where using webflux and r2dbc-postgres. I have discovered a strange issue when trying to do some db operations in a flatMap().

Code example:

```<code>@Transactional
public Mono<Void> insertDummyFooBars() {
        return Flux.fromIterable(IntStream.rangeClosed(1, 260).boxed().collect(Collectors.toList()))
                .log()
                .flatMap(i -> this.repository.save(FooBar.builder().foo("test-" + i).build()))
                .log()
                .concatMap(i -> this.repository.findAll())
                .then();
    }
</code>```

It seems like flatMap can process max 256 elements in batches. (Queues.SMALL_BUFFER_SIZE default value is 256). So when I tried to run the code above (with 260 elements) I've got an exception - TransientDataAccessResourceException and the following message:

Cannot exchange messages because the request queue limit is exceeded; nested exception is io.r2dbc.postgresql.client.ReactorNettyClient$RequestQueueException

There is no Releasing R2DBC Connection after this exception. The pgdb connection/session remains in idle in transaction state and the app is not able to run properly when pool max size is reached and all of the connections are in idle in transaction state. I think the connection should be released even if an exception happened or not.

If I use concatMap instead of flatMap it works as expected - no exception, connection released! It's also ok with flatMap when the elements are less than or equal to 256.

Is it possible to force pgdb connection closure? What should I do If I have lot of db operations in flatMap like this? Should I replace all of them with concatMap? Is there a global solution for this?

Versions:
Postgres: 12.6, Spring-boot: 2.7.6

Demo project

LOG:

```<code>2022-12-08 16:32:13.092  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | onNext(256)
2022-12-08 16:32:13.092 DEBUG 17932 --- [actor-tcp-nio-1] o.s.r2dbc.core.DefaultDatabaseClient     : Executing SQL statement [INSERT INTO foo_bar (foo) VALUES ($1)]
2022-12-08 16:32:13.114  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.FlatMap.2                   : onNext(FooBar(id=258, foo=test-1))
2022-12-08 16:32:13.143 DEBUG 17932 --- [actor-tcp-nio-1] o.s.r2dbc.core.DefaultDatabaseClient     : Executing SQL statement [SELECT foo_bar.* FROM foo_bar]
2022-12-08 16:32:13.143  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | request(1)
2022-12-08 16:32:13.143  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | onNext(257)
2022-12-08 16:32:13.144 DEBUG 17932 --- [actor-tcp-nio-1] o.s.r2dbc.core.DefaultDatabaseClient     : Executing SQL statement [INSERT INTO foo_bar (foo) VALUES ($1)]
2022-12-08 16:32:13.149  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | onComplete()
2022-12-08 16:32:13.149  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | cancel()
2022-12-08 16:32:13.160 ERROR 17932 --- [actor-tcp-nio-1] reactor.Flux.FlatMap.2                   : onError(org.springframework.dao.TransientDataAccessResourceException: executeMany; SQL [INSERT INTO foo_bar (foo) VALUES ($1)]; Cannot exchange messages because the request queue limit is exceeded; nested exception is io.r2dbc.postgresql.client.ReactorNettyClient$RequestQueueException: [08006] Cannot exchange messages because the request queue limit is exceeded)
2022-12-08 16:32:13.167 ERROR 17932 --- [actor-tcp-nio-1] reactor.Flux.FlatMap.2                   :

org.springframework.dao.TransientDataAccessResourceException: executeMany; SQL [INSERT INTO foo_bar (foo) VALUES ($1)]; Cannot exchange messages because the request queue limit is exceeded; nested exception is io.r2dbc.postgresql.client.ReactorNettyClient$RequestQueueException: [08006] Cannot exchange messages because the request queue limit is exceeded
    at org.springframework.r2dbc.connection.ConnectionFactoryUtils.convertR2dbcException(ConnectionFactoryUtils.java:215) ~[spring-r2dbc-5.3.24.jar:5.3.24]
    at org.springframework.r2dbc.core.DefaultDatabaseClient.lambda$inConnectionMany$8(DefaultDatabaseClient.java:147) ~[spring-r2dbc-5.3.24.jar:5.3.24]
    at reactor.core.publisher.Flux.lambda$onErrorMap$29(Flux.java:7105) ~[reactor-core-3.4.25.jar:3.4.25]
    at reactor.core.publisher.Flux.lambda$onErrorResume$30(Flux.java:7158) ~[reactor-core-3.4.25.jar:3.4.25]
    at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94) ~[reactor-core-3.4.25.jar:3.4.25]
</code>```

I have tried to change the Queues.SMALL_BUFFER_SIZE, and also tried to add a concurrency value to the flatmap. It works when I reduced the value to 255 but I think it is not a good solution.

Body:
I have a spring-boot application where using webflux and r2dbc-postgres. I have discovered a strange issue when trying to do some db operations in a flatMap().

Code example:

@Transactional
public Mono<Void> insertDummyFooBars() {
        return Flux.fromIterable(IntStream.rangeClosed(1, 260).boxed().collect(Collectors.toList()))
                .log()
                .flatMap(i -> this.repository.save(FooBar.builder().foo("test-" + i).build()))
                .log()
                .concatMap(i -> this.repository.findAll())
                .then();
    }

It seems like flatMap can process max 256 elements in batches. (Queues.SMALL_BUFFER_SIZE default value is 256). So when I tried to run the code above (with 260 elements) I've got an exception - TransientDataAccessResourceException and the following message:

Cannot exchange messages because the request queue limit is exceeded; nested exception is io.r2dbc.postgresql.client.ReactorNettyClient$RequestQueueException

There is no Releasing R2DBC Connection after this exception. The pgdb connection/session remains in idle in transaction state and the app is not able to run properly when pool max size is reached and all of the connections are in idle in transaction state. I think the connection should be released even if an exception happened or not.

If I use concatMap instead of flatMap it works as expected - no exception, connection released! It's also ok with flatMap when the elements are less than or equal to 256.

Is it possible to force pgdb connection closure? What should I do If I have lot of db operations in flatMap like this? Should I replace all of them with concatMap? Is there a global solution for this?

Versions:
Postgres: 12.6, Spring-boot: 2.7.6

Demo project

LOG:

2022-12-08 16:32:13.092  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | onNext(256)
2022-12-08 16:32:13.092 DEBUG 17932 --- [actor-tcp-nio-1] o.s.r2dbc.core.DefaultDatabaseClient     : Executing SQL statement [INSERT INTO foo_bar (foo) VALUES ($1)]
2022-12-08 16:32:13.114  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.FlatMap.2                   : onNext(FooBar(id=258, foo=test-1))
2022-12-08 16:32:13.143 DEBUG 17932 --- [actor-tcp-nio-1] o.s.r2dbc.core.DefaultDatabaseClient     : Executing SQL statement [SELECT foo_bar.* FROM foo_bar]
2022-12-08 16:32:13.143  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | request(1)
2022-12-08 16:32:13.143  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | onNext(257)
2022-12-08 16:32:13.144 DEBUG 17932 --- [actor-tcp-nio-1] o.s.r2dbc.core.DefaultDatabaseClient     : Executing SQL statement [INSERT INTO foo_bar (foo) VALUES ($1)]
2022-12-08 16:32:13.149  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | onComplete()
2022-12-08 16:32:13.149  INFO 17932 --- [actor-tcp-nio-1] reactor.Flux.Iterable.1                  : | cancel()
2022-12-08 16:32:13.160 ERROR 17932 --- [actor-tcp-nio-1] reactor.Flux.FlatMap.2                   : onError(org.springframework.dao.TransientDataAccessResourceException: executeMany; SQL [INSERT INTO foo_bar (foo) VALUES ($1)]; Cannot exchange messages because the request queue limit is exceeded; nested exception is io.r2dbc.postgresql.client.ReactorNettyClient$RequestQueueException: [08006] Cannot exchange messages because the request queue limit is exceeded)
2022-12-08 16:32:13.167 ERROR 17932 --- [actor-tcp-nio-1] reactor.Flux.FlatMap.2                   :

org.springframework.dao.TransientDataAccessResourceException: executeMany; SQL [INSERT INTO foo_bar (foo) VALUES ($1)]; Cannot exchange messages because the request queue limit is exceeded; nested exception is io.r2dbc.postgresql.client.ReactorNettyClient$RequestQueueException: [08006] Cannot exchange messages because the request queue limit is exceeded
    at org.springframework.r2dbc.connection.ConnectionFactoryUtils.convertR2dbcException(ConnectionFactoryUtils.java:215) ~[spring-r2dbc-5.3.24.jar:5.3.24]
    at org.springframework.r2dbc.core.DefaultDatabaseClient.lambda$inConnectionMany$8(DefaultDatabaseClient.java:147) ~[spring-r2dbc-5.3.24.jar:5.3.24]
    at reactor.core.publisher.Flux.lambda$onErrorMap$29(Flux.java:7105) ~[reactor-core-3.4.25.jar:3.4.25]
    at reactor.core.publisher.Flux.lambda$onErrorResume$30(Flux.java:7158) ~[reactor-core-3.4.25.jar:3.4.25]
    at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94) ~[reactor-core-3.4.25.jar:3.4.25]

I have tried to change the Queues.SMALL_BUFFER_SIZE, and also tried to add a concurrency value to the flatmap. It works when I reduced the value to 255 but I think it is not a good solution.


来源: stackexchange

问:
Use the fingerprint browser and Python Selenium to register a Discord account, the account is disabled

I use Python Selenium proxy ip, the fingerprint browser is adspower and I want to automate the creation of Discord account, when I use Selenium to complete the first registration page to fill in the email, password and other information and click the submit button, the robot verification code behind, and the mobile phone number are all filled in manually by myself. But when I reached the last step of verifying my email, I was forced to log out as soon as I logged in, indicating that the account was unavailable, why is this?

I tried changing the proxy IP using a different country's mobile number. I use ActionChains, but I get that the account is disabled, I don't know what happened?
I hope that the Discord account that I can register through the code will not be disabled

ContentLicense: CC BY-SA 4.0


问:
selenium driver error to set value for date type of input using send_keys
for example,

```<code>end_date = driver.find_element(By.XPATH, "//input[@id='end-date']")
#end_date.send_keys('2023-11-18')  #correct -> 2023-11-8
end_date.send_keys('2023-01-18')  #error -> 2023-11-8
</code>```

it change 0118 to 118(i.e. 11-08) automatic(bug), when coding in opensea's list (where date is need)

How should I do? Thx

I try
end_date.send_keys('2023-11-18')  #correct -> 2023-11-8
It do well.
But
end_date.send_keys('2023-01-18')  #error -> 2023-11-8
Wrong.

Body:
for example,

end_date = driver.find_element(By.XPATH, "//input[@id='end-date']")
#end_date.send_keys('2023-11-18')  #correct -> 2023-11-8
end_date.send_keys('2023-01-18')  #error -> 2023-11-8

it change 0118 to 118(i.e. 11-08) automatic(bug), when coding in opensea's list (where date is need)

How should I do? Thx

I try
end_date.send_keys('2023-11-18')  #correct -> 2023-11-8
It do well.
But
end_date.send_keys('2023-01-18')  #error -> 2023-11-8
Wrong.


问:
How can I fix "'R_Realloc' could not re-allocate memory" in R?
I've been trying to do stm in R, with codes like,

```<code>`kresult <- searchK(myout$documents, myout$vocab,
                   K=20:25,
                   prevalence = ~ created_at,
                   data=myout$meta,
)`
</code>```

then I face to the error.

```<code>Beginning Spectral Initialization
     Calculating the gram matrix...
     Finding anchor words...
    ......................
     Recovering initialization...
    .................................
Initialization complete.
.......................................................................
Completed E-Step (15 seconds).
Error in .sortCsparse(.Call(dtCMatrix_sparse_solve, a, b)) :
  'R_Realloc' could not re-allocate memory (2632458240 bytes)
</code>```

Please tell me how can I fix this problem...
Thanks.

I closed every other applications and rebooted but there was no change.

Body:
I've been trying to do stm in R, with codes like,

`kresult <- searchK(myout$documents, myout$vocab,
                   K=20:25,
                   prevalence = ~ created_at,
                   data=myout$meta,
)`

then I face to the error.

Beginning Spectral Initialization
     Calculating the gram matrix...
     Finding anchor words...
    ......................
     Recovering initialization...
    .................................
Initialization complete.
.......................................................................
Completed E-Step (15 seconds).
Error in .sortCsparse(.Call(dtCMatrix_sparse_solve, a, b)) :
  'R_Realloc' could not re-allocate memory (2632458240 bytes)

Please tell me how can I fix this problem...
Thanks.

I closed every other applications and rebooted but there was no change.


问:
How do I draw this shader on a plane in WebGL
I am a complete newbie to WebGl now the thing is I want to draw this  shader on my webpage . But I am unable to figure how to do it, can anyone help me?

I tried to Create  a custom shader in Three.js but it is working.


问:
FastAPI, ASGI middleware, sync routes & thread-local data
I've been migrating an existing WSGI app to FastAPI. I'm having trouble fully understanding the different dynamics of the two frameworks, and hope you can shed some light conceptually.

At the moment I have the following setup, largely inspired by existing app:

ASGI middleware that catches exceptions

ASGI middleware that parses request user credentials and stores result in a threading.local() object

ASGI middleware that opens database session and catches database exceptions in subsequent logic

Simple (async) route handler for legacy routes, which translates Starlette request args into format accepted by former app, then calling the route synchronously.

All legacy endpoints "work". Meaning: results were functionally correct in a unit test setting and simple localhost testing. I noticed something was amiss when I added a 'native' sync route: it was executed in a separate (AnyIO) thread from the middleware, and therefore it did not have the user credentials it parsed.

Some initial questions, feel free to add/tell me if I'm asking the wrong question:

Currently sync legacy routes (with database I/O) are run in an async route handler. I assume that's a bad idea from a performance standpoint?

Is threading.local() even local to individual async routes? Is there an 'intended' way in FastAPI/Starlette for ASGI middleware to provide data to the function that ultimately executes the request?

FastAPI's database example uses a dependency with a generator to open the database session. When trying this setup, I noticed database issues upon commit (done by the same dependency after the yield) would still result in an OK response sent to the user. Could this be correct? If so, must I explicitly commit within every route function (or wrap it in a decorator that does so) instead of the dependency?

I noticed FastAPI's add_exception_handler() doesn't catch exceptions in ASGI middleware. Is that correct?

Which other questions should I be asking here?

Insights are welcome - thanks :)


问:
Enabling "justMyCode" in Visual Studio Code for React JS Code Debugging
I want to enable "justMyCode" option in Visual Studio Code to debug just my code in React. Currently when I debug debugger steps also in files like;

```<code>fmkadmapgofadopljbjfkapdkoienihi/build/injectGlobalHook.js
\\node_modules\\scheduler\\cjs\\scheduler.development.js
\\node_modules\\lottie-web\\build\\player\\lottie.js
</code>```

ect...

I have already tried;

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "React",
            "type": "chrome",
            "request": "launch",
            "justMyCode":true,

            "url": "http://localhost:5173",
            "webRoot": "${workspaceFolder}",
            "sourceMapPathOverrides":
                {
                    "webpack:///src*": "${webroot}/*",
                },
            ]
        },

    ]
}
</code>```

This throws "Property justMyCode is not allowed." error.

Then I tried;

```<code>
{
"version": "0.2.0",
"configurations": \[
{
"name": "React",
"type": "chrome",
"request": "launch",

            "url": "http://localhost:5173",
            "webRoot": "${workspaceFolder}",
            "sourceMapPathOverrides":
                {
                    "webpack:///src*": "${webroot}/*",
                },
            "skipFiles": [

                "${workspaceFolder}/bvars/<node_internals>/**",
                "${workspaceFolder}/bvars/node_modules/**",
            ]
        },

    ]

}

</code>```

This seems to skip node files but this time an;

```<code><eval>\VM4697589
</code>```

file appeared as well as;

```<code>\src\client\client.ts
fmkadmapgofadopljbjfkapdkoienihi/build/injectGlobalHook.js
</code>```

files ect...

How can I bypass all these system files and debug step only my code ?
Also is there a way to even not open any external files at all (including my own files) and debug only current file ?

I am quite new so sorry if these are too basic. Thank you in advance...

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

Body:
I want to enable "justMyCode" option in Visual Studio Code to debug just my code in React. Currently when I debug debugger steps also in files like;

fmkadmapgofadopljbjfkapdkoienihi/build/injectGlobalHook.js
\\node_modules\\scheduler\\cjs\\scheduler.development.js
\\node_modules\\lottie-web\\build\\player\\lottie.js

ect...

I have already tried;

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "React",
            "type": "chrome",
            "request": "launch",
            "justMyCode":true,

            "url": "http://localhost:5173",
            "webRoot": "${workspaceFolder}",
            "sourceMapPathOverrides":
                {
                    "webpack:///src*": "${webroot}/*",
                },
            ]
        },

    ]
}

This throws "Property justMyCode is not allowed." error.

Then I tried;

{
"version": "0.2.0",
"configurations": \[
{
"name": "React",
"type": "chrome",
"request": "launch",

            "url": "http://localhost:5173",
            "webRoot": "${workspaceFolder}",
            "sourceMapPathOverrides":
                {
                    "webpack:///src*": "${webroot}/*",
                },
            "skipFiles": [

                "${workspaceFolder}/bvars/<node_internals>/**",
                "${workspaceFolder}/bvars/node_modules/**",
            ]
        },

    ]

}

This seems to skip node files but this time an;

<eval>\VM4697589

file appeared as well as;

\src\client\client.ts
fmkadmapgofadopljbjfkapdkoienihi/build/injectGlobalHook.js

files ect...

How can I bypass all these system files and debug step only my code ?
Also is there a way to even not open any external files at all (including my own files) and debug only current file ?

I am quite new so sorry if these are too basic. Thank you in advance...


问:
ios screen on/off event
Audio is turned off even though visibilityChange event listener is not registered in ios. Are there any other events?

```<code>var hidden, visibilityChange;
if (typeof document.hidden !== "undefined")
{
      hidden = "hidden";
      visibilityChange = "visibilitychange";
}
else if (typeof document.mozHidden !== "undefined")
{
      hidden = "mozHidden";
      visibilityChange = "mozvisibilitychange";
}
else if (typeof document.msHidden !== "undefined")
{
      hidden = "msHidden";
      visibilityChange = "msvisibilitychange";
}
else if (typeof document.webkitHidden !== "undefined")
{
      hidden = "webkitHidden";
      visibilityChange = "webkitvisibilitychange";
}
//document.addEventListener(visibilityChange, SnlPixiMgr.VisibilityChange, false );
</code>```
```<code>arguments.callee.VisibilityChange = function()
{
    if(document.hidden)
    {
        for( var i=0; i<SnlPixiMgr.m_HiddenEvent.length; i++ )
        {
            SnlPixiMgr.m_HiddenEvent[i]();
        }
    }
    else
    {
        for( var i=0; i<SnlPixiMgr.m_VisibleEvent.length; i++ )
        {
            SnlPixiMgr.m_VisibleEvent[i]();
        }
    }
}
</code>```

I don't want the BGM to be cut off even if the screen of ios is turned off.

Title: ios screen on/off event

Body:
Audio is turned off even though visibilityChange event listener is not registered in ios. Are there any other events?

var hidden, visibilityChange;
if (typeof document.hidden !== "undefined")
{
      hidden = "hidden";
      visibilityChange = "visibilitychange";
}
else if (typeof document.mozHidden !== "undefined")
{
      hidden = "mozHidden";
      visibilityChange = "mozvisibilitychange";
}
else if (typeof document.msHidden !== "undefined")
{
      hidden = "msHidden";
      visibilityChange = "msvisibilitychange";
}
else if (typeof document.webkitHidden !== "undefined")
{
      hidden = "webkitHidden";
      visibilityChange = "webkitvisibilitychange";
}
//document.addEventListener(visibilityChange, SnlPixiMgr.VisibilityChange, false );

arguments.callee.VisibilityChange = function()
{
    if(document.hidden)
    {
        for( var i=0; i<SnlPixiMgr.m_HiddenEvent.length; i++ )
        {
            SnlPixiMgr.m_HiddenEvent[i]();
        }
    }
    else
    {
        for( var i=0; i<SnlPixiMgr.m_VisibleEvent.length; i++ )
        {
            SnlPixiMgr.m_VisibleEvent[i]();
        }
    }
}

I don't want the BGM to be cut off even if the screen of ios is turned off.


问:
Why is the length different?
//delphi 7 procedure TForm1.Button1Click(Sender: TObject); Var strList: TStringList; strLength: String; begin strList:= TStringList.Create; strList.Text:= 'example'; // 7 characters  strLength:= IntToStr(Length(strList.Text)); Showmessage(strLength); //  9 characters strList.Free; end;
strList.Text:= 'example'; where the length is 7 characters
Showmessage(strLength); why am i getting the 9 character result?

```<code>Thank you in advance to those who are interested.
</code>```

Title: Why is the length different?

Body:
//delphi 7 procedure TForm1.Button1Click(Sender: TObject); Var strList: TStringList; strLength: String; begin strList:= TStringList.Create; strList.Text:= 'example'; // 7 characters  strLength:= IntToStr(Length(strList.Text)); Showmessage(strLength); //  9 characters strList.Free; end;
strList.Text:= 'example'; where the length is 7 characters
Showmessage(strLength); why am i getting the 9 character result?

Thank you in advance to those who are interested.


问:
Would move-constructors make Pin/Unpin unnecessary?
Pin/Unpin was introduced as a prerequisite to adding async/await support to Rust. It allows safely polling a future that potentially has internal refererences to it's own state.

However, wouldn't introducing move-constructors to the language be a simpler solution? This way the future could be moved freely in memory after being polled, all the internal references being fixed by the move-constructor. For example:

async fn foo { /* ... */ }

async fn bar {
    let future = foo();
    poll_fn(|cx| future.poll(cx)).await;
    // Now `future` might have internal references.
    let boxed_future = Box::new(future);
    // The future was moved to the heap, but the move-constructor
    // took care of adjusting the internal references, so we can
    // safely poll the future again.
    boxed_future.await;
}
```

Surely this approach was contemplated, but ultimately rejected. Why?

Body:
Pin/Unpin was introduced as a prerequisite to adding async/await support to Rust. It allows safely polling a future that potentially has internal refererences to it's own state.

However, wouldn't introducing move-constructors to the language be a simpler solution? This way the future could be moved freely in memory after being polled, all the internal references being fixed by the move-constructor. For example:

async fn foo { /* ... */ }

async fn bar {
    let future = foo();
    poll_fn(|cx| future.poll(cx)).await;
    // Now `future` might have internal references.
    let boxed_future = Box::new(future);
    // The future was moved to the heap, but the move-constructor
    // took care of adjusting the internal references, so we can
    // safely poll the future again.
    boxed_future.await;
}

Surely this approach was contemplated, but ultimately rejected. Why?


问:
Change structure of an array Javascript
I am using Highcharts to create multiple bars on a chart and I get the data from an Ajax call.

What I encounter is linked to the format of the array I get.

What I am doing to create the array is :

```<code>elements = [];

// AJAX request here ($.getJSON(...))

    $.each(data, function(key, value) {
        elements.push(value.item1);
    }

// End of $.getJSON
</code>```

When using this method, Highcharts does not work properly, I know I can add the data another way but I would still like to solve this problem.

Here is what happens when I console.log(elements) :

```<code>Array []

0: 0

1: 0

2: 0

3: 0

4: 0

5: 5

6: 0

length: 7

<prototype>: Array []
</code>```

I can get the structure I want by writing var elements = [0, 0, 0, 0, 5, 0];

When I console.log(elements) I get this structure :

```<code>Array(6) [ 0, 0, 0, 0, 5, 0 ]

0: 0

1: 0

2: 0

3: 0

4: 5

5: 0

length: 6

<prototype>: Array []
</code>```

To me both arrays are similar but there's a difference on the first line of the console.log().

I don't really understand what is causing this.

EDIT:
After the Ajax and the $.each, I create the chart, but when using an array created with

```<code>elements.push()
</code>```

the chart is not created.

My problem does not come from the fact that console.log displays different things, it comes from the fact that Highcharts does not "understand" the array I am giving it.

Title: Change structure of an array Javascript

Body:
I am using Highcharts to create multiple bars on a chart and I get the data from an Ajax call.

What I encounter is linked to the format of the array I get.

What I am doing to create the array is :

elements = [];

// AJAX request here ($.getJSON(...))

    $.each(data, function(key, value) {
        elements.push(value.item1);
    }

// End of $.getJSON

When using this method, Highcharts does not work properly, I know I can add the data another way but I would still like to solve this problem.

Here is what happens when I console.log(elements) :

Array []

0: 0

1: 0

2: 0

3: 0

4: 0

5: 5

6: 0

length: 7

<prototype>: Array []

I can get the structure I want by writing var elements = [0, 0, 0, 0, 5, 0];

When I console.log(elements) I get this structure :

Array(6) [ 0, 0, 0, 0, 5, 0 ]

0: 0

1: 0

2: 0

3: 0

4: 5

5: 0

length: 6

<prototype>: Array []

To me both arrays are similar but there's a difference on the first line of the console.log().

I don't really understand what is causing this.

EDIT:
After the Ajax and the $.each, I create the chart, but when using an array created with

elements.push()

the chart is not created.

My problem does not come from the fact that console.log displays different things, it comes from the fact that Highcharts does not "understand" the array I am giving it.


问:
I am trying to write GraphQL schema for the first time for creating an API for my project but I am getting error
I am trying to write a Graphql schema for creating API.
Here is the GraphQL schema :

```<code>input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } # FOR TESTING ONLY!

type User @model {
  id: ID!
  username: String!
  posts: [Post] @connection(keyName:"byUser", fields: ["id"])

}

type Post @model @key( name: "byUser",fields: ["userID"] ){
  id: ID!
  videoUri: String!
  description:String!
  userID: ID!
  user: User @connection(fields:["userID"])
  songID: ID!
  song:Song @connection(fields:["songID"])
  }

type Song @model {
  id: ID!
  name: String!
  imageUri: String!
}
</code>```

I am trying to write a GraphQL schema for creating an API for my project and later after doing amplify push in my terminal I am getting this error "Your GraphQL Schema is using "@connection", "@key" directives from an older version of the GraphQL Transformer."
and after doing amplify console api  I am getting this error on the AWS amplify console.

Please correct me where I am wrong as I am new to GraphQL and AWS. Thanks

Body:
I am trying to write a Graphql schema for creating API.
Here is the GraphQL schema :

input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } # FOR TESTING ONLY!

type User @model {
  id: ID!
  username: String!
  posts: [Post] @connection(keyName:"byUser", fields: ["id"])

}

type Post @model @key( name: "byUser",fields: ["userID"] ){
  id: ID!
  videoUri: String!
  description:String!
  userID: ID!
  user: User @connection(fields:["userID"])
  songID: ID!
  song:Song @connection(fields:["songID"])
  }

type Song @model {
  id: ID!
  name: String!
  imageUri: String!
}

I am trying to write a GraphQL schema for creating an API for my project and later after doing amplify push in my terminal I am getting this error "Your GraphQL Schema is using "@connection", "@key" directives from an older version of the GraphQL Transformer."
and after doing amplify console api  I am getting this error on the AWS amplify console.

Please correct me where I am wrong as I am new to GraphQL and AWS. Thanks


问:
Custom C++ header error undefined reference to `ClientData::ClientData
I am Starting learning C++ from scratch, and now I am trying to import this custom header to one of my cpp. Its a pretty basic class.

ClientData.h

```<code>#ifndef CLIENTDATA_H
#define CLIENTDATA_H

#include <string>
using namespace std;

class ClientData{
public:
    ClientData(int=0, const string & = "", const string & = "", double = 0);

    void setAccountNumber(int);
    int getAccountNumber() const;

    void setLastName(const string &);
    string getLastName() const;

    void setFirstName(const string &);
    string getFirstName() const;

    void setBalance(double);
    double getBalance() const;

private:
    int accountNumber;
    char lastName[15];
    char firstName[10];
    double balance;
};

#endif
</code>```

tutor.cpp

```<code>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include "ClientData.h"

using namespace std;

int main(){
  ClientData blankClient;
  return 0;
}
</code>```

I get an error of: undefined reference to ClientData::ClientData(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, double)

For an extra info: I am using MinGW Compiler, and I also name the header ClientData.h placed under the include folder of MinGW Compiler directory. I run this code under sublime text.

What should I do to solve this? Thankyou

Body:
I am Starting learning C++ from scratch, and now I am trying to import this custom header to one of my cpp. Its a pretty basic class.

ClientData.h

#ifndef CLIENTDATA_H
#define CLIENTDATA_H

#include <string>
using namespace std;

class ClientData{
public:
    ClientData(int=0, const string & = "", const string & = "", double = 0);

    void setAccountNumber(int);
    int getAccountNumber() const;

    void setLastName(const string &);
    string getLastName() const;

    void setFirstName(const string &);
    string getFirstName() const;

    void setBalance(double);
    double getBalance() const;

private:
    int accountNumber;
    char lastName[15];
    char firstName[10];
    double balance;
};

#endif

tutor.cpp

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include "ClientData.h"

using namespace std;

int main(){
  ClientData blankClient;
  return 0;
}

I get an error of: undefined reference to ClientData::ClientData(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, double)

For an extra info: I am using MinGW Compiler, and I also name the header ClientData.h placed under the include folder of MinGW Compiler directory. I run this code under sublime text.

What should I do to solve this? Thankyou


问:
echarts: How to get outward facing labels with polar bar\scatter chart
I want to have a circular chart, either bar or scatter, similar to this one in the examples ..

but I want the labels (ie. the 10p, 11p, 12p) to be pointing outwards similar to how it is on this tree chart, also from the examples,

does anyone know how to do this? thanks v much in advance for any help.


问:
Why does creating an object when calling DB using Entity Framework result in "instances of abstract classes cannot be created" error?
I have an abstract class OrderDetail and a class Order with this definition:

```<code>public class Order
{
    public OrderDetail Detail { get; set; }
}
</code>```

I'm trying to query DB and get a list of Orders, but get "instances of abstract classes cannot be created" error. But if I test creating new Orders directly then there would be no problem.

Here's what I've tested so far:

Pass cases

```<code>var success1 = new Order();

var success2 = new Order() { Detail = null };

var success3 = db.Invoice.Select(_ => new Order()).ToList();
</code>```

Fail case

```<code>var fail = db.Invoice.Select(_ => new Order() { Detail = null }).ToList();
</code>```

I'm using .NET Framework 4.8 and Entity Framework 6.1.3.

Body:
I have an abstract class OrderDetail and a class Order with this definition:

public class Order
{
    public OrderDetail Detail { get; set; }
}

I'm trying to query DB and get a list of Orders, but get "instances of abstract classes cannot be created" error. But if I test creating new Orders directly then there would be no problem.

Here's what I've tested so far:

Pass cases

var success1 = new Order();

var success2 = new Order() { Detail = null };

var success3 = db.Invoice.Select(_ => new Order()).ToList();

Fail case

var fail = db.Invoice.Select(_ => new Order() { Detail = null }).ToList();

I'm using .NET Framework 4.8 and Entity Framework 6.1.3.


问:
How to update color axis values for google geo chart?
I am trying to draw map with dynamic values and able to do so but Color Axis bar values are not updating

this is my geoChart code

```<code>  public geoChart: GoogleChartInterface = {
    chartType: 'GeoChart',
    dataTable:  this.states_data,
    options: {
      region: 'IN', // INDIA
      // colorAxis: {colors: ['#00F919', '#0FFFE4', '#1FA20F','#156930','#033E3B']},
       resolution: 'provinces',
       backgroundColor: '#00000',
      // datalessRegionColor: '#00000',
      // defaultColor: '#00000',
       'height': 400,
      // is3D: true
    }
  };
</code>```

This is how I want to update this bar values

how do I update highlighted image bar values ?

Able to draw map with dynamic values but updating color bar values

tried below code for drawing map

```<code>  let ccComponent = this.geoChart.component;
        if(ccComponent){
        ccComponent.draw();
        }
</code>```

Body:
I am trying to draw map with dynamic values and able to do so but Color Axis bar values are not updating

this is my geoChart code

  public geoChart: GoogleChartInterface = {
    chartType: 'GeoChart',
    dataTable:  this.states_data,
    options: {
      region: 'IN', // INDIA
      // colorAxis: {colors: ['#00F919', '#0FFFE4', '#1FA20F','#156930','#033E3B']},
       resolution: 'provinces',
       backgroundColor: '#00000',
      // datalessRegionColor: '#00000',
      // defaultColor: '#00000',
       'height': 400,
      // is3D: true
    }
  };

This is how I want to update this bar values

how do I update highlighted image bar values ?

Able to draw map with dynamic values but updating color bar values

tried below code for drawing map

  let ccComponent = this.geoChart.component;
        if(ccComponent){
        ccComponent.draw();
        }


问:
"Signature not yet current" in AWS signature 4 - WSO2 class mediator
I am currently trying to list all users using AWS IAM api and facing some difficulties. When after invoking the API through the WSO2 micro integrator it shows following error,

XML Response from AWS

I have set the time zone to UTC in the deployed docker pod. To generate the signature I had to implement a custom class mediator and used the AWS recommended java implementation to generate the key.

```<code>package test;

import java.util.Calendar;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class IamConfigMediator extends AbstractMediator {

    private static final String ACCESS_KEY = "XXXX";
    private static final String SECRET_KEY = "XXXXXX";
    private static final String region = "us-east-1";
    private static final String serviceName = "iam";
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    public boolean mediate(MessageContext context) {
        log.info("[IamConfigMediator] Generating SIGNATURE_HEADER and EXPIRE_TIME ##############################");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR_OF_DAY, 24);
        long time = cal.getTimeInMillis();
        String expireTime = formatTimestamp(time);

        context.setProperty("EXPIRE_TIME", expireTime);

        try {
            byte[] signature = getSignatureKey(SECRET_KEY, expireTime, region, serviceName);
            String header = "AWS4-HMAC-SHA256 Credential=" + ACCESS_KEY + "/" + expireTime + "/" + region + "/" + serviceName + "/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + bytesToHex(signature);
            context.setProperty("SIGNATURE_HEADER", header);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    static byte[] HmacSHA256(String data, byte[] key) throws Exception {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes("UTF-8"));
    }

    static byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
        byte[] kSecret = ("AWS4" + key).getBytes("UTF-8");
        byte[] kDate = HmacSHA256(dateStamp, kSecret);
        byte[] kRegion = HmacSHA256(regionName, kDate);
        byte[] kService = HmacSHA256(serviceName, kRegion);
        byte[] kSigning = HmacSHA256("aws4_request", kService);
        return kSigning;
    }

    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }

    private static final DateTimeFormatter dateFormatter = DateTimeFormat
        .forPattern("yyyyMMdd").withZoneUTC();

    private static final DateTimeFormatter timeFormatter = DateTimeFormat
        .forPattern("yyyyMMdd'T'HHmmss'Z'").withZoneUTC();

    public static String formatTimestamp(long timeMilli) {
        return timeFormatter.print(timeMilli);
    }

}

</code>```

Above implementation was used to generate the signature header("SIGNATURE_HEADER").

Body:
I am currently trying to list all users using AWS IAM api and facing some difficulties. When after invoking the API through the WSO2 micro integrator it shows following error,

XML Response from AWS

I have set the time zone to UTC in the deployed docker pod. To generate the signature I had to implement a custom class mediator and used the AWS recommended java implementation to generate the key.

package test;

import java.util.Calendar;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class IamConfigMediator extends AbstractMediator {

    private static final String ACCESS_KEY = "XXXX";
    private static final String SECRET_KEY = "XXXXXX";
    private static final String region = "us-east-1";
    private static final String serviceName = "iam";
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    public boolean mediate(MessageContext context) {
        log.info("[IamConfigMediator] Generating SIGNATURE_HEADER and EXPIRE_TIME ##############################");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR_OF_DAY, 24);
        long time = cal.getTimeInMillis();
        String expireTime = formatTimestamp(time);

        context.setProperty("EXPIRE_TIME", expireTime);

        try {
            byte[] signature = getSignatureKey(SECRET_KEY, expireTime, region, serviceName);
            String header = "AWS4-HMAC-SHA256 Credential=" + ACCESS_KEY + "/" + expireTime + "/" + region + "/" + serviceName + "/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + bytesToHex(signature);
            context.setProperty("SIGNATURE_HEADER", header);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    static byte[] HmacSHA256(String data, byte[] key) throws Exception {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes("UTF-8"));
    }

    static byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
        byte[] kSecret = ("AWS4" + key).getBytes("UTF-8");
        byte[] kDate = HmacSHA256(dateStamp, kSecret);
        byte[] kRegion = HmacSHA256(regionName, kDate);
        byte[] kService = HmacSHA256(serviceName, kRegion);
        byte[] kSigning = HmacSHA256("aws4_request", kService);
        return kSigning;
    }

    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }

    private static final DateTimeFormatter dateFormatter = DateTimeFormat
        .forPattern("yyyyMMdd").withZoneUTC();

    private static final DateTimeFormatter timeFormatter = DateTimeFormat
        .forPattern("yyyyMMdd'T'HHmmss'Z'").withZoneUTC();

    public static String formatTimestamp(long timeMilli) {
        return timeFormatter.print(timeMilli);
    }

}

Above implementation was used to generate the signature header("SIGNATURE_HEADER").


问:
Conflict when overwriting hadoop S3 configuration on Spark
I have two MinIO storages as follow

```<code>version: "3.9"
services:
  minio:
    image: quay.io/minio/minio:latest
    ports:
      - "9000:9000"
      - "9001:9001"
    environment:
      MINIO_ROOT_USER: "user"
      MINIO_ROOT_PASSWORD: "pwd"
    volumes:
      - ./data/minio:/data # For keeping actual data
    command: server /data --console-address ":9001"

  minio2:
    image: quay.io/minio/minio:latest
    ports:
      - "9002:9000"
      - "9003:9001"
    environment:
      MINIO_ROOT_USER: "user2"
      MINIO_ROOT_PASSWORD: "pwd2"
    volumes:
      - ./data/minio2:/data # For keeping actual data
    command: server /data --console-address ":9001"
</code>```

But when I try to read from the first MinIO and write to the second MinIO

import org.apache.spark.sql.SparkSession

object Main extends App {

  // Initialization
  val spark = SparkSession
    .builder()
    .appName("O2SS_SparkServer")
    .master("local[*]")
    .config("spark.ui.port", "4040")
    .getOrCreate()
  spark.sparkContext.setLogLevel("WARN")

  // Read Csv from S3_1
  val endpoint  = "http://127.0.0.1:9000"
  val accessKey = "user"
  val secretKey = "pwd"
  val bucket    = "test_bucket"
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket.endpoint", endpoint)
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket.access.key", accessKey)
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket.secret.key", secretKey)
  val input     = spark.read.csv(s"s3a://$bucket/<someFile>.csv")

  // Write Csv to S3_2
  val endpoint2  = "http://127.0.0.1:9002"
  val accessKey2 = "user2"
  val secretKey2 = "pwd2"
  val bucket2    = "test_bucket"
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket2.endpoint", endpoint2)
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket2.access.key", accessKey2)
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket2.secret.key", secretKey2)
  input.write.parquet(s"s3a://$bucket2/IfNotInS3_2_THENBUG.parquet")

}
```

It writes into the first MinIO instead of the second

Remark:

I know about the "per Bucket" settings and how S3 bucket naming are unique. And so using S3 instead I will not encounter the problem => This is not the subject

Currently on Spark 3.3.1

Body:
I have two MinIO storages as follow

version: "3.9"
services:
  minio:
    image: quay.io/minio/minio:latest
    ports:
      - "9000:9000"
      - "9001:9001"
    environment:
      MINIO_ROOT_USER: "user"
      MINIO_ROOT_PASSWORD: "pwd"
    volumes:
      - ./data/minio:/data # For keeping actual data
    command: server /data --console-address ":9001"

  minio2:
    image: quay.io/minio/minio:latest
    ports:
      - "9002:9000"
      - "9003:9001"
    environment:
      MINIO_ROOT_USER: "user2"
      MINIO_ROOT_PASSWORD: "pwd2"
    volumes:
      - ./data/minio2:/data # For keeping actual data
    command: server /data --console-address ":9001"

But when I try to read from the first MinIO and write to the second MinIO

import org.apache.spark.sql.SparkSession

object Main extends App {

  // Initialization
  val spark = SparkSession
    .builder()
    .appName("O2SS_SparkServer")
    .master("local[*]")
    .config("spark.ui.port", "4040")
    .getOrCreate()
  spark.sparkContext.setLogLevel("WARN")

  // Read Csv from S3_1
  val endpoint  = "http://127.0.0.1:9000"
  val accessKey = "user"
  val secretKey = "pwd"
  val bucket    = "test_bucket"
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket.endpoint", endpoint)
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket.access.key", accessKey)
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket.secret.key", secretKey)
  val input     = spark.read.csv(s"s3a://$bucket/<someFile>.csv")

  // Write Csv to S3_2
  val endpoint2  = "http://127.0.0.1:9002"
  val accessKey2 = "user2"
  val secretKey2 = "pwd2"
  val bucket2    = "test_bucket"
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket2.endpoint", endpoint2)
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket2.access.key", accessKey2)
  spark.sparkContext.hadoopConfiguration.set(s"fs.s3a.bucket.$bucket2.secret.key", secretKey2)
  input.write.parquet(s"s3a://$bucket2/IfNotInS3_2_THENBUG.parquet")

}

It writes into the first MinIO instead of the second

Remark:

I know about the "per Bucket" settings and how S3 bucket naming are unique. And so using S3 instead I will not encounter the problem => This is not the subject

Currently on Spark 3.3.1


问:
Why doesn't it show up after I change the offscreen size?
I'm trying to write examples in webgl where the implementation of fbo does not render successfully if the original size is changed.

The original size of OFFSCREEN_WIDTH and OFFSCREEN_HEIGHT is 256 pixels,When I  change the value nothing is rendered on the screen, I'd like to know why this is？

after I changed the size, I tried to render only the textures in the fbo on the screen and it was able to display.

Effect
and code:

// FramebufferObject.js (c) matsuda and kanda
// Vertex shader program
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'attribute vec2 a_TexCoord;\n' +
  'uniform mat4 u_MvpMatrix;\n' +
  'varying vec2 v_TexCoord;\n' +
  'void main() {\n' +
  '  gl_Position = u_MvpMatrix * a_Position;\n' +
  '  v_TexCoord = a_TexCoord;\n' +
  '}\n';

// Fragment shader program
var FSHADER_SOURCE =
  '#ifdef GL_ES\n' +
  'precision mediump float;\n' +
  '#endif\n' +
  'uniform sampler2D u_Sampler;\n' +
  'varying vec2 v_TexCoord;\n' +
  'void main() {\n' +
  '  gl_FragColor = texture2D(u_Sampler, v_TexCoord);\n' +
  '}\n';

// Size of off screen
var OFFSCREEN_WIDTH = 256;
var OFFSCREEN_HEIGHT = 256;

function main() {
  // Retrieve <canvas> element
  var canvas = document.getElementById('webgl');

  // Get the rendering context for WebGL
  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log('Failed to get the rendering context for WebGL');
    return;
  }

  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }

  // Get the storage location of attribute variables and uniform variables
  var program = gl.program; // Get program object
  program.a_Position = gl.getAttribLocation(program, 'a_Position');
  program.a_TexCoord = gl.getAttribLocation(program, 'a_TexCoord');
  program.u_MvpMatrix = gl.getUniformLocation(program, 'u_MvpMatrix');
  if (program.a_Position < 0 || program.a_TexCoord < 0 || !program.u_MvpMatrix) {
    console.log('Failed to get the storage location of a_Position, a_TexCoord, u_MvpMatrix');
    return;
  }

  // Set the vertex information
  var cube = initVertexBuffersForCube(gl);
  var plane = initVertexBuffersForPlane(gl);
  if (!cube || !plane) {
    console.log('Failed to set the vertex information');
    return;
  }

  // Set texture
  var texture = initTextures(gl);
  if (!texture) {
    console.log('Failed to intialize the texture.');
    return;
  }

  // Initialize framebuffer object (FBO)
  var fbo = initFramebufferObject(gl);
  if (!fbo) {
    console.log('Failed to intialize the framebuffer object (FBO)');
    return;
  }

  // Enable depth test
  gl.enable(gl.DEPTH_TEST);   //  gl.enable(gl.CULL_FACE);

  var viewProjMatrix = new Matrix4();   // Prepare view projection matrix for color buffer
  viewProjMatrix.setPerspective(30, canvas.width/canvas.height, 1.0, 100.0);
  viewProjMatrix.lookAt(0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

  var viewProjMatrixFBO = new Matrix4();   // Prepare view projection matrix for FBO
  viewProjMatrixFBO.setPerspective(30.0, OFFSCREEN_WIDTH/OFFSCREEN_HEIGHT, 1.0, 100.0);
  viewProjMatrixFBO.lookAt(0.0, 2.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

  // Start drawing
  var currentAngle = 0.0; // Current rotation angle (degrees)
  var tick = function() {
    currentAngle = animate(currentAngle);  // Update current rotation angle
    draw(gl, canvas, fbo, plane, cube, currentAngle, texture, viewProjMatrix, viewProjMatrixFBO);
    window.requestAnimationFrame(tick, canvas);
  };
  tick();
}

function initVertexBuffersForCube(gl) {
  // Create a cube
  //    v6----- v5
  //   /|      /|
  //  v1------v0|
  //  | |     | |
  //  | |v7---|-|v4
  //  |/      |/
  //  v2------v3

  // Vertex coordinates
  var vertices = new Float32Array([
     1.0, 1.0, 1.0,  -1.0, 1.0, 1.0,  -1.0,-1.0, 1.0,   1.0,-1.0, 1.0,    // v0-v1-v2-v3 front
     1.0, 1.0, 1.0,   1.0,-1.0, 1.0,   1.0,-1.0,-1.0,   1.0, 1.0,-1.0,    // v0-v3-v4-v5 right
     1.0, 1.0, 1.0,   1.0, 1.0,-1.0,  -1.0, 1.0,-1.0,  -1.0, 1.0, 1.0,    // v0-v5-v6-v1 up
    -1.0, 1.0, 1.0,  -1.0, 1.0,-1.0,  -1.0,-1.0,-1.0,  -1.0,-1.0, 1.0,    // v1-v6-v7-v2 left
    -1.0,-1.0,-1.0,   1.0,-1.0,-1.0,   1.0,-1.0, 1.0,  -1.0,-1.0, 1.0,    // v7-v4-v3-v2 down
     1.0,-1.0,-1.0,  -1.0,-1.0,-1.0,  -1.0, 1.0,-1.0,   1.0, 1.0,-1.0     // v4-v7-v6-v5 back
  ]);

  // Texture coordinates
  var texCoords = new Float32Array([
      1.0, 1.0,   0.0, 1.0,   0.0, 0.0,   1.0, 0.0,    // v0-v1-v2-v3 front
      0.0, 1.0,   0.0, 0.0,   1.0, 0.0,   1.0, 1.0,    // v0-v3-v4-v5 right
      1.0, 0.0,   1.0, 1.0,   0.0, 1.0,   0.0, 0.0,    // v0-v5-v6-v1 up
      1.0, 1.0,   0.0, 1.0,   0.0, 0.0,   1.0, 0.0,    // v1-v6-v7-v2 left
      0.0, 0.0,   1.0, 0.0,   1.0, 1.0,   0.0, 1.0,    // v7-v4-v3-v2 down
      0.0, 0.0,   1.0, 0.0,   1.0, 1.0,   0.0, 1.0     // v4-v7-v6-v5 back
  ]);

  // Indices of the vertices
  var indices = new Uint8Array([
     0, 1, 2,   0, 2, 3,    // front
     4, 5, 6,   4, 6, 7,    // right
     8, 9,10,   8,10,11,    // up
    12,13,14,  12,14,15,    // left
    16,17,18,  16,18,19,    // down
    20,21,22,  20,22,23     // back
  ])

  var o = new Object();  // Create the "Object" object to return multiple objects.

  // Write vertex information to buffer object
  o.vertexBuffer = initArrayBufferForLaterUse(gl, vertices, 3, gl.FLOAT);
  o.texCoordBuffer = initArrayBufferForLaterUse(gl, texCoords, 2, gl.FLOAT);
  o.indexBuffer = initElementArrayBufferForLaterUse(gl, indices, gl.UNSIGNED_BYTE);
  if (!o.vertexBuffer || !o.texCoordBuffer || !o.indexBuffer) return null;

  o.numIndices = indices.length;

  // Unbind the buffer object
  gl.bindBuffer(gl.ARRAY_BUFFER, null);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

  return o;
}

function initVertexBuffersForPlane(gl) {
  // Create face
  //  v1------v0
  //  |        |
  //  |        |
  //  |        |
  //  v2------v3

  // Vertex coordinates
  var vertices = new Float32Array([
    1.0, 1.0, 0.0,  -1.0, 1.0, 0.0,  -1.0,-1.0, 0.0,   1.0,-1.0, 0.0    // v0-v1-v2-v3
  ]);

  // Texture coordinates
  var texCoords = new Float32Array([1.0, 1.0,   0.0, 1.0,   0.0, 0.0,   1.0, 0.0]);

  // Indices of the vertices
  var indices = new Uint8Array([0, 1, 2,   0, 2, 3]);

  var o = new Object(); // Create the "Object" object to return multiple objects.

  // Write vertex information to buffer object
  o.vertexBuffer = initArrayBufferForLaterUse(gl, vertices, 3, gl.FLOAT);
  o.texCoordBuffer = initArrayBufferForLaterUse(gl, texCoords, 2, gl.FLOAT);
  o.indexBuffer = initElementArrayBufferForLaterUse(gl, indices, gl.UNSIGNED_BYTE);
  if (!o.vertexBuffer || !o.texCoordBuffer || !o.indexBuffer) return null;

  o.numIndices = indices.length;

  // Unbind the buffer object
  gl.bindBuffer(gl.ARRAY_BUFFER, null);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

  return o;
}

function initArrayBufferForLaterUse(gl, data, num, type) {
  // Create a buffer object
  var buffer = gl.createBuffer();
  if (!buffer) {
    console.log('Failed to create the buffer object');
    return null;
  }
  // Write date into the buffer object
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);

  // Store the necessary information to assign the object to the attribute variable later
  buffer.num = num;
  buffer.type = type;

  return buffer;
}

function initElementArrayBufferForLaterUse(gl, data, type) {
  // Create a buffer object
  var buffer = gl.createBuffer();
  if (!buffer) {
    console.log('Failed to create the buffer object');
    return null;
  }
  // Write date into the buffer object
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW);

  buffer.type = type;

  return buffer;
}

function initTextures(gl) {
  var texture = gl.createTexture();   // Create a texture object
  if (!texture) {
    console.log('Failed to create the Texture object');
    return null;
  }

  // Get storage location of u_Sampler
  var u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');
  if (!u_Sampler) {
    console.log('Failed to get the storage location of u_Sampler');
    return null;
  }

  var image = new Image();  // Create image object
  if (!image) {
    console.log('Failed to create the Image object');
    return null;
  }
  // Register the event handler to be called when image loading is completed
  image.onload = function() {
    // Write image data to texture object
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);  // Flip the image Y coordinate
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
    // Pass the texure unit 0 to u_Sampler
    gl.uniform1i(u_Sampler, 0);

    gl.bindTexture(gl.TEXTURE_2D, null); // Unbind the texture object
  };

  // Tell the browser to load an Image
  image.src = '../resources/sky_cloud.jpg';

  return texture;
}

function initFramebufferObject(gl) {
  var framebuffer, texture, depthBuffer;

  // Define the error handling function
  var error = function() {
    if (framebuffer) gl.deleteFramebuffer(framebuffer);
    if (texture) gl.deleteTexture(texture);
    if (depthBuffer) gl.deleteRenderbuffer(depthBuffer);
    return null;
  }

  // Create a frame buffer object (FBO)
  framebuffer = gl.createFramebuffer();
  if (!framebuffer) {
    console.log('Failed to create frame buffer object');
    return error();
  }

  // Create a texture object and set its size and parameters
  texture = gl.createTexture(); // Create a texture object
  if (!texture) {
    console.log('Failed to create texture object');
    return error();
  }
  gl.bindTexture(gl.TEXTURE_2D, texture); // Bind the object to target
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  framebuffer.texture = texture; // Store the texture object

  // Create a renderbuffer object and Set its size and parameters
  depthBuffer = gl.createRenderbuffer(); // Create a renderbuffer object
  if (!depthBuffer) {
    console.log('Failed to create renderbuffer object');
    return error();
  }
  gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer); // Bind the object to target
  gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT);

  // Attach the texture and the renderbuffer object to the FBO
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);

  // Check if FBO is configured correctly
  var e = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  if (gl.FRAMEBUFFER_COMPLETE !== e) {
    console.log('Frame buffer object is incomplete: ' + e.toString());
    return error();
  }

  // Unbind the buffer object
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.bindTexture(gl.TEXTURE_2D, null);
  gl.bindRenderbuffer(gl.RENDERBUFFER, null);

  return framebuffer;
}
function draw(gl, canvas, fbo, plane, cube, angle, texture, viewProjMatrix, viewProjMatrixFBO) {
  gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);              // Change the drawing destination to FBO
  gl.viewport(0, 0, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT); // Set a viewport for FBO

  gl.clearColor(0.2, 0.2, 0.4, 1.0); // Set clear color (the color is slightly changed)
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);  // Clear FBO

  drawTexturedCube(gl, gl.program, cube, angle, texture, viewProjMatrixFBO);   // Draw the cube

  gl.bindFramebuffer(gl.FRAMEBUFFER, null);        // Change the drawing destination to color buffer
  gl.viewport(0, 0, canvas.width, canvas.height);  // Set the size of viewport back to that of <canvas>

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // Clear the color buffer

  drawTexturedPlane(gl, gl.program, plane, angle, fbo.texture, viewProjMatrix);  // Draw the plane
}

// Coordinate transformation matrix
var g_modelMatrix = new Matrix4();
var g_mvpMatrix = new Matrix4();

function drawTexturedCube(gl, program, o, angle, texture, viewProjMatrix) {
  // Calculate a model matrix
  g_modelMatrix.setRotate(20.0, 1.0, 0.0, 0.0);
  g_modelMatrix.rotate(angle, 0.0, 1.0, 0.0);

  // Calculate the model view project matrix and pass it to u_MvpMatrix
  g_mvpMatrix.set(viewProjMatrix);
  g_mvpMatrix.multiply(g_modelMatrix);
  gl.uniformMatrix4fv(program.u_MvpMatrix, false, g_mvpMatrix.elements);

  drawTexturedObject(gl, program, o, texture);
}

function drawTexturedPlane(gl, program, o, angle, texture, viewProjMatrix) {
  // Calculate a model matrix
  g_modelMatrix.setTranslate(0, 0, 1);
  g_modelMatrix.rotate(20.0, 1.0, 0.0, 0.0);
  g_modelMatrix.rotate(angle, 0.0, 1.0, 0.0);

  // Calculate the model view project matrix and pass it to u_MvpMatrix
  g_mvpMatrix.set(viewProjMatrix);
  g_mvpMatrix.multiply(g_modelMatrix);
  gl.uniformMatrix4fv(program.u_MvpMatrix, false, g_mvpMatrix.elements);

  drawTexturedObject(gl, program, o, texture);
}

function drawTexturedObject(gl, program, o, texture) {
  // Assign the buffer objects and enable the assignment
  initAttributeVariable(gl, program.a_Position, o.vertexBuffer);    // Vertex coordinates
  initAttributeVariable(gl, program.a_TexCoord, o.texCoordBuffer);  // Texture coordinates

  // Bind the texture object to the target
  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, texture);

  // Draw
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, o.indexBuffer);
  gl.drawElements(gl.TRIANGLES, o.numIndices, o.indexBuffer.type, 0);
}

// Assign the buffer objects and enable the assignment
function initAttributeVariable(gl, a_attribute, buffer) {
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.vertexAttribPointer(a_attribute, buffer.num, buffer.type, false, 0, 0);
  gl.enableVertexAttribArray(a_attribute);
}

function drawTexturedCube2(gl, o, angle, texture, viewpProjMatrix, u_MvpMatrix) {
  // Calculate a model matrix
  g_modelMatrix.rotate(20.0, 1.0, 0.0, 0.0);
  g_modelMatrix.rotate(angle, 0.0, 1.0, 0.0);
  g_modelMatrix.scale(1, 1, 1);

  // Calculate the model view project matrix and pass it to u_MvpMatrix
  g_mvpMatrix.set(vpMatrix);
  g_mvpMatrix.multiply(g_modelMatrix);
  gl.uniformMatrix4fv(u_MvpMatrix, false, g_mvpMatrix.elements);

  drawTexturedObject(gl, o, texture);
}

var ANGLE_STEP = 30;   // The increments of rotation angle (degrees)

var last = Date.now(); // Last time that this function was called
function animate(angle) {
  var now = Date.now();   // Calculate the elapsed time
  var elapsed = now - last;
  last = now;
  // Update the current rotation angle (adjusted by the elapsed time)
  var newAngle = angle + (ANGLE_STEP * elapsed) / 1000.0;
  return newAngle % 360;
}

```


问:
How to fetch the text displayed on dropdown button in flutter
I have a dropdown button in which I am binding id to value and name to display Text. When user select an item from dropdown, I am getting the value using onChanged. How can I get the displayed text along with the value?</p>
```<code>    return Obx(() => DropdownButton(
          focusColor: Colors.blue,
          underline: SizedBox(),
          isExpanded: true,
          isDense: true,
          hint: Text("Select from List"),
          value: (fgTaskController.selectedFG.value == "")
              ? null
              : fgTaskController.selectedFG.value,
          items: fgTaskController.fgList.map((item) {
            return DropdownMenuItem(
              value: item.id,
              child: new Text(
                item.fgName.toString(),
                style: GoogleFonts.notoSerif(
                    textStyle: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue,
                )),
              ),
            );
          }).toList(),
          onChanged: (newValue) {
            fgTaskController.setSelectedFG(newValue);
            _selectedFG = newValue!;

          },
        ));
  }```

My Data set is like this:

[
 {
  "fg_name": "fg_name 1",
  "id": "1"
 },
 {
  "fg_name": "fg_name 2",
  "id": "2"
 },
 {
  "fg_name": "fg_name 3",
  "id": "3"
 }]

fg_name is displayed to user. Value is id. I want to save the selected fg_name and id to a Listview. That is the purpose.
</code>```

Body:
I have a dropdown button in which I am binding id to value and name to display Text. When user select an item from dropdown, I am getting the value using onChanged. How can I get the displayed text along with the value?

    return Obx(() => DropdownButton(
          focusColor: Colors.blue,
          underline: SizedBox(),
          isExpanded: true,
          isDense: true,
          hint: Text("Select from List"),
          value: (fgTaskController.selectedFG.value == "")
              ? null
              : fgTaskController.selectedFG.value,
          items: fgTaskController.fgList.map((item) {
            return DropdownMenuItem(
              value: item.id,
              child: new Text(
                item.fgName.toString(),
                style: GoogleFonts.notoSerif(
                    textStyle: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue,
                )),
              ),
            );
          }).toList(),
          onChanged: (newValue) {
            fgTaskController.setSelectedFG(newValue);
            _selectedFG = newValue!;

          },
        ));
  }```

My Data set is like this:

[
 {
  "fg_name": "fg_name 1",
  "id": "1"
 },
 {
  "fg_name": "fg_name 2",
  "id": "2"
 },
 {
  "fg_name": "fg_name 3",
  "id": "3"
 }]

fg_name is displayed to user. Value is id. I want to save the selected fg_name and id to a Listview. That is the purpose.


问:
I want to extend React-Query support on old browsers without manually testing my Next application on the said old browsers
I found this quote on the installation page but I don't understand the approach they want me to take:

"Depending on your environment, you might need to add polyfills. If you want to support older browsers, you need to transpile the library from node_modules yourselves."

You can check it here

I compared the default suppoted browers listed here vs. the release dates of those versions and would like to extend my application's support for browsers, ideally 5 and upto 10 years old.

Default React query browser support:

```<code>Chrome >= 73
Firefox >= 78
Edge >= 79
Safari >= 12.0
iOS >= 12.0
opera >= 53
</code>```

I am currently using

TanStack Query v4

Next.js v13 (SWC)

So far I have tried following the SWC documentation for browser support: docs

Body:
I found this quote on the installation page but I don't understand the approach they want me to take:

"Depending on your environment, you might need to add polyfills. If you want to support older browsers, you need to transpile the library from node_modules yourselves."

You can check it here

I compared the default suppoted browers listed here vs. the release dates of those versions and would like to extend my application's support for browsers, ideally 5 and upto 10 years old.

Default React query browser support:

Chrome >= 73
Firefox >= 78
Edge >= 79
Safari >= 12.0
iOS >= 12.0
opera >= 53

I am currently using

TanStack Query v4

Next.js v13 (SWC)

So far I have tried following the SWC documentation for browser support: docs


问:
bash script that checks ping output and run a second command restarting a strongswan service
I'm new to the world of linux and scripting, The OS is Amazon Linux 2 (EC2 instance).

The instance have a Strongswan Site-to-Site VPN connectivity to endpoint IP address 1.1.1.1

The problem is that it disconnects randomly and I have to run the command "sudo strongswan restart" everytime to reestablish the connection.

What I would like to learn right now is a script that continuously checks the connectivity to 1.1.1.1 and runs the "sudo strongswan restart" once disconnected and how to set a cron job for it.

Right now the only thing I can manage for cron is to run this job every 1 hour which works.

0 * * * * sudo strongswan restart

I need help for the script that check for ping timeout and run the VPN restart command


问:
Cloned profiles under non Salesforce License - Unable to create new custom objects
Can users "not with Salesforce License" be given permission to  create custom objects?

The "Customize Application" option Under "Administrative Permissions" is VISIBLE ONLY for the cloned profiles under "the Salesforce license"
2. But this option is NOT VISIBLE for the cloned profiles of other licenses (i.e. for licenses other than the Salesforce license)


问:
Want to display message for particular rows with list item which column value is null or blank in datagridview
Dear All Master,

I Want to display message for particular rows with list item column value is null or blank in datagridview.

so I want to display the message from the list item of "column1" where the null and blank. Is there a recommended solution that is best?

Thanks

```<code>so the output should be like this :
The following rows, Column2 must have a value.
from list item column1 :
A1
A3
A5
A6
A7
or
A1,A3,A5,A6,A7
Please check
</code>```

```<code>Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView1.Rows.Add(New Object() {"A1", Nothing, "C1"})
        DataGridView1.Rows.Add(New Object() {"A2", "B2", "C2"})
        DataGridView1.Rows.Add(New Object() {"A3", Nothing, "C3"})
        DataGridView1.Rows.Add(New Object() {"A4", "B4", "C4"})
        DataGridView1.Rows.Add(New Object() {"A5", 0, "C5"})
        DataGridView1.Rows.Add(New Object() {"A6", 0, "C6"})
        DataGridView1.Rows.Add(New Object() {"A7", Nothing, "C7"})

    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Results =
            (
                From T In DataGridView1.Rows.OfType(Of DataGridViewRow) _
                .Select(Function(r, i) New With
                                       {
                                           .Item = r,
                                           .Index = i
                                       })
                Where Not T.Item.IsNewRow AndAlso IsNothing(T.Item.Cells("Column2").Value)
            ).ToList

        If Results.Count > 0 Then
            MessageBox.Show("The following rows, Column2 must have a value." &
                            Environment.NewLine &
                            String.Join(",", Results.Select(Function(x) x.Index).ToArray))
        Else
            '
            ' Column2 has values for each row
            '
        End If
    End Sub

End Class
</code>```

Body:
Dear All Master,

I Want to display message for particular rows with list item column value is null or blank in datagridview.

so I want to display the message from the list item of "column1" where the null and blank. Is there a recommended solution that is best?

Thanks

so the output should be like this :
The following rows, Column2 must have a value.
from list item column1 :
A1
A3
A5
A6
A7
or
A1,A3,A5,A6,A7
Please check

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView1.Rows.Add(New Object() {"A1", Nothing, "C1"})
        DataGridView1.Rows.Add(New Object() {"A2", "B2", "C2"})
        DataGridView1.Rows.Add(New Object() {"A3", Nothing, "C3"})
        DataGridView1.Rows.Add(New Object() {"A4", "B4", "C4"})
        DataGridView1.Rows.Add(New Object() {"A5", 0, "C5"})
        DataGridView1.Rows.Add(New Object() {"A6", 0, "C6"})
        DataGridView1.Rows.Add(New Object() {"A7", Nothing, "C7"})

    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Results =
            (
                From T In DataGridView1.Rows.OfType(Of DataGridViewRow) _
                .Select(Function(r, i) New With
                                       {
                                           .Item = r,
                                           .Index = i
                                       })
                Where Not T.Item.IsNewRow AndAlso IsNothing(T.Item.Cells("Column2").Value)
            ).ToList

        If Results.Count > 0 Then
            MessageBox.Show("The following rows, Column2 must have a value." &
                            Environment.NewLine &
                            String.Join(",", Results.Select(Function(x) x.Index).ToArray))
        Else
            '
            ' Column2 has values for each row
            '
        End If
    End Sub

End Class


问:
how to pass and get Enums as parameters in angular routing?
I am using angular 15.
the models I defined as below:

export enum CustomerTypes {
  Real,
  Legal,
}

export class Customer {
  public customerId?: number;
  public customerType?: CustomerTypes;
  public customerName?: string;

}```
</div>
</div>
</p>
<p>in the main-page.component.html, I pass the customerType as a parameter to customers.component.ts.</p>
<p><strong>main-page.component.html:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-list-item  routerLink="customers" routerLinkActive="activeLink"> 'customers list' </mat-list-item></code>```

the content of coustomers.component.ts and its routing-module:

**//customers-routing.module.ts:**
const routes: Routes =[
  { path: '', component: CustomersComponent, children: [
      {
        path: 'customersList/:type',
        component: CustomersListComponent
      },

      // rest of code ...

**//customers.component.ts:**

      customerType = [CustomerTypes.Real, CustomerTypes.Legal];```
<pre class="snippet-code-html lang-html prettyprint-override"><code>**//customers.component.html:**
 {{ 'real customer' }}
 {{ 'legal customer' }}

     // rest of code ...</code>```

so far, the customer component replaces the customrList component with its <route-outlet> to list the customers by customerType. in the customerList.component.ts, getting all customers is successfully, but creating a new customer by its customertype property rises an error in side of server. because, the custometType value which got from route as parameter has not CustomerType type!
the content of customerList.componet.ts for getting customertype as a parameter from the route and getting all customers by their type as well as creating new customer are following:

**//customerList.component.ts**

 customertype!: CustomeType;
 newCustomer!: Customer
 //getting all customers by their type is done successfully
 ngOnInit(): void {
    this.customersForList$ = this.route.paramMap.pipe(
      switchMap((params: Params) => {
        return  this.customersService.getCustomersForListByType(this.customerType = params['get']('type'))
        }));
 }

 **//creating new customer**
 addNewCustomer(): void{
        this.newCustomer = new Customer();
        this.newCustomer.customerName = 'xyz';
        this.newCustomer.custometType = this.customerType;
        console.log(`customerType: ${this.customerType}`); //customerType: 0
        this.customersService.addCustomer(this.newCustomer); // error 500 from server...
        //rest of code ...
 }```
</div>
</div>
</p>
<p>I dont know whats the type of customerType. it seems that its type is not CustomerType (Enum). even, I tried to use switch statement to set the newCustomer.customerType with correct value:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>this.newCustomer.name = 'xyz';
        switch(this.customerType){
           case 0: this.newCustomer.customerType = CustomerType.real; break;
           case 1: this.newCustomer.customerType = CustomerType.legal; break;
        }
        this.customersService.addCustomer(this.newCustomer);</code>```

but. unfortunately, it seems that the customerType value is not 0 or 1 at all and the switch does not work. It is interesting that the parameter sent to the service to get all customers based on thier type works perfectly. In other words, the parameter sent to the service is of Enum type. See the content of the service:

// ===== works well ....
getCustomersForListByType(type: CustomerTypes): Observable<Customer[]> {

   return this.http.get<Customer[]>(this.baseUrl + '/getCustomersByType/' + type);.}

// has error 500 !!!!!!
  addCustomer(customer: Customer): Observable<Customer> {
    return this.http.post<Customer>(this.baseUrl + '/addCustomer', customer);}```

how can I have the customerType value correctly from the route to add a new customer?

Body:
I am using angular 15.
the models I defined as below:

export enum CustomerTypes {
  Real,
  Legal,
}

export class Customer {
  public customerId?: number;
  public customerType?: CustomerTypes;
  public customerName?: string;

}

in the main-page.component.html, I pass the customerType as a parameter to customers.component.ts.

main-page.component.html:

<mat-list-item  routerLink="customers" routerLinkActive="activeLink"> 'customers list' </mat-list-item>

the content of coustomers.component.ts and its routing-module:

**//customers-routing.module.ts:**
const routes: Routes =[
  { path: '', component: CustomersComponent, children: [
      {
        path: 'customersList/:type',
        component: CustomersListComponent
      },

      // rest of code ...

**//customers.component.ts:**

      customerType = [CustomerTypes.Real, CustomerTypes.Legal];

**//customers.component.html:**
 {{ 'real customer' }}
 {{ 'legal customer' }}

     // rest of code ...

so far, the customer component replaces the customrList component with its <route-outlet> to list the customers by customerType. in the customerList.component.ts, getting all customers is successfully, but creating a new customer by its customertype property rises an error in side of server. because, the custometType value which got from route as parameter has not CustomerType type!
the content of customerList.componet.ts for getting customertype as a parameter from the route and getting all customers by their type as well as creating new customer are following:

**//customerList.component.ts**

 customertype!: CustomeType;
 newCustomer!: Customer
 //getting all customers by their type is done successfully
 ngOnInit(): void {
    this.customersForList$ = this.route.paramMap.pipe(
      switchMap((params: Params) => {
        return  this.customersService.getCustomersForListByType(this.customerType = params['get']('type'))
        }));
 }

 **//creating new customer**
 addNewCustomer(): void{
        this.newCustomer = new Customer();
        this.newCustomer.customerName = 'xyz';
        this.newCustomer.custometType = this.customerType;
        console.log(`customerType: ${this.customerType}`); //customerType: 0
        this.customersService.addCustomer(this.newCustomer); // error 500 from server...
        //rest of code ...
 }

I dont know whats the type of customerType. it seems that its type is not CustomerType (Enum). even, I tried to use switch statement to set the newCustomer.customerType with correct value:

this.newCustomer.name = 'xyz';
        switch(this.customerType){
           case 0: this.newCustomer.customerType = CustomerType.real; break;
           case 1: this.newCustomer.customerType = CustomerType.legal; break;
        }
        this.customersService.addCustomer(this.newCustomer);

but. unfortunately, it seems that the customerType value is not 0 or 1 at all and the switch does not work. It is interesting that the parameter sent to the service to get all customers based on thier type works perfectly. In other words, the parameter sent to the service is of Enum type. See the content of the service:

// ===== works well ....
getCustomersForListByType(type: CustomerTypes): Observable<Customer[]> {

   return this.http.get<Customer[]>(this.baseUrl + '/getCustomersByType/' + type);.}

// has error 500 !!!!!!
  addCustomer(customer: Customer): Observable<Customer> {
    return this.http.post<Customer>(this.baseUrl + '/addCustomer', customer);}

how can I have the customerType value correctly from the route to add a new customer?


问:
How to set filter and also add a QPushButton to a QTableView in PyQt? i.e how to set two models to a QTableView?
I am new to PyQt.
I have a QLineEdit and a QTableView in my window.
My requirements:

Whenever I type something in QLineEdit, the table has to show filtered results according to what I typed.

I want to add a QPushButton at last column of QTableView.

I have successfully implemented these requirements individually. But I am not able to add these two requirements simultaniously.

Here's my code:

```<code>from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys

class Application(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(0,0,700,200)
        self.initUI()

    def initUI(self):

        self.mainLayout = QVBoxLayout()
        self.searchBar = QLineEdit()
        self.table = QTableView()

        self.mainLayout.addWidget(self.searchBar)
        self.mainLayout.addWidget(self.table)

        self.modelOfTable = QStandardItemModel()
        self.modelOfTable.setHorizontalHeaderLabels(['ID', 'Date', 'Description', 'Cause', 'Category', 'Button'])
        self.table.setModel(self.modelOfTable)

        self.modelOfTable.appendRow([QStandardItem(str(i)) for i in range(5)])
        self.modelOfTable.appendRow([QStandardItem(str(i)) for i in range(4,9)])
        self.modelOfTable.appendRow([QStandardItem(str(i)) for i in range(7,12)])
        for i in range(3):
            self.table.setIndexWidget(self.modelOfTable.index(i, 5), QPushButton("button"))

        filter_proxy_model = QSortFilterProxyModel()
        filter_proxy_model.setSourceModel(self.modelOfTable)
        filter_proxy_model.setFilterKeyColumn(-1)
        self.searchBar.textChanged.connect(filter_proxy_model.setFilterRegExp)

        self.table.setModel(self.modelOfTable)

        main_widget = QWidget()
        main_widget.setLayout(self.mainLayout)
        self.setCentralWidget(main_widget)
        # Setting the window to be in maximised mode
        #self.showMaximized()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Application()
    ex.show()
    sys.exit(app.exec_())
</code>```

All the problem is in  self.table.setModel line.

If I write self.table.setModel(self.modelOfTable) in that line, Pushbutton is placed in last column but filter is not working.

If I write self.table.setModel(self.modelOfTable) in that line, filter is working but there is no pushbutton in last column.

How can I add both two requirements at a time?

Body:
I am new to PyQt.
I have a QLineEdit and a QTableView in my window.
My requirements:

Whenever I type something in QLineEdit, the table has to show filtered results according to what I typed.

I want to add a QPushButton at last column of QTableView.

I have successfully implemented these requirements individually. But I am not able to add these two requirements simultaniously.

Here's my code:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys

class Application(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(0,0,700,200)
        self.initUI()

    def initUI(self):

        self.mainLayout = QVBoxLayout()
        self.searchBar = QLineEdit()
        self.table = QTableView()

        self.mainLayout.addWidget(self.searchBar)
        self.mainLayout.addWidget(self.table)

        self.modelOfTable = QStandardItemModel()
        self.modelOfTable.setHorizontalHeaderLabels(['ID', 'Date', 'Description', 'Cause', 'Category', 'Button'])
        self.table.setModel(self.modelOfTable)

        self.modelOfTable.appendRow([QStandardItem(str(i)) for i in range(5)])
        self.modelOfTable.appendRow([QStandardItem(str(i)) for i in range(4,9)])
        self.modelOfTable.appendRow([QStandardItem(str(i)) for i in range(7,12)])
        for i in range(3):
            self.table.setIndexWidget(self.modelOfTable.index(i, 5), QPushButton("button"))

        filter_proxy_model = QSortFilterProxyModel()
        filter_proxy_model.setSourceModel(self.modelOfTable)
        filter_proxy_model.setFilterKeyColumn(-1)
        self.searchBar.textChanged.connect(filter_proxy_model.setFilterRegExp)

        self.table.setModel(self.modelOfTable)

        main_widget = QWidget()
        main_widget.setLayout(self.mainLayout)
        self.setCentralWidget(main_widget)
        # Setting the window to be in maximised mode
        #self.showMaximized()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Application()
    ex.show()
    sys.exit(app.exec_())

All the problem is in  self.table.setModel line.

If I write self.table.setModel(self.modelOfTable) in that line, Pushbutton is placed in last column but filter is not working.

If I write self.table.setModel(self.modelOfTable) in that line, filter is working but there is no pushbutton in last column.

How can I add both two requirements at a time?


问:
How to re write pandas for loop computation with list comprehension or np.where / np.select
```<code>#BOH qty * capacity to get EQ
for i in final_merge2['FLAG']:
    if i =='BOH':
        for j in final_merge2['Plan_ID']:
            if j =='JUL':
                final_merge2['EQ202207'] = (final_merge2['Qty202207']*final_merge2['Capacity'])/1000000
</code>```

This logic is taking 30 mins because of data size

Tried this logic but didnt work

```<code>conditions  = [(final_merge2['FLAG'] == 'BOH') & (final_merge2['Plan_ID'] =='JUL')]
choices     = [(final_merge2['Qty202207']*final_merge2['Capacity'])/1000000]
final_merge2["EQ202207"] = np.select(conditions, , default=final_merge2["EQ202207"])
</code>```

also this

```<code>final_merge2["EQ202207"]=((final_merge2['Qty202207']*final_merge2['Capacity'])/1000000).where(final_merge2.FLAG == 'BOH',(.where(final_merge2.Plan_ID=='JUL')))

</code>```

But I didnt get the working solution.

How to re write pandas for loop computation with list comprehension or np.where  / np.select

I want to multiply two columns  & divide by 100000 if two columns has the values (final_merge2['FLAG'] =='BOH &final_merge2['Plan_ID']=='JUL)

```<code>final_merge2['Qty202207']*final_merge2['Capacity'])/1000000
</code>```

Body:
#BOH qty * capacity to get EQ
for i in final_merge2['FLAG']:
    if i =='BOH':
        for j in final_merge2['Plan_ID']:
            if j =='JUL':
                final_merge2['EQ202207'] = (final_merge2['Qty202207']*final_merge2['Capacity'])/1000000

This logic is taking 30 mins because of data size

Tried this logic but didnt work

conditions  = [(final_merge2['FLAG'] == 'BOH') & (final_merge2['Plan_ID'] =='JUL')]
choices     = [(final_merge2['Qty202207']*final_merge2['Capacity'])/1000000]
final_merge2["EQ202207"] = np.select(conditions, , default=final_merge2["EQ202207"])

also this

final_merge2["EQ202207"]=((final_merge2['Qty202207']*final_merge2['Capacity'])/1000000).where(final_merge2.FLAG == 'BOH',(.where(final_merge2.Plan_ID=='JUL')))

But I didnt get the working solution.

How to re write pandas for loop computation with list comprehension or np.where  / np.select

I want to multiply two columns  & divide by 100000 if two columns has the values (final_merge2['FLAG'] =='BOH &final_merge2['Plan_ID']=='JUL)

final_merge2['Qty202207']*final_merge2['Capacity'])/1000000


问:
Can I set token to authentication of Swagger after try it out request to login?
I am very new in swagger.

Current, I need to write API document for my NodeJS app, use swagger to do it.

Problem is I have to get JWT token and paste it to authentication box every time I open my api document.

I am using Postman, and It's providing a feature preScript. It run after request, I can use this feature to get token and set it to variable and use this variable value to send request.

Can I do it the same ???


问:
Two models with one-to-many into single JSON dict
I have two models for 'PO Header' and 'PO Item' data like this:

```<code>class po(models.Model):
    po_number = models.CharField(max_length=16, null=True)
    buy_org = models.CharField(max_length=20, null=True)
    supplier = models.CharField(max_length=16, null=True)

class poitm(models.Model):
    po = models.ForeignKey(po, on_delete=models.CASCADE, related_name='poitm')
    po_li = models.CharField(max_length=6, null=True)
    matnr = models.CharField(max_length=16, null=True)
    quantity = models.DecimalField(decimal_places=6, max_digits=16, null=True)
</code>```

I try to create a view that returns a json object like this:

```<code>[{'po_number':'45000123','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123456','quantity':'12'},{'po_li':'020','matnr':'123457','quantity':'8'}]},{'po_number':'45000124','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123235','quantity':'15'},{'po_li':'020','matnr':'123499','quantity':'24'}]}
]
</code>```

In principle a list of purchase orders with each purchase order containing a list of purchase order items.

I managed to create queryset containing the data like I need it but for performance reasons when using datatables.net with dom data I need to return the data in json format instead of looping through the queryset in the html template.

```<code>def purchaseorders(request):
    polist=purchaseOrder.objects.all()
    itemlist=poItem.objects.all()
    for poentry in polist:
        poentry.itemlist=itemlist.filter(po_id=poentry.id)
    return render(request, 'purchaseorders.html', {"poitems":polist})
</code>```

This seems to create a queryset with each object of a queryset. This then gives me a problem when I try to serialize it to json. Only the fields from the outer queryset are in the json result.

In the end the purpose is to generate an html page with a datatables.net table. Currently I am achieving this by looping through the inner and the outer queryset in the html page using django tags:

    var data =[ {% for po in poitems %}
{ "ponumber": '{{ po.po_number}}', "buy_org": "{{ po.buy_org }}", "supplier": "{{ po.supplier }}","itemlist": [
{% for itemlist in po.itemlist %}
{ "poli": '{{ itemlist.po_li }}', "matnr": '{{ itemlist.matnr}}', "quantity": '{{itemlist.quantity}}'},
{% endfor %}
]},
{% endfor %} ]```

This is a serious performance issue when I deal with a few thousand purchase orders. According to Datatables.net the correct way is to go with ajax and providing the data in json format.

I looked and tried for two solid days, turning in circles now, please help.

Body:
I have two models for 'PO Header' and 'PO Item' data like this:

class po(models.Model):
    po_number = models.CharField(max_length=16, null=True)
    buy_org = models.CharField(max_length=20, null=True)
    supplier = models.CharField(max_length=16, null=True)

class poitm(models.Model):
    po = models.ForeignKey(po, on_delete=models.CASCADE, related_name='poitm')
    po_li = models.CharField(max_length=6, null=True)
    matnr = models.CharField(max_length=16, null=True)
    quantity = models.DecimalField(decimal_places=6, max_digits=16, null=True)

I try to create a view that returns a json object like this:

[{'po_number':'45000123','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123456','quantity':'12'},{'po_li':'020','matnr':'123457','quantity':'8'}]},{'po_number':'45000124','buy_org':'Org1','supplier':'Org2','itemlist':[{'po_li':'010','matnr':'123235','quantity':'15'},{'po_li':'020','matnr':'123499','quantity':'24'}]}
]

In principle a list of purchase orders with each purchase order containing a list of purchase order items.

I managed to create queryset containing the data like I need it but for performance reasons when using datatables.net with dom data I need to return the data in json format instead of looping through the queryset in the html template.

def purchaseorders(request):
    polist=purchaseOrder.objects.all()
    itemlist=poItem.objects.all()
    for poentry in polist:
        poentry.itemlist=itemlist.filter(po_id=poentry.id)
    return render(request, 'purchaseorders.html', {"poitems":polist})

This seems to create a queryset with each object of a queryset. This then gives me a problem when I try to serialize it to json. Only the fields from the outer queryset are in the json result.

In the end the purpose is to generate an html page with a datatables.net table. Currently I am achieving this by looping through the inner and the outer queryset in the html page using django tags:

    var data =[ {% for po in poitems %}
{ "ponumber": '{{ po.po_number}}', "buy_org": "{{ po.buy_org }}", "supplier": "{{ po.supplier }}","itemlist": [
{% for itemlist in po.itemlist %}
{ "poli": '{{ itemlist.po_li }}', "matnr": '{{ itemlist.matnr}}', "quantity": '{{itemlist.quantity}}'},
{% endfor %}
]},
{% endfor %} ]

This is a serious performance issue when I deal with a few thousand purchase orders. According to Datatables.net the correct way is to go with ajax and providing the data in json format.

I looked and tried for two solid days, turning in circles now, please help.


问:
How could I create a form that has sub-sub-group in react?
Html version of the form

I used Multiselect component and am wondering if I could solve this problem using Multiselect component.