问:
Rust openssl rsa OAEP Padding not working
I am playing around with RSA encryption and I have just been using the standard PCKS1 padding which works fine, but I would like to use the more advanced OAEP or PSS Padding schemes. But for some reason when I switch the constant from PCKS1 to PKCS1_OAEP, it compiles but I get a run-time error. Which implies to me that the functionality is there but I am doing something wrong.
Here's my code

```<code>use openssl::{rsa::{Rsa, Padding}, symm::Cipher};
use bincode;

fn main() {
    let rsa = Rsa::generate(512).unwrap();
    let password = "password";
    let source = "hello paul".to_string();
    let data = bincode::serialize(&source).unwrap();
    let private = rsa.private_key_to_pem_passphrase(Cipher::aes_128_cbc(), password.as_bytes()).unwrap();

    //encrypt
    let private_key = Rsa::private_key_from_pem_passphrase(&private, password.as_bytes()).unwrap();

    let mut enc_data = vec![0; private_key.size() as usize];
    match private_key.private_encrypt(&data, &mut enc_data, Padding::PKCS1_OAEP) {
        Ok(_) => {},
        Err(e) => {
            println!("{e}");
            return;
        }
    }
}
</code>```

and my Cargo.toml dependencies

```<code>[dependencies]
openssl-sys = "0.9.79"
openssl = "0.10.44"
chrono = "0.4"
bincode = "1.0"
serde = { version = "1.0", features = ["derive"] }

</code>```

and here is the error I am getting.

```<code>error:04066076:rsa routines:rsa_ossl_private_encrypt:unknown padding type:crypto/rsa/rsa_ossl.c:273:
</code>```

So I am getting this from this resource(https://docs.rs/openssl/latest/openssl/rsa/struct.Padding.html#associatedconstant.PKCS1_OAEP)
I ahve also tried it with PKCS1_PSS and get the same error.
Does anyone know whats up, maybe they never actually finished OAEP or PSS, or is there something wrong on my end? Maybe I need to use a different Cipher than aes_128_cbc? Thanks for reading any help is appreciated.

Body:
I am playing around with RSA encryption and I have just been using the standard PCKS1 padding which works fine, but I would like to use the more advanced OAEP or PSS Padding schemes. But for some reason when I switch the constant from PCKS1 to PKCS1_OAEP, it compiles but I get a run-time error. Which implies to me that the functionality is there but I am doing something wrong.
Here's my code

use openssl::{rsa::{Rsa, Padding}, symm::Cipher};
use bincode;

fn main() {
    let rsa = Rsa::generate(512).unwrap();
    let password = "password";
    let source = "hello paul".to_string();
    let data = bincode::serialize(&source).unwrap();
    let private = rsa.private_key_to_pem_passphrase(Cipher::aes_128_cbc(), password.as_bytes()).unwrap();

    //encrypt
    let private_key = Rsa::private_key_from_pem_passphrase(&private, password.as_bytes()).unwrap();

    let mut enc_data = vec![0; private_key.size() as usize];
    match private_key.private_encrypt(&data, &mut enc_data, Padding::PKCS1_OAEP) {
        Ok(_) => {},
        Err(e) => {
            println!("{e}");
            return;
        }
    }
}

and my Cargo.toml dependencies

[dependencies]
openssl-sys = "0.9.79"
openssl = "0.10.44"
chrono = "0.4"
bincode = "1.0"
serde = { version = "1.0", features = ["derive"] }

and here is the error I am getting.

error:04066076:rsa routines:rsa_ossl_private_encrypt:unknown padding type:crypto/rsa/rsa_ossl.c:273:

So I am getting this from this resource(https://docs.rs/openssl/latest/openssl/rsa/struct.Padding.html#associatedconstant.PKCS1_OAEP)
I ahve also tried it with PKCS1_PSS and get the same error.
Does anyone know whats up, maybe they never actually finished OAEP or PSS, or is there something wrong on my end? Maybe I need to use a different Cipher than aes_128_cbc? Thanks for reading any help is appreciated.


来源: stackexchange

问:
Kotlin/JS Invalid property id when adding cursor pointer style to span
Here is the code:

```<code>h.span {
    css {
        cursor = Cursor.pointer
    }
    +"∄"
    ...
}
</code>```

When compiled, it produces the following error:

```<code>> Task :browser:processDceKotlinJs FAILED
error: at /.../build/js/packages/kjs-browser/kotlin/kjs-browser.js (1193, 185): invalid property id
</code>```

Examining the location of the error, we see it's at the $receiver_0.cursor line, below, and it indicates the entry default (at position 185):

  function RecordList$lambda$lambda$lambda$lambda$lambda$lambda$lambda(closure$id, closure$updateList) {
    return function ($receiver) {
      var $receiver_0 = {};
      $receiver_0.cursor = (/*union*/{alias: 'alias', allScroll: 'all-scroll', cell: 'cell', colResize: 'col-resize', contextMenu: 'context-menu', copy: 'copy', crosshair: 'crosshair', default: 'default', eResize: 'e-resize', ewResize: 'ew-resize', grab: 'grab', grabbing: 'grabbing', help: 'help', move: 'move', nResize: 'n-resize', neResize: 'ne-resize', neswResize: 'nesw-resize', noDrop: 'no-drop', notAllowed: 'not-allowed', nsResize: 'ns-resize', nwResize: 'nw-resize', nwseResize: 'nwse-resize', pointer: 'pointer', progress: 'progress', rowResize: 'row-resize', sResize: 's-resize', seResize: 'se-resize', swResize: 'sw-resize', text: 'text', verticalText: 'vertical-text', wResize: 'w-resize', wait: 'wait', zoomIn: 'zoom-in', zoomOut: 'zoom-out'}/*union*/).pointer;
      $receiver.className = css($receiver_0);
      $receiver.unaryPlus_pdl1vz$('\u2204');
      $receiver.onClick = preventDefault(RecordList$lambda$lambda$lambda$lambda$lambda$lambda$lambda$lambda(closure$id, closure$updateList));
      return Unit;
    };
  }
```

By removing the css block that sets the pointer style, the error disappears.

As an interesting side note, the code runs just fine in development mode (browserDevelopmentRun).

ContentLicense: CC BY-SA 4.0

Body:
Here is the code:

h.span {
    css {
        cursor = Cursor.pointer
    }
    +"∄"
    ...
}

When compiled, it produces the following error:

> Task :browser:processDceKotlinJs FAILED
error: at /.../build/js/packages/kjs-browser/kotlin/kjs-browser.js (1193, 185): invalid property id

Examining the location of the error, we see it's at the $receiver_0.cursor line, below, and it indicates the entry default (at position 185):

  function RecordList$lambda$lambda$lambda$lambda$lambda$lambda$lambda(closure$id, closure$updateList) {
    return function ($receiver) {
      var $receiver_0 = {};
      $receiver_0.cursor = (/*union*/{alias: 'alias', allScroll: 'all-scroll', cell: 'cell', colResize: 'col-resize', contextMenu: 'context-menu', copy: 'copy', crosshair: 'crosshair', default: 'default', eResize: 'e-resize', ewResize: 'ew-resize', grab: 'grab', grabbing: 'grabbing', help: 'help', move: 'move', nResize: 'n-resize', neResize: 'ne-resize', neswResize: 'nesw-resize', noDrop: 'no-drop', notAllowed: 'not-allowed', nsResize: 'ns-resize', nwResize: 'nw-resize', nwseResize: 'nwse-resize', pointer: 'pointer', progress: 'progress', rowResize: 'row-resize', sResize: 's-resize', seResize: 'se-resize', swResize: 'sw-resize', text: 'text', verticalText: 'vertical-text', wResize: 'w-resize', wait: 'wait', zoomIn: 'zoom-in', zoomOut: 'zoom-out'}/*union*/).pointer;
      $receiver.className = css($receiver_0);
      $receiver.unaryPlus_pdl1vz$('\u2204');
      $receiver.onClick = preventDefault(RecordList$lambda$lambda$lambda$lambda$lambda$lambda$lambda$lambda(closure$id, closure$updateList));
      return Unit;
    };
  }

By removing the css block that sets the pointer style, the error disappears.

As an interesting side note, the code runs just fine in development mode (browserDevelopmentRun).


问:
How to allow all users to run this SQL query?
Some context: I am trying to upload data from Comcast into our database.  Comcast sends the data in a macro-enabled workbook with file extension ".xlsm" which is disgusting. To circumvent this, I setup a power automate desktop flow to open the XLSM files and save them as XLSX files.  I then run this query under an INSERT on our reporting server to get the data into the DB:

```<code>SELECT *
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
   'Excel 12.0 Xml;Database=\\COMPANYNAME\company\customer\Comcast\Comcast.xlsx;', Sheet1$);
</code>```

The only problem is, I'd like this to be automated.  So I setup a cloud power automate flow to run the desktop flow and then execute a stored procedure in SQL Server.  My flow receives the same error I do on my machine as well as any user outside of the COMPANYNAME\administrator session in SSMS on our reporting server:

Msg 7399, Level 16, State 1, Line 5
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7303, Level 16, State 1, Line 5
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

It has been very difficult to research this issue as there seem to be many possible causes.  I'm no IT wizard but I know enough to be dangerous.  Thank you in advance for your time and help and I eagerly await your response!

Body:
Some context: I am trying to upload data from Comcast into our database.  Comcast sends the data in a macro-enabled workbook with file extension ".xlsm" which is disgusting. To circumvent this, I setup a power automate desktop flow to open the XLSM files and save them as XLSX files.  I then run this query under an INSERT on our reporting server to get the data into the DB:

SELECT *
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
   'Excel 12.0 Xml;Database=\\COMPANYNAME\company\customer\Comcast\Comcast.xlsx;', Sheet1$);

The only problem is, I'd like this to be automated.  So I setup a cloud power automate flow to run the desktop flow and then execute a stored procedure in SQL Server.  My flow receives the same error I do on my machine as well as any user outside of the COMPANYNAME\administrator session in SSMS on our reporting server:

Msg 7399, Level 16, State 1, Line 5
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7303, Level 16, State 1, Line 5
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

It has been very difficult to research this issue as there seem to be many possible causes.  I'm no IT wizard but I know enough to be dangerous.  Thank you in advance for your time and help and I eagerly await your response!


问:
The Xmx Parameter Doesn't Do Anything
I've got a java program that gets quite RAM-hungry over time (for as yet undetermined reasons). So to prevent it going crazy with the page file, I run it with the parameter -Xmx1536m, so that Java will just crash once the program's taken up one and a half gig of RAM. Better that then having my whole computer lock up.

The trouble is, it's not working. When I check Task Manager, sometimes Java is hogging 2.8GB of RAM, or higher! The program should be crashing well before it gets to that point!

Why isn't it?

Title: The Xmx Parameter Doesn't Do Anything


问:
How do I implement a many-to-many relationship with a checkbox to assign permissions to a role in Nova 4?

How do I implement a many-to-many relationship with a checkbox to assign permissions to a role in Nova 4?
I have tables (roles and permissions and role_permission), I want to apply multiple permissions to a role in the role page.

BelongsToMany::make('permissions')
```


问:
Why is Zod recursive tuple giving validation runtime error?
I've been trying to do a recursive tuple using Zod and when I run my script I am getting the following error:

```<code> return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
{ TSError: ⨯ Unable to compile TypeScript:
examples/Markdown.ts:87:14 - error TS2322: Type 'ZodLazy<ZodTuple<[ZodUnion<[ZodNativeEnum<{ readonly A: "a"; readonly ABBR: "abbr"; readonly ACRONYM: "acronym"; readonly B: "b"; readonly BDO: "bdo"; readonly BI: "big"; readonly BR: "br"; readonly BUTTON: "button"; ... 24 more ...; readonly VAR: "var"; }>, ZodNativeEnum<...>]>, ZodObject<...>, ZodNullable<...>], n...' is not assignable to type 'ZodType<Markdown, ZodTypeDef, Markdown>'.
  Types of property '_type' are incompatible.
    Type '["object" | "map" | "code" | "address" | "article" | "aside" | "blockquote" | "canvas" | "dd" | "div" | "dl" | "dt" | "fieldset" | "figcaption" | "figure" | "footer" | "form" | ... 49 more ... | "var", {}, Markdown[], ...unknown[]]' is not assignable to type 'Markdown'.
      Target allows only 3 element(s) but source may have more.

87 export const Markdown: z.ZodType<Markdown> = z.lazy(() =
</code>```

This is my actual code implementation: Markdown.ts

// TAGS has been simplified here for readability
const TAGS = { BR: "br", P: "p", SPAN: "span" } as const

type Children = string | Markdown

type Markdown = [
  typeof TAGS[keyof typeof TAGS],
  {},
  Children[] | null
]

export const Markdown: z.ZodType<Markdown> = z.lazy(() =>
  z.tuple([
    z.nativeEnum(TAGS),
    z.object({}),
    z.nullable(z.array(Markdown))
  ])
)

// This typing works:
const sample: Markdown = [
  "p",
  {},
  [
    "Let us know how we can help!",
    [
      "br",
      {},
      null
    ],
    [
      "span",
      {},
      [
        "Hello Jim!"
      ]
    ]
  ]
]
```

There don't appear to be any typescript errors in my editor, it's only when I try to utilize the zod validation at runtime that the error message appears. I am not sure if this is a zod issue or me not properly understanding tuples in Typescript.

Body:
I've been trying to do a recursive tuple using Zod and when I run my script I am getting the following error:

 return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
{ TSError: ⨯ Unable to compile TypeScript:
examples/Markdown.ts:87:14 - error TS2322: Type 'ZodLazy<ZodTuple<[ZodUnion<[ZodNativeEnum<{ readonly A: "a"; readonly ABBR: "abbr"; readonly ACRONYM: "acronym"; readonly B: "b"; readonly BDO: "bdo"; readonly BI: "big"; readonly BR: "br"; readonly BUTTON: "button"; ... 24 more ...; readonly VAR: "var"; }>, ZodNativeEnum<...>]>, ZodObject<...>, ZodNullable<...>], n...' is not assignable to type 'ZodType<Markdown, ZodTypeDef, Markdown>'.
  Types of property '_type' are incompatible.
    Type '["object" | "map" | "code" | "address" | "article" | "aside" | "blockquote" | "canvas" | "dd" | "div" | "dl" | "dt" | "fieldset" | "figcaption" | "figure" | "footer" | "form" | ... 49 more ... | "var", {}, Markdown[], ...unknown[]]' is not assignable to type 'Markdown'.
      Target allows only 3 element(s) but source may have more.

87 export const Markdown: z.ZodType<Markdown> = z.lazy(() =

This is my actual code implementation: Markdown.ts

// TAGS has been simplified here for readability
const TAGS = { BR: "br", P: "p", SPAN: "span" } as const

type Children = string | Markdown

type Markdown = [
  typeof TAGS[keyof typeof TAGS],
  {},
  Children[] | null
]

export const Markdown: z.ZodType<Markdown> = z.lazy(() =>
  z.tuple([
    z.nativeEnum(TAGS),
    z.object({}),
    z.nullable(z.array(Markdown))
  ])
)

// This typing works:
const sample: Markdown = [
  "p",
  {},
  [
    "Let us know how we can help!",
    [
      "br",
      {},
      null
    ],
    [
      "span",
      {},
      [
        "Hello Jim!"
      ]
    ]
  ]
]

There don't appear to be any typescript errors in my editor, it's only when I try to utilize the zod validation at runtime that the error message appears. I am not sure if this is a zod issue or me not properly understanding tuples in Typescript.


问:
Flutter: Unable to connect to VM service at *link* WebSocketChannelException: WebSocket connection failed
I am creating a Flutter application that utilizes GoogleMaps APIs. After adding a function to search using the Places API, my application shuts down a few seconds after compiling with the following error:

Error after compiling

I've updated http, GoogleMaps SDK for ios, the podfile, and Flutter itself. None of those things seem to fix the problem. Below is part of the code I added that seems to be causing this issue:

Potentially problematic code

I'm unsure what WebSocket is, but I'm utilizing http to get the input from user text in order to generate the location. Any ideas on how to go about fixing this? I couldn't find any solutions just by searching the error.


问:
Create second DF based on a column of list
I would like to create a second table with the values from a column of list of strings.

I have a df:

sent_id
associations

1
["a","b","c"]

2
NaN

3
["a"]

4
["d"]

I would like to "normalize" my data by creating a second dataframe like this:

sent_id
association

1
"a"

1
"b"

1
"c"

3
"a"

4
"d"

How do I achieve this?

I have partially arrive at my solution using this code I found in stackoverflow:

```<code>test = pd.Series(sum([item for item in df["associations"]], []))
</code>```

But this doesn't preserve the sent_id

Body:
I would like to create a second table with the values from a column of list of strings.

I have a df:

sent_id
associations

1
["a","b","c"]

2
NaN

3
["a"]

4
["d"]

I would like to "normalize" my data by creating a second dataframe like this:

sent_id
association

1
"a"

1
"b"

1
"c"

3
"a"

4
"d"

How do I achieve this?

I have partially arrive at my solution using this code I found in stackoverflow:

test = pd.Series(sum([item for item in df["associations"]], []))

But this doesn't preserve the sent_id


问:
The best way to run tests on different environments and different test sets using gitlab ci/cd
I have a project written in Java. Code is on Gitlab.
I would like to be able to run my tests (written in selenium + testng) in gitlab CI on different environments and different test suites (all.xml, login.xml, order.xml etc).
What is the best way to do this using gitab-ci.yml file? Currently I have the file configured as below and everything works. I can run both tests on DEV and PROD environments and different test suites. But the problem is a lot of duplicate code in the gitlab-ci.yml file. How to do it better?
My gitab-ci.yml file:</p>
```<code>image: myImage/maven-chrome:jdk-17

stages:
  - test

LOGIN_DEV:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=login.xml -DTestEnvironment=DEV
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

REGISTER_DEV:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=register.xml -DTestEnvironment=DEV
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

ALL_DEV:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=all.xml -DTestEnvironment=DEV
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

LOGIN_PROD:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=login.xml -DTestEnvironment=PROD
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

REGISTER_PROD:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=register.xml -DTestEnvironment=PROD
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

ALL_PROD:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=all.xml -DTestEnvironment=PROD
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual
</code>```

Body:
I have a project written in Java. Code is on Gitlab.
I would like to be able to run my tests (written in selenium + testng) in gitlab CI on different environments and different test suites (all.xml, login.xml, order.xml etc).
What is the best way to do this using gitab-ci.yml file? Currently I have the file configured as below and everything works. I can run both tests on DEV and PROD environments and different test suites. But the problem is a lot of duplicate code in the gitlab-ci.yml file. How to do it better?
My gitab-ci.yml file:

image: myImage/maven-chrome:jdk-17

stages:
  - test

LOGIN_DEV:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=login.xml -DTestEnvironment=DEV
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

REGISTER_DEV:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=register.xml -DTestEnvironment=DEV
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

ALL_DEV:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=all.xml -DTestEnvironment=DEV
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

LOGIN_PROD:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=login.xml -DTestEnvironment=PROD
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

REGISTER_PROD:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=register.xml -DTestEnvironment=PROD
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual

ALL_PROD:
  stage: test
  script:
    - mvn $MAVEN_OPTS clean test -D surefire.suiteXmlFiles=all.xml -DTestEnvironment=PROD
  artifacts:
    paths:
      - results
    expire_in: 1 day
    when: manual
  when: manual


问:
How to detect cycles of Time series data using Python
I have battery voltage data for one month I need to find out the cycle count for how many cycles the battery fully charged and discharged when the peak voltage value is grater than 53v and valley has to be inbetween 43 and 44 it has to detect one full cycle since I used peak detection algorithm it is not detecting correctly here is y data https://docs.google.com/spreadsheets/d/1K0XspcrpO94mv2wFgW45DzSjAO0Af1uSwmoHHVxDJwI/edit?usp=sharing

Script I used:

```<code>import numpy as np
op_col = []
for i in df["voltage"]:
 op_col.append(i)
np.set_printoptions(threshold=np.inf)
x = np.array(op_col)
from scipy.signal import find_peaks
peak, _ = find_peaks(x, width=800,prominence=1,height=51)
fig= plt.figure(figsize=(19,8))
plt.plot(x)
plt.xlim(0,45000)
plt.plot(peak, x[peak], "x", color = 'r')
</code>```

This cycles count I need to get it how can I do that:

Body:
I have battery voltage data for one month I need to find out the cycle count for how many cycles the battery fully charged and discharged when the peak voltage value is grater than 53v and valley has to be inbetween 43 and 44 it has to detect one full cycle since I used peak detection algorithm it is not detecting correctly here is y data https://docs.google.com/spreadsheets/d/1K0XspcrpO94mv2wFgW45DzSjAO0Af1uSwmoHHVxDJwI/edit?usp=sharing

Script I used:

import numpy as np
op_col = []
for i in df["voltage"]:
 op_col.append(i)
np.set_printoptions(threshold=np.inf)
x = np.array(op_col)
from scipy.signal import find_peaks
peak, _ = find_peaks(x, width=800,prominence=1,height=51)
fig= plt.figure(figsize=(19,8))
plt.plot(x)
plt.xlim(0,45000)
plt.plot(peak, x[peak], "x", color = 'r')

This cycles count I need to get it how can I do that:


问:
dragEnd() and TypeError (cannot read properties of undefined (reading "src"))
I seem to be hard stuck with this game. I tried to comment the relevant lines of code. It seems that the "src" of the images im dragging get "lost" when I drop the image into their new place. Up to this point I think everything logs as expected, except when its time to switch "src"s between them two inside of dragEnd().

When executed dragEnd() keeps the .src of the first image (taken from dragstart), and when its time to dragDrop() this.otherTile still hast the .src. But when I release I get the error inside of dragEnd(), when its time to read the .src of this.otherTile.

I just hope this isnt another dumb error because of spelling. But I dont understand why this.currTile keeps the src when picked and dropped and this.otherTile "loses" it when its time to change.

Thank you very much in advance!

```<code>class PuzzleGame extends Game {
  constructor() {
    super();
    this.rows = 3;
    this.columns = 3;
    //current clicked image, other the one we swap with
    this.currTile;
    this.otherTile;
    this.turns = 0;
    this.imageOrder = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    this.randomOrder = [];
  }
  populateBoard() {
    for (let r = 0; r < this.rows; r++) {
      for (let c = 0; c < this.columns; c++) {
        let tile = document.createElement("img");
        tile.id = r.toString() + "-" + c.toString();
        tile.src = "./images/" + this.randomOrder.shift() + ".png";
        // drag functions
        tile.addEventListener("dragstart", this.dragStart);
        tile.addEventListener("dragover", this.dragOver);
        tile.addEventListener("dragenter", this.dragEnter);
        tile.addEventListener("dragleave", this.dragLeave);
        tile.addEventListener("drop", this.dragDrop);
        tile.addEventListener("dragend", this.dragEnd);

        document.getElementById("board").append(tile);
      }
    }
  }
  _randomizeOrder() {
    if (!this.imageOrder) return undefined;
    this.randomOrder = this.imageOrder.sort(function () {
      return Math.random() - 0.5;
    });
    return this.randomOrder;
  }
  puzzleStart() {
    this._randomizeOrder();
    this.populateBoard();
  }
  dragStart() {
    this.currTile = this //image being dragged
    console.log(this) //logs img.id and img.src "/images/4.png"
    console.log(this.src)// logs file path users/xxxx/desktop/etc/4.png
  }
  dragOver(e) {
    e.preventDefault();
  }
  dragEnter(e) {
    e.preventDefault();
  }
  dragLeave() {}
  dragDrop() {
    this.otherTile = this; //image tile being dropped
    console.log(this.otherTile.src ) //logs file path users/xxxxx/desktop/etc/9.png
  }
  dragEnd() {
    let currImg = this.currTile.src;
    console.log(this.currTile) //logs currTile
    console.log(currImg); //logs file path
    let otherImg = this.otherTile.src; //Error on this line of code TypeError:cannot read properties of undefined (reading "src")
    this.currTile.src = otherImg;
    this.otherTile.src = currImg;
    console.log(this.otherTile)
  }
}
</code>```

Body:
I seem to be hard stuck with this game. I tried to comment the relevant lines of code. It seems that the "src" of the images im dragging get "lost" when I drop the image into their new place. Up to this point I think everything logs as expected, except when its time to switch "src"s between them two inside of dragEnd().

When executed dragEnd() keeps the .src of the first image (taken from dragstart), and when its time to dragDrop() this.otherTile still hast the .src. But when I release I get the error inside of dragEnd(), when its time to read the .src of this.otherTile.

I just hope this isnt another dumb error because of spelling. But I dont understand why this.currTile keeps the src when picked and dropped and this.otherTile "loses" it when its time to change.

Thank you very much in advance!

class PuzzleGame extends Game {
  constructor() {
    super();
    this.rows = 3;
    this.columns = 3;
    //current clicked image, other the one we swap with
    this.currTile;
    this.otherTile;
    this.turns = 0;
    this.imageOrder = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    this.randomOrder = [];
  }
  populateBoard() {
    for (let r = 0; r < this.rows; r++) {
      for (let c = 0; c < this.columns; c++) {
        let tile = document.createElement("img");
        tile.id = r.toString() + "-" + c.toString();
        tile.src = "./images/" + this.randomOrder.shift() + ".png";
        // drag functions
        tile.addEventListener("dragstart", this.dragStart);
        tile.addEventListener("dragover", this.dragOver);
        tile.addEventListener("dragenter", this.dragEnter);
        tile.addEventListener("dragleave", this.dragLeave);
        tile.addEventListener("drop", this.dragDrop);
        tile.addEventListener("dragend", this.dragEnd);

        document.getElementById("board").append(tile);
      }
    }
  }
  _randomizeOrder() {
    if (!this.imageOrder) return undefined;
    this.randomOrder = this.imageOrder.sort(function () {
      return Math.random() - 0.5;
    });
    return this.randomOrder;
  }
  puzzleStart() {
    this._randomizeOrder();
    this.populateBoard();
  }
  dragStart() {
    this.currTile = this //image being dragged
    console.log(this) //logs img.id and img.src "/images/4.png"
    console.log(this.src)// logs file path users/xxxx/desktop/etc/4.png
  }
  dragOver(e) {
    e.preventDefault();
  }
  dragEnter(e) {
    e.preventDefault();
  }
  dragLeave() {}
  dragDrop() {
    this.otherTile = this; //image tile being dropped
    console.log(this.otherTile.src ) //logs file path users/xxxxx/desktop/etc/9.png
  }
  dragEnd() {
    let currImg = this.currTile.src;
    console.log(this.currTile) //logs currTile
    console.log(currImg); //logs file path
    let otherImg = this.otherTile.src; //Error on this line of code TypeError:cannot read properties of undefined (reading "src")
    this.currTile.src = otherImg;
    this.otherTile.src = currImg;
    console.log(this.otherTile)
  }
}


问:
Flutter schedule notification but with different body
guys, i'm trying for 4 days until now to figure out how can I add a function to show different String on the next notification. The only result i get it's one random String who is showing over and over again. Here is the code, the code is separated on 2 separated classes:

```<code>Future<void> showNotification(int id, String title, String body) async {
    await flutterLocalNotificationsPlugin.periodicallyShow(
      id,
      title,
      body,
      RepeatInterval.everyMinute,
      const NotificationDetails(
        // Android details
        android: AndroidNotificationDetails('main_channel', 'Main Channel',
            channelDescription: "ashwin",
            importance: Importance.max,
            priority: Priority.max),
        // iOS details
        iOS: DarwinNotificationDetails(
          sound: 'default.wav',
          presentAlert: true,
          presentBadge: true,
          presentSound: true,
        ),
      ),
      androidAllowWhileIdle:
          true, // To show notification even when the app is closed
    );
  }
</code>```

This is the schedule notification that i m calling

```<code> String? randomName;
    final random = new Random();
    randomName = names[random.nextInt(names.length)];
</code>```
```<code> onPressed: () {
                      setState(() {
                        showToast();
                        NotificationService().showNotification(
                          1,
                          '$randomNames${widget.userPost}',
                          randomName!,
                        );
                      });
                    },
</code>```

randomName and onPressed are on the other class. It's working but it show only one random notification over and over again, i've tried with awesome notification and workmanager but it s not working for me. Anybody here who can help me with this?

I want to show at every notification that user riceve a different String not just one over and over again

Body:
guys, i'm trying for 4 days until now to figure out how can I add a function to show different String on the next notification. The only result i get it's one random String who is showing over and over again. Here is the code, the code is separated on 2 separated classes:

Future<void> showNotification(int id, String title, String body) async {
    await flutterLocalNotificationsPlugin.periodicallyShow(
      id,
      title,
      body,
      RepeatInterval.everyMinute,
      const NotificationDetails(
        // Android details
        android: AndroidNotificationDetails('main_channel', 'Main Channel',
            channelDescription: "ashwin",
            importance: Importance.max,
            priority: Priority.max),
        // iOS details
        iOS: DarwinNotificationDetails(
          sound: 'default.wav',
          presentAlert: true,
          presentBadge: true,
          presentSound: true,
        ),
      ),
      androidAllowWhileIdle:
          true, // To show notification even when the app is closed
    );
  }

This is the schedule notification that i m calling

 String? randomName;
    final random = new Random();
    randomName = names[random.nextInt(names.length)];

 onPressed: () {
                      setState(() {
                        showToast();
                        NotificationService().showNotification(
                          1,
                          '$randomNames${widget.userPost}',
                          randomName!,
                        );
                      });
                    },

randomName and onPressed are on the other class. It's working but it show only one random notification over and over again, i've tried with awesome notification and workmanager but it s not working for me. Anybody here who can help me with this?

I want to show at every notification that user riceve a different String not just one over and over again


问:
In Python 3.7+, are dicts ordered when specifically created using curly brace notation ({})?
In Python 3.7, dictionaries preserve insertion order. The dict() constructor, when provided with a list of tuples, will insert the keys in order.  Will curly brace notation also preserve order?  That is, will the below assertion always pass?

```<code>import random

keys = [str(i) for i in range(1_000_000)]

test_dict = {key: "" for key in keys}
assert keys == list(test_dict.keys())
</code>```

I know this seems small, but I'm looking for specific documentation about the curly brace delimiter.

Thanks!

Body:
In Python 3.7, dictionaries preserve insertion order. The dict() constructor, when provided with a list of tuples, will insert the keys in order.  Will curly brace notation also preserve order?  That is, will the below assertion always pass?

import random

keys = [str(i) for i in range(1_000_000)]

test_dict = {key: "" for key in keys}
assert keys == list(test_dict.keys())

I know this seems small, but I'm looking for specific documentation about the curly brace delimiter.

Thanks!


问:
Total Revenue reporting metric decrease on adding different dimensions and metrics
I'm building a Google Analytics 4 report to export the total revenue for a specific GA property.
Validating the report results built via API against the results via UI we noticed that there are a weird behavior on the UI.

We built a report on the UI containing the summarized total revenue by "session default channel group", "device category", "session campaign" and "session source". Using this configuration the total revenue is $524k, summarized.

Once we update the definition adding the metric "new users", the total revenue was updated to $520k, summarized.

We updated the report definition by adding the dimension "Date" and the metrics "Total Users", "Ecommerce purchases", "Sessions" and "Event Value" and the metric total revenue was decrease to $516k, summarized.

I would like to understand why is this happening? how can I identify the real summarized value.
Thank you in advance!

I'm expecting to see the Total Revenue metric values in a consistent way, to keep the same value.


问:
emu8086 screen goes out of focus on virtual device state change
I am writing a program in assembly using emu8086.

The program is basically trying to keep the virtual device Thermometer.exe at some target temperature, starting at 60 and increasing / decreasing it based on '+' / '-' char input.

The problem is not in the input, but in the screen and Thermometer windows themselves.
Each time the heater is toggled, the screen window goes out of focus and instead the Thermometer screen goes into focus, which is very annoying to say the least.

My question is, is it possible to disable this behavior and make the screen always in focus?

Here's my code, if it helps:

```<code>org 100h

jmp start
target dw 60

start:

mov cx, 1
infinite:
inc cx

mov ah, 06h
mov dl, 0ffh
int 21h
jz no_key

cmp al, '+'
je inc_temp
cmp al, '-'
je dec_temp

inc_temp:
inc target
jmp no_key

dec_temp:
dec target

no_key:

in ax, 125
cmp ax, target
jl on
cmp ax, target
jg off

jmp continue

on:
mov ax, 1
out 127, ax
jmp continue

off:
mov ax, 0
out 127, ax

continue:
loop infinite

e:
mov ah, 0
int 16h
ret
</code>```

Body:
I am writing a program in assembly using emu8086.

The program is basically trying to keep the virtual device Thermometer.exe at some target temperature, starting at 60 and increasing / decreasing it based on '+' / '-' char input.

The problem is not in the input, but in the screen and Thermometer windows themselves.
Each time the heater is toggled, the screen window goes out of focus and instead the Thermometer screen goes into focus, which is very annoying to say the least.

My question is, is it possible to disable this behavior and make the screen always in focus?

Here's my code, if it helps:

org 100h

jmp start
target dw 60

start:

mov cx, 1
infinite:
inc cx

mov ah, 06h
mov dl, 0ffh
int 21h
jz no_key

cmp al, '+'
je inc_temp
cmp al, '-'
je dec_temp

inc_temp:
inc target
jmp no_key

dec_temp:
dec target

no_key:

in ax, 125
cmp ax, target
jl on
cmp ax, target
jg off

jmp continue

on:
mov ax, 1
out 127, ax
jmp continue

off:
mov ax, 0
out 127, ax

continue:
loop infinite

e:
mov ah, 0
int 16h
ret


问:
How to put condition on Custom Json Convertor
I have defined a custom Json Convertor for my DTO as below

```<code>public class CustomJsonConverter<T> : JsonConverter<T> where T : class
    {
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            some code...
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            some code...
        }
    }
</code>```

Then i am using it on my DTO as below

```<code>[JsonConverter(typeof(CustomJsonConverter<StudentDTO>))]
    public class StudentDTO
    {
            some code...
    }
</code>```

Its all working super fine.
Now All I want is At some place I want .net to use My JsonConverter and in other places i want .net to use default JsonConverter.
How Do I Do it

Is there a way where I remove the converter annotation from the DTO and instead Use "JsonSerialzer.Serialize()" and somehow I can tell it which converter to use.

Body:
I have defined a custom Json Convertor for my DTO as below

public class CustomJsonConverter<T> : JsonConverter<T> where T : class
    {
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            some code...
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            some code...
        }
    }

Then i am using it on my DTO as below

[JsonConverter(typeof(CustomJsonConverter<StudentDTO>))]
    public class StudentDTO
    {
            some code...
    }

Its all working super fine.
Now All I want is At some place I want .net to use My JsonConverter and in other places i want .net to use default JsonConverter.
How Do I Do it

Is there a way where I remove the converter annotation from the DTO and instead Use "JsonSerialzer.Serialize()" and somehow I can tell it which converter to use.


问:
Issue with the createSharedElementStackNavigator
I am having an issue with the CreateSharedElementStacknavigator that it doesn't transition back to the initial spot where I left off if I were to use a scroll view. For example, Like if I were to scroll down a couple swipes at the home page and click on an item. It would direct me to another screen. Now if I were to press another Item inside that screen, then it will direct me to another screen once more. Okay, let's say if I wanted to return back to the home screen and I click the back button on the screen I am in and hit the back button again to return to home. Now, it leaves me at the top of the screen instead of the initial point where I left off at the middle. Anyway I can get this fixed?

I have tried using the createNativeStackNavigator and it does leave me back at the initial point where I left off if I were to jump two screens more in an item.

I want to keep the createSharedElementStackNavigator because of the fluid animation it contains, but also have the createNativeStackNavigator which helps to keep the initial screen not transition to the top.

Here's a video example of what I am talking about:

https://drive.google.com/file/d/1ugv0z6vUD5XZjt52hHE3OqBD0PVjfrX2/view?usp=sharing


问:
Can't update child entity spring boot with JPA
when i request to update my parent and child table throw put request (send data through JSON) parent table is update and in child table new extra row create with the same parent id rather than update row.

```<code>
@Entity
public class Book {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        private String title;

        @OneToMany(mappedBy = "book",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
        @JsonManagedReference
        private List<Author> author;

        @OneToOne(cascade = CascadeType.ALL)
        @JsonManagedReference
        private BookImage bookImage;

// Getters and Setter
</code>```
```<code>@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
@Entity
public class Author{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String firstname;
    private String lastname;
    private String language;

    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    @JsonBackReference
    private Book book;

// Getters and Setter
</code>```
```<code>@Entity
public class BookImage{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private String type;
    private Long size;
    @Lob
    private Blob image;

    @OneToOne(mappedBy = "bookImage",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    @JsonBackReference
    private Book book;

// Getters and Setter
</code>```
```<code>@PutMapping("/book/{id}")
    public ResponseEntity<Book> updateBook(@RequestParam("file") MultipartFile file,
            @RequestParam("book") String bookData, @PathVariable("id") int id) {
        try {
                        Book book = this.objectMapper.readValue(bookData, Book.class);
            // Create Book Image

            BookImage bookImage = new BookImage();
            bookImage.setId(id);
            bookImage.setName(file.getOriginalFilename());
            bookImage.setType(file.getContentType());
            bookImage.setSize(file.getSize());
            bookImage.setImage(new SerialBlob(file.getBytes()));
            book.setBookImage(bookImage);
            book.setId(id);
            this.bookService.updateBook(book);
            return ResponseEntity.of(Optional.of(book));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

</code>```
```<code>@Component
public class BookService
{
    @Autowired
    private BookRepository bookRepository;

    public List<Book> getAllBooks(){
        return this.bookRepository.findAll();
    }
    public Book getBookById(int id) {
        Book book = null;
        try {
            book = this.bookRepository.getBookById(id);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return book;
    }
    public Book addBook(Book book) {
        return this.bookRepository.save(book);
    }

    public void deleteBook(int id) {
        this.bookRepository.deleteById(id);
    }
    public void updateBook(Book book) {
        this.bookRepository.save(book);
    }
}
</code>```

Table Data After POST

now put with book id request

after put table data

Create 2 new raw rather than update raw...

Put request with book id 152 update book and book_image data but in author table create a 2 extra new row rather than update the data

i want to update the author table data

Body:
when i request to update my parent and child table throw put request (send data through JSON) parent table is update and in child table new extra row create with the same parent id rather than update row.

@Entity
public class Book {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        private String title;

        @OneToMany(mappedBy = "book",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
        @JsonManagedReference
        private List<Author> author;

        @OneToOne(cascade = CascadeType.ALL)
        @JsonManagedReference
        private BookImage bookImage;

// Getters and Setter

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
@Entity
public class Author{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String firstname;
    private String lastname;
    private String language;

    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    @JsonBackReference
    private Book book;

// Getters and Setter

@Entity
public class BookImage{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private String type;
    private Long size;
    @Lob
    private Blob image;

    @OneToOne(mappedBy = "bookImage",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    @JsonBackReference
    private Book book;

// Getters and Setter

@PutMapping("/book/{id}")
    public ResponseEntity<Book> updateBook(@RequestParam("file") MultipartFile file,
            @RequestParam("book") String bookData, @PathVariable("id") int id) {
        try {
                        Book book = this.objectMapper.readValue(bookData, Book.class);
            // Create Book Image

            BookImage bookImage = new BookImage();
            bookImage.setId(id);
            bookImage.setName(file.getOriginalFilename());
            bookImage.setType(file.getContentType());
            bookImage.setSize(file.getSize());
            bookImage.setImage(new SerialBlob(file.getBytes()));
            book.setBookImage(bookImage);
            book.setId(id);
            this.bookService.updateBook(book);
            return ResponseEntity.of(Optional.of(book));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

@Component
public class BookService
{
    @Autowired
    private BookRepository bookRepository;

    public List<Book> getAllBooks(){
        return this.bookRepository.findAll();
    }
    public Book getBookById(int id) {
        Book book = null;
        try {
            book = this.bookRepository.getBookById(id);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return book;
    }
    public Book addBook(Book book) {
        return this.bookRepository.save(book);
    }

    public void deleteBook(int id) {
        this.bookRepository.deleteById(id);
    }
    public void updateBook(Book book) {
        this.bookRepository.save(book);
    }
}

Table Data After POST

now put with book id request

after put table data

Create 2 new raw rather than update raw...

Put request with book id 152 update book and book_image data but in author table create a 2 extra new row rather than update the data

i want to update the author table data


问:
How to fix the axis range of a graph plot in r programming?
I am trying to plot a boxplot between two attributes from my dataset "Neighborhood" and "SalePrice". The SalePrice includes values from 35,000 to 750,000. When i am trying to plot the graph between them, it is showing SalePrice as 1e+05, 2e+05 etc.

I am using this code

```<code>chart1 = ggplot(data, aes(x= Neighborhood, y= SalePrice)) + geom_boxplot() + geom_hline(aes(yintercept= 70), colour = "red", linetype= "dashed", lwd=2) + theme(axis.text.x = element_text(angle = 90, hjust =1))
chart1
</code>```

If i am using

```<code>scale_y_continuous(labels = dollar_format())
</code>```

It is giving me error (Error in dollar_format() : could not find function "dollar_format")

Anyone knows how can I fix this problem. I want to show prices in 0 - 100,000 - 200,000 . . .

Body:
I am trying to plot a boxplot between two attributes from my dataset "Neighborhood" and "SalePrice". The SalePrice includes values from 35,000 to 750,000. When i am trying to plot the graph between them, it is showing SalePrice as 1e+05, 2e+05 etc.

I am using this code

chart1 = ggplot(data, aes(x= Neighborhood, y= SalePrice)) + geom_boxplot() + geom_hline(aes(yintercept= 70), colour = "red", linetype= "dashed", lwd=2) + theme(axis.text.x = element_text(angle = 90, hjust =1))
chart1

If i am using

scale_y_continuous(labels = dollar_format())

It is giving me error (Error in dollar_format() : could not find function "dollar_format")

Anyone knows how can I fix this problem. I want to show prices in 0 - 100,000 - 200,000 . . .


问:
Create a density map with ZIP codes
I have a dataset with some statistics for each ZIP area in the U.S.

I would like to create a map in which each area has a different color based on a statistic, or with some circles showing the density in the zone.

I tried to install the usa package and I used the zipcodes function to create a new table, that I left joined to my dataset by the zipcode. I then wrote this ggplot code:

```<code>to_map %>%
  ggplot(aes(x = long, y = lat, fill=my_stat)) +
  geom_polygon(color = "black", size = 0.09) +
  scale_fill_gradient(low = "yellow", high = "dark green") +
  ggthemes::theme_map() +
  theme(legend.background=element_rect(fill = alpha("white", 0.5)))

</code>```

But I obtain some weird drawing that makes no sense:
enter image description here

Does anyone know how to fix it?

Title: Create a density map with ZIP codes

Body:
I have a dataset with some statistics for each ZIP area in the U.S.

I would like to create a map in which each area has a different color based on a statistic, or with some circles showing the density in the zone.

I tried to install the usa package and I used the zipcodes function to create a new table, that I left joined to my dataset by the zipcode. I then wrote this ggplot code:

to_map %>%
  ggplot(aes(x = long, y = lat, fill=my_stat)) +
  geom_polygon(color = "black", size = 0.09) +
  scale_fill_gradient(low = "yellow", high = "dark green") +
  ggthemes::theme_map() +
  theme(legend.background=element_rect(fill = alpha("white", 0.5)))

But I obtain some weird drawing that makes no sense:
enter image description here

Does anyone know how to fix it?


问:
Need to build a direct graph on networkx(Python)
On a json serialization, I have to create a direct graph and for every follower of my "target analysis account" I have to create an edge on the direct graph.

Specifically, I have to analyze a twitter account which has 135 followers. For each follower of the account, I have to create a sort of connection with the accounts who follow it, and in the end, create the whole network.

The connections are based on twitter "id" and are all placed in a .json file (already done)

Thanks

```<code>#building a direct graph
directed_graph = nx.DiGraph()
directed_graph.add_node("Maintwitteraccount")

for follower in all_user_follower.data:
    directed_graph.add_node(follower["id"], username=follower["username"], description=follower["description"], follower_count=follower["public_metrics"]["followers_count"])
    directed_graph.nodes(data = True)

print("Questi sono i nodi:\n",directed_graph.nodes())
#print(directed_graph.nodes().data())

with open('data/followers.json', encoding="utf8") as json_file:
    data = json.load(json_file)

with open('data/followers_serializzati.json', encoding="utf8") as json_file:
    data2 = json.load(json_file)

# Building edges from maintwitteraccount and his followers
i=0
while i < len(all_followers[username]):
    id = data['Maintwitteraccount'][i]['id']
    directed_graph.add_edge("Maintwitteraccount",id)
    i += 1

#building edges from followers of  Maintwitteraccount and their followers
i=0
j=0
while i < len(all_followers[username]):
    id = data['Maintwitteraccount'][i]['id']

    follower_count_id = data2[str(id)]['public_metrics']['followers_count']

    while j < min(follower_count_id,1000):
        follower_id = list(data2[str(id)]['followers'].keys())[j]
        directed_graph.add_edge(id,follower_id)
        j += 1

    i += 1

print("\nQuesti sono gli archi:\n",directed_graph.edges())
</code>```

Body:
On a json serialization, I have to create a direct graph and for every follower of my "target analysis account" I have to create an edge on the direct graph.

Specifically, I have to analyze a twitter account which has 135 followers. For each follower of the account, I have to create a sort of connection with the accounts who follow it, and in the end, create the whole network.

The connections are based on twitter "id" and are all placed in a .json file (already done)

Thanks

#building a direct graph
directed_graph = nx.DiGraph()
directed_graph.add_node("Maintwitteraccount")

for follower in all_user_follower.data:
    directed_graph.add_node(follower["id"], username=follower["username"], description=follower["description"], follower_count=follower["public_metrics"]["followers_count"])
    directed_graph.nodes(data = True)

print("Questi sono i nodi:\n",directed_graph.nodes())
#print(directed_graph.nodes().data())

with open('data/followers.json', encoding="utf8") as json_file:
    data = json.load(json_file)

with open('data/followers_serializzati.json', encoding="utf8") as json_file:
    data2 = json.load(json_file)

# Building edges from maintwitteraccount and his followers
i=0
while i < len(all_followers[username]):
    id = data['Maintwitteraccount'][i]['id']
    directed_graph.add_edge("Maintwitteraccount",id)
    i += 1

#building edges from followers of  Maintwitteraccount and their followers
i=0
j=0
while i < len(all_followers[username]):
    id = data['Maintwitteraccount'][i]['id']

    follower_count_id = data2[str(id)]['public_metrics']['followers_count']

    while j < min(follower_count_id,1000):
        follower_id = list(data2[str(id)]['followers'].keys())[j]
        directed_graph.add_edge(id,follower_id)
        j += 1

    i += 1

print("\nQuesti sono gli archi:\n",directed_graph.edges())


问:
How to use useState within a promise.then()?
I'm trying to set a state within a promise.then() block and I'm confused on why it's not working.

```<code>const [rules, setRules] React.useState(<h1>hi</h1>);
const [modalVisible, setModalVisible] = React.useState(false);

const getRules = () => {
  apicall.promise().then((res) => {
    var rules = null;
    ...
    rules = <h1>hello</h1>;
    ...
    return rules;
  }).then((rulesComp) => {
    setRules(rulesComp);
  });
}

const SvgButton = ({node}: any) => {
  return (
    <foreignObject x="0" y="0" width="20" height="20">
      <div onClick={() => {getRules(); setModalVisible(true);}}>
        <mySVG />
      </div>
    </foreignObject>
  )
}

return (

    <><div>
       <SvgButton> is shown here
    </div>

    <Modal
      onDismiss={() => setModalVisible(false)}
      visible={modalVisible}
      closeAriaLabel="Close modal"
      footer="Modal footer"
      header="Modal title"
    >
      {rules}
    </Modal></>
);
</code>```

How can I make it so that the proper rules renders? Because right now it's just constantly showing the initial state.

Body:
I'm trying to set a state within a promise.then() block and I'm confused on why it's not working.

const [rules, setRules] React.useState(
hi
);
const [modalVisible, setModalVisible] = React.useState(false);

const getRules = () => {
  apicall.promise().then((res) => {
    var rules = null;
    ...
    rules =
hello
;
    ...
    return rules;
  }).then((rulesComp) => {
    setRules(rulesComp);
  });
}

const SvgButton = ({node}: any) => {
  return (
    <foreignObject x="0" y="0" width="20" height="20">

 {getRules(); setModalVisible(true);}}>
        <mySVG />

    </foreignObject>
  )
}

return (

    <>

       <SvgButton> is shown here

    <Modal
      onDismiss={() => setModalVisible(false)}
      visible={modalVisible}
      closeAriaLabel="Close modal"
      footer="Modal footer"
      header="Modal title"
    >
      {rules}
    </Modal></>
);

How can I make it so that the proper rules renders? Because right now it's just constantly showing the initial state.


问:
Is there a more efficient way to reduce Java TreeSet to a subset based on index?
I am currently implementing the Mash algorithm for genome comparison. For this I need to create a sketch S(A) for each genome, which is a set of certain size s containing the lowest hash values corresponding to k-mers in the genome. To compare two genomes, I am computing the Jaccard index, for which I need an additional sketch of the union of the two genomes, i.e. S(A u B) for two genomes A and B. This should contain the s lowest hash values found in the union of A and B.

I am computing the sketches as a TreeSet because in the original algorithm to compute a sketch I need to remove the biggest value from the set whenever I add a new value that is lower and the sketch has already reached the maximum size s. This is very easily accomplished using TreeSet because the largest value will be in the last position of the set.

I have computed a union of two sketches and now want to remove the larger elements to reduce the sketch size to size s. I first implemented this using a while loop and removing the last element until reaching the desired size.

The following is my code using an example TreeSet and size s = 10:

```<code>SortedSet<Integer> example = new TreeSet<>();
for (int i = 0; i < 15; i++) {
    example.add(i);
}

while (example.size() > 10) example.remove(example.last());
</code>```

However, in the real application sketch sizes will be much larger and the size of the union can be up to two times the size of a single sketch. Trying to find a more efficient way to reduce the sketch size I found that you could convert the TreeSet to an array. Thus, my second approach would be the following:

```<code>Object[] temp = example.toArray();
int value = (int) temp[10];
example = example.headSet(value);
</code>```

So, here I am getting the value at index s from the array, which I can then use to create a headSet from the TreeSet.

Now, I am wondering if there is a more efficient way to reduce the size of the TreeSet, where I don't need to iterate over the size of the TreeSet over and over again or generate an extra array.

Body:
I am currently implementing the Mash algorithm for genome comparison. For this I need to create a sketch S(A) for each genome, which is a set of certain size s containing the lowest hash values corresponding to k-mers in the genome. To compare two genomes, I am computing the Jaccard index, for which I need an additional sketch of the union of the two genomes, i.e. S(A u B) for two genomes A and B. This should contain the s lowest hash values found in the union of A and B.

I am computing the sketches as a TreeSet because in the original algorithm to compute a sketch I need to remove the biggest value from the set whenever I add a new value that is lower and the sketch has already reached the maximum size s. This is very easily accomplished using TreeSet because the largest value will be in the last position of the set.

I have computed a union of two sketches and now want to remove the larger elements to reduce the sketch size to size s. I first implemented this using a while loop and removing the last element until reaching the desired size.

The following is my code using an example TreeSet and size s = 10:

SortedSet<Integer> example = new TreeSet<>();
for (int i = 0; i < 15; i++) {
    example.add(i);
}

while (example.size() > 10) example.remove(example.last());

However, in the real application sketch sizes will be much larger and the size of the union can be up to two times the size of a single sketch. Trying to find a more efficient way to reduce the sketch size I found that you could convert the TreeSet to an array. Thus, my second approach would be the following:

Object[] temp = example.toArray();
int value = (int) temp[10];
example = example.headSet(value);

So, here I am getting the value at index s from the array, which I can then use to create a headSet from the TreeSet.

Now, I am wondering if there is a more efficient way to reduce the size of the TreeSet, where I don't need to iterate over the size of the TreeSet over and over again or generate an extra array.


问:
onClick and/or onChange not functioning
I have a formik form with a select field; two options. When i use onClick I always get "yes" submitted and if i use onChange it does not work in that it does not allow me to choose anything, just always leaves the field the same as before.

I have read a ton of different things. I have tried the setFieldValue, and I have tried onBlur, I have tried numerous different ways in writing the onChange handler without any success. Maybe i am just not changing and writing it properly.

I have looked over the suggested questions already on here and for whatever reason i can not get them to work in my code.

```<code>   import React, { useState, useRef } from 'react';
   import { Form, Field, } from 'formik';
   import emailjs from '@emailjs/browser';
</code>```
```<code>const RsvpForm = ({ errors, touched, isValid, dirty }) => {

const form = useRef();

const sendEmail = (e) => {
  e.preventDefault();

  const userName = e.target[0].value;
  const email = e.target[1].value;
  const attending = state;
  const plusOne = plusone;
  const guests = e.target[4].value;
  const guestNumber = e.target[5].value;
  const guest_name = e.target[6].value;
  const song = e.target[7].value;
  const message = e.target[8].value;

  let templateParams = {
      userName: userName,
      email: email,
      attending: attending,
      plusOne: plusOne,
      guests: guests,
      guestNumber: guestNumber,
      guest_name: guest_name,
      song: song,
      message: message,
  };

  emailjs.send(process.env.REACT_APP_SERVICE_ID, process.env.REACT_APP_TEMPLATE_ID, templateParams,   process.env.REACT_APP_PUBLIC_KEY)
    .then((result) => {
        console.log(result.text);
        e.target.reset();
    }, (error) => {
        console.log(error.text);
    });
};

const[state, attendingState] = useState("");
const onClick = (e) => {
  let{value} = e.target;
  if(value=== 'yes') {
    attendingState('yes')
  }else {
    attendingState('no')
  }
}

const[plusone, plusOnestate] = useState("");
const onPick = (e) => {
  let{value} = e.target;

  if(value=== 'no') {
    plusOnestate('no')
  }else {
    plusOnestate('yes')
  }
}
</code>```

return (

```<code><div className='form-group'>
  <label className='col-form-label'>Plus One:</label>
  <Field
    component='select'
    className={
      touched.plusOne
        ? `form-control ${errors.plusOne ? 'invalid' : 'valid'}`
        : `form-control`
    }
    name='plusOne'
    type='select'
    // onChange={(e) => setFieldValue('plusOne', e.target.value)}
    onClick={onPick}
  >
    <option value="">Please select an answer</option>
    <option value="yes">Yes, please add a plus one or few</option>
    <option value="no">Just me!</option>

  </Field>
  {touched.plusOne && errors.plusOne && (
    <small className='text-warning'><strong>{errors.plusOne}</strong></small>
  )}
</div>
</code>```
```<code>

</code>```

Title: onClick and/or onChange not functioning

Body:
I have a formik form with a select field; two options. When i use onClick I always get "yes" submitted and if i use onChange it does not work in that it does not allow me to choose anything, just always leaves the field the same as before.

I have read a ton of different things. I have tried the setFieldValue, and I have tried onBlur, I have tried numerous different ways in writing the onChange handler without any success. Maybe i am just not changing and writing it properly.

I have looked over the suggested questions already on here and for whatever reason i can not get them to work in my code.

   import React, { useState, useRef } from 'react';
   import { Form, Field, } from 'formik';
   import emailjs from '@emailjs/browser';

const RsvpForm = ({ errors, touched, isValid, dirty }) => {

const form = useRef();

const sendEmail = (e) => {
  e.preventDefault();

  const userName = e.target[0].value;
  const email = e.target[1].value;
  const attending = state;
  const plusOne = plusone;
  const guests = e.target[4].value;
  const guestNumber = e.target[5].value;
  const guest_name = e.target[6].value;
  const song = e.target[7].value;
  const message = e.target[8].value;

  let templateParams = {
      userName: userName,
      email: email,
      attending: attending,
      plusOne: plusOne,
      guests: guests,
      guestNumber: guestNumber,
      guest_name: guest_name,
      song: song,
      message: message,
  };

  emailjs.send(process.env.REACT_APP_SERVICE_ID, process.env.REACT_APP_TEMPLATE_ID, templateParams,   process.env.REACT_APP_PUBLIC_KEY)
    .then((result) => {
        console.log(result.text);
        e.target.reset();
    }, (error) => {
        console.log(error.text);
    });
};

const[state, attendingState] = useState("");
const onClick = (e) => {
  let{value} = e.target;
  if(value=== 'yes') {
    attendingState('yes')
  }else {
    attendingState('no')
  }
}

const[plusone, plusOnestate] = useState("");
const onPick = (e) => {
  let{value} = e.target;

  if(value=== 'no') {
    plusOnestate('no')
  }else {
    plusOnestate('yes')
  }
}

return (

  Plus One:
  <Field
    component='select'
    className={
      touched.plusOne
        ? `form-control ${errors.plusOne ? 'invalid' : 'valid'}`
        : `form-control`
    }
    name='plusOne'
    type='select'
    // onChange={(e) => setFieldValue('plusOne', e.target.value)}
    onClick={onPick}
  >
    <option value="">Please select an answer</option>
    <option value="yes">Yes, please add a plus one or few</option>
    <option value="no">Just me!</option>

  </Field>
  {touched.plusOne && errors.plusOne && (
    {errors.plusOne}
  )}


问:
Converting a WinForms Library from Net. Framework to Net. Core results in an error: Failed to load assembly
I have an WinForms Library with runtime and design-time assemblies.

In Net. Framework 4.7 it work perfectly well.

When I converted the library to Net. Core 6 the design-time part has stopped working
with a error
Failed to load assembly: EhLib.WinForms.Design.dll
I can't understand why.

The EhLib.WinForms.Design.dll file is present in the WinFormsApp1\bin\Debug\net6.0-windows project folder.

EhLib.WinForms.Design.dll is located in the \bin\Debug\net6.0-windows\ folder for each project.

When debugging DesignToolsServer.exe, you can see that the studio is loading this assembly.


问:
How do I create a script thats the difference between two variables?
I am completely new to this so apologies if this doesnt make any sense or is the complete wrong place to ask (if it is please tell me, I will not be offended).

I am using TradingView am looking at the RSI indicator with a moving avg on the chart. I would like to create a script that charts the difference between the current RSI and the moving avg. How do I do this?

I have a little bit of experience with coding, but just enough to understand the concepts of how it works.

Any feedback at all would be greatly appreciated.

thank you

I havent tried anything yet, I am not sure where to start.


问:
Libreswan invalid peer id while connecting to ikev1 tunnel
I want to connect to a watchguard remote access vpn server. I got the following shrewsoft configuration file for that:

```<code>n:version:2
s:network-host:SERVER_IP
n:network-ike-port:500
s:client-auto-mode:pull
s:client-iface:virtual
n:client-addr-auto:1
n:network-mtu-size:1380
s:network-natt-mode:enable
n:network-natt-port:4500
n:network-natt-rate:20
s:network-frag-mode:disable
n:network-dpd-enable:1
n:network-notify-enable:1
n:client-banner-enable:0
n:client-wins-used:1
n:client-wins-auto:1
n:client-dns-used:1
n:client-dns-auto:1
n:client-splitdns-used:1
n:client-splitdns-auto:1
s:auth-method:mutual-psk-xauth
b:auth-mutual-psk:SECRET
s:ident-client-type:ufqdn
s:ident-client-data:USERID
s:ident-server-type:any
s:phase1-exchange:aggressive
s:phase1-cipher:aes
n:phase1-keylen:256
s:phase1-hash:sha2-256
n:phase1-dhgroup:14
n:phase1-life-secs:86400
n:vendor-chkpt-enable:0
s:phase2-transform:esp-aes
n:phase2-keylen:256
s:phase2-hmac:sha2-256
n:phase2-pfsgroup:14
n:phase2-life-secs:28800
n:phase2-life-kbytes:0
s:ipcomp-transform:disabled
s:policy-level:unique
n:policy-nailed:0
n:policy-list-auto:0
s:policy-list-include:192.168.170.89 / 255.255.255.255

</code>```

This just works fine on windows, but on linux without GUI there is a known bug that traffic to the vpn won't get routed.

So I tried using Libreswan to connect, here is my config for that:

```<code>conn VPN
    authby=secret
    keyexchange=ike
    ikev2=no
    auto=add
    aggressive=yes
    fragmentation=no

    ike=aes256-sha2;modp2048
    phase2=esp
    phase2alg=aes256-sha2;modp2048

    right=SERVER_IP
    left=%defaultroute

    leftid=@USERNAME
    rightid=%any
    rightnexthop=%defaultroute
    rightsubnet=192.168.170.89/32

    leftmodecfgclient=yes
    modecfgpull=yes
    nat-keepalive=yes

    leftxauthclient=yes
    leftxauthusername=XAUTH_USER
    rightxauthserver=yes
</code>```

But I get the following error in phase1:

```<code>002 "VPN" #1: initiating IKEv1 Aggressive Mode connection
110 "VPN" #1: sent Aggressive Mode request
002 "VPN" #1: Peer ID is ID_IPV4_ADDR: 'NOT_SERVER_IP'
003 "VPN" #1: Peer ID 'NOT_SERVER_IP' mismatched on first found connection and no better connection found
003 "VPN" #1: initial Aggressive Mode packet claiming to be from SERVER_IP on SERVER_IP:500 but no connection has been authorized
218 "VPN" #1: sending notification INVALID_ID_INFORMATION to SERVER_IP:500
</code>```

SERVER_IP refers to the vpn gateway IP and NOT_SERVER_IP refers to some "random" ipv4

As I said, this happens only with libreswan and not with shrewsoft. Is there any common configuration missing?
I even captured the initial ISAKMP request from shrewsoft and libreswan,
libreswan
shrewsoft

really appreciate any help on this topic

I tried setting the rightip to the ip provided in the libreswan response, but than I get

```<code>received Hash Payload does not match computed value
223 "VPN" #1: sending notification INVALID_HASH_INFORMATION to SERVER_IP:500
</code>```

Which should be a result of using the wrong id in the request

Body:
I want to connect to a watchguard remote access vpn server. I got the following shrewsoft configuration file for that:

n:version:2
s:network-host:SERVER_IP
n:network-ike-port:500
s:client-auto-mode:pull
s:client-iface:virtual
n:client-addr-auto:1
n:network-mtu-size:1380
s:network-natt-mode:enable
n:network-natt-port:4500
n:network-natt-rate:20
s:network-frag-mode:disable
n:network-dpd-enable:1
n:network-notify-enable:1
n:client-banner-enable:0
n:client-wins-used:1
n:client-wins-auto:1
n:client-dns-used:1
n:client-dns-auto:1
n:client-splitdns-used:1
n:client-splitdns-auto:1
s:auth-method:mutual-psk-xauth
b:auth-mutual-psk:SECRET
s:ident-client-type:ufqdn
s:ident-client-data:USERID
s:ident-server-type:any
s:phase1-exchange:aggressive
s:phase1-cipher:aes
n:phase1-keylen:256
s:phase1-hash:sha2-256
n:phase1-dhgroup:14
n:phase1-life-secs:86400
n:vendor-chkpt-enable:0
s:phase2-transform:esp-aes
n:phase2-keylen:256
s:phase2-hmac:sha2-256
n:phase2-pfsgroup:14
n:phase2-life-secs:28800
n:phase2-life-kbytes:0
s:ipcomp-transform:disabled
s:policy-level:unique
n:policy-nailed:0
n:policy-list-auto:0
s:policy-list-include:192.168.170.89 / 255.255.255.255

This just works fine on windows, but on linux without GUI there is a known bug that traffic to the vpn won't get routed.

So I tried using Libreswan to connect, here is my config for that:

conn VPN
    authby=secret
    keyexchange=ike
    ikev2=no
    auto=add
    aggressive=yes
    fragmentation=no

    ike=aes256-sha2;modp2048
    phase2=esp
    phase2alg=aes256-sha2;modp2048

    right=SERVER_IP
    left=%defaultroute

    leftid=@USERNAME
    rightid=%any
    rightnexthop=%defaultroute
    rightsubnet=192.168.170.89/32

    leftmodecfgclient=yes
    modecfgpull=yes
    nat-keepalive=yes

    leftxauthclient=yes
    leftxauthusername=XAUTH_USER
    rightxauthserver=yes

But I get the following error in phase1:

002 "VPN" #1: initiating IKEv1 Aggressive Mode connection
110 "VPN" #1: sent Aggressive Mode request
002 "VPN" #1: Peer ID is ID_IPV4_ADDR: 'NOT_SERVER_IP'
003 "VPN" #1: Peer ID 'NOT_SERVER_IP' mismatched on first found connection and no better connection found
003 "VPN" #1: initial Aggressive Mode packet claiming to be from SERVER_IP on SERVER_IP:500 but no connection has been authorized
218 "VPN" #1: sending notification INVALID_ID_INFORMATION to SERVER_IP:500

SERVER_IP refers to the vpn gateway IP and NOT_SERVER_IP refers to some "random" ipv4

As I said, this happens only with libreswan and not with shrewsoft. Is there any common configuration missing?
I even captured the initial ISAKMP request from shrewsoft and libreswan,
libreswan
shrewsoft

really appreciate any help on this topic

I tried setting the rightip to the ip provided in the libreswan response, but than I get

received Hash Payload does not match computed value
223 "VPN" #1: sending notification INVALID_HASH_INFORMATION to SERVER_IP:500

Which should be a result of using the wrong id in the request


问:
AWS MSK MongoDB Sink Connector with IAM Auth enabled
I have created a AWS MSK Cluster with both IAM and SCRAM authentication enabled. When trying to create a MongoDB sink connector that writes messages from kafka topics to MongoDB, the connector creation fails with a message saying

```<code>There is an issue with the connector
Code: UnknownError.Unknown
Message: The last operation failed. Retry the operation.
</code>```

Here is the Trust relations in the Role i.e created

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "kafkaconnect.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "1234567890"
                },
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:kafkaconnect:us-west-2:1234567890:connector/*"
                }
            }
        }
    ]
}
</code>```

Permissions assigned to the role

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "kafka-cluster:*",
                "kafkaconnect:*",
                "kms:Decrypt",
                "secretsmanager:GetSecretValue",
                "s3:*",
                "kafka:*",
                "logs:*"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

Why is the connector creation failing and there's absolutely no logs created in CloudWatch

Body:
I have created a AWS MSK Cluster with both IAM and SCRAM authentication enabled. When trying to create a MongoDB sink connector that writes messages from kafka topics to MongoDB, the connector creation fails with a message saying

There is an issue with the connector
Code: UnknownError.Unknown
Message: The last operation failed. Retry the operation.

Here is the Trust relations in the Role i.e created

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "kafkaconnect.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "1234567890"
                },
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:kafkaconnect:us-west-2:1234567890:connector/*"
                }
            }
        }
    ]
}

Permissions assigned to the role

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "kafka-cluster:*",
                "kafkaconnect:*",
                "kms:Decrypt",
                "secretsmanager:GetSecretValue",
                "s3:*",
                "kafka:*",
                "logs:*"
            ],
            "Resource": "*"
        }
    ]
}

Why is the connector creation failing and there's absolutely no logs created in CloudWatch


问:
gtkmm Why window has black background and dialog does not
I have a very simple gtkmm3 app with 2 widgets (a window and a dialog) that shows both in response to event on_activate via:

```<code>    add_window(widget); widget.present();
</code>```

Both the dialog and the window have exactly the same code, with the only difference being the base class (Gtk::ApplicationWindow vs Gtk::Dialog).
The code for them is following:

```<code>constructor()
{
    set_decorated(false);
    set_app_paintable();
    set_default_size(640, 480);

    // remove default child if present
    auto child = get_child();
    if (child) remove(), delete child;
}

bool on_draw(const ::Cairo::RefPtr< ::Cairo::Context> & cr)
{
    // get the size of the window
    int width, height;
    get_size(width, height);

    // semi-transparent grey background
    cr->set_source_rgba(0.5,0.5,0.5,0.5);

    // make round edges
    const auto border_radius = 50;
    cr->arc(width - border_radius, height - border_radius, border_radius, 0, M_PI_2);
    cr->arc(border_radius, height - border_radius, border_radius, M_PI_2, M_PI);
    cr->arc(border_radius, border_radius, border_radius, M_PI, 3 * M_PI_2);
    cr->arc(width - border_radius, border_radius, border_radius, 3 * M_PI_2, 0);

    cr->clip(); // clip the edges
    cr->paint(); // paint the background

    return false;
}
</code>```

Surprisingly the result of both cases is different. The dialog gets the intended semi-transparent look, but the window has a black rectangular background.
I presume the window background must be drawn before on_draw, but I don't know when.

Q1: What is the difference between them?

Since Gtk::Dialog inherits from Gtk::Window, there must be a way to remove that black background.
Q2: How can I do that myself?

I already tried removing all CSS styles, by inserting * { all: unset; } in the Gtk inspector, with no visible effect (the inspector did showed all CSS nodes being reset). This makes me think that the black background may not be related to CSS, but I may be wrong.

This is what it looks like:

Body:
I have a very simple gtkmm3 app with 2 widgets (a window and a dialog) that shows both in response to event on_activate via:

    add_window(widget); widget.present();

Both the dialog and the window have exactly the same code, with the only difference being the base class (Gtk::ApplicationWindow vs Gtk::Dialog).
The code for them is following:

constructor()
{
    set_decorated(false);
    set_app_paintable();
    set_default_size(640, 480);

    // remove default child if present
    auto child = get_child();
    if (child) remove(), delete child;
}

bool on_draw(const ::Cairo::RefPtr< ::Cairo::Context> & cr)
{
    // get the size of the window
    int width, height;
    get_size(width, height);

    // semi-transparent grey background
    cr->set_source_rgba(0.5,0.5,0.5,0.5);

    // make round edges
    const auto border_radius = 50;
    cr->arc(width - border_radius, height - border_radius, border_radius, 0, M_PI_2);
    cr->arc(border_radius, height - border_radius, border_radius, M_PI_2, M_PI);
    cr->arc(border_radius, border_radius, border_radius, M_PI, 3 * M_PI_2);
    cr->arc(width - border_radius, border_radius, border_radius, 3 * M_PI_2, 0);

    cr->clip(); // clip the edges
    cr->paint(); // paint the background

    return false;
}

Surprisingly the result of both cases is different. The dialog gets the intended semi-transparent look, but the window has a black rectangular background.
I presume the window background must be drawn before on_draw, but I don't know when.

Q1: What is the difference between them?

Since Gtk::Dialog inherits from Gtk::Window, there must be a way to remove that black background.
Q2: How can I do that myself?

I already tried removing all CSS styles, by inserting * { all: unset; } in the Gtk inspector, with no visible effect (the inspector did showed all CSS nodes being reset). This makes me think that the black background may not be related to CSS, but I may be wrong.

This is what it looks like:


问:
Show results of long running job from external API on same page (WordPress)

I have a WordPress page with a form where the user can put in some
parameters.

When the form is sent it triggers an API. This can take a while (!)

When the API is ready it calls my WordPress site URL, which triggers a function:

```<code>add_action('wp_ajax_api_callback_action', 'my_callback_action');

function my_callback_action() {
  // Show API results on same page
}
</code>```

When the function is called I want to show the results underneath the users form on the same page via jQuery.

How can I achieve this? The API is calling the WordPress URL, but how does the user's browser should know about it? Can I let run something in the background in the browser to wait until the API is ready (a cron job is not what I'm looking for)?

Any help is appreciated to guide me in the right direction.

Body:
I have a WordPress page with a form where the user can put in some
parameters.

When the form is sent it triggers an API. This can take a while (!)

When the API is ready it calls my WordPress site URL, which triggers a function:

add_action('wp_ajax_api_callback_action', 'my_callback_action');

function my_callback_action() {
  // Show API results on same page
}

When the function is called I want to show the results underneath the users form on the same page via jQuery.

How can I achieve this? The API is calling the WordPress URL, but how does the user's browser should know about it? Can I let run something in the background in the browser to wait until the API is ready (a cron job is not what I'm looking for)?

Any help is appreciated to guide me in the right direction.