问:
How to map JSON Object with Java Pojo Class Spring Boot?
How to map JSON object with POJO class in Spring Boot. I have JSON data as below:

```<code>    {
    "report": "Cost History",
    "dimensions": [
        {
            "time": [
                {
                    "label": "Total",
                    "name": "total"
                },
                {
                    "name": "2021-12",
                    "label": "2021-12",
                    "direct": null,
                    "populated": false,
                    "excluded": null,
                    "extended": false,
                    "sort_order": null,
                    "parent": -1
                },
                {
                    "name": "2022-12",
                    "label": "2022-12",
                    "direct": null,
                    "populated": true,
                    "excluded": null,
                    "extended": false,
                    "sort_order": null,
                    "parent": -1
                }
                // etc... etc ....
            ]
        },
        {
            "Azure-Services": [
                {
                    "label": "Total",
                    "name": "total"
                },
                {
                    "name": "3000",
                    "label": "Storage",
                    "direct": null,
                    "populated": null,
                    "excluded": null,
                    "extended": false,
                    "sort_order": null,
                    "parent": -1
                },
                {
                    "name": "3001",
                    "label": "Storage Account",
                    "direct": true,
                    "populated": null,
                    "excluded": null,
                    "extended": false,
                    "sort_order": null,
                    "parent": 0
                }
                // .. etc etc
            ]
        }
    ],
    "measures": [
        {
            "name": "total_cost",
            "label": "Total Cost ($)",
            "metadata": {
                "type": "cost",
                "units": "CAD",
                "supports_drilldown": true,
                "label": "Total Cost ($)"
            }
        }
    ],
    "interval": "monthly",
    "filters": [
        "Azure-Services:select:4001,4012"
    ],
    "updated_at": "2022-12-10T06:17:08Z",
    "bill_drop_info": [],
    "visualization_options": null,
    "data": [
        [
            [
                8421.915094617003
            ],
            [
                null
            ],
            [
                null
            ],
            [
                null
            ]
        ],
        [
            [
                null
            ],
            [
                null
            ],
            [
                null
            ],
            [
                null
            ]
        ],
        [
            [
                null
            ],
            [
                null
            ],
            [
                null
            ],
            [
                null
            ]
        ],
        [
            [
                388.6801747227753
            ],
            [
                388.6801747227753
            ],
            [
                0.5626267227750004
            ],
            [
                388.1175480000003
            ]
        ],
        [
            [
                872.0477601498656
            ],
            [
                872.0477601498656
            ],
            [
                1.2152157498662994
            ],
            [
                870.8325443999993
            ]
        ]
    ],
    "status": "ok",
    "enable_dp_popover": false,
    "cube_id": "44326_0419_03"
}
</code>```

and I am getting response from my REST Api like this:

```<code>    {
    "responseMessage": "SUCCESS",
    "status": "OK",
    "statusCode": 1,
    "response": {
        "report": "Cost History",
        "dimensions": [
            {
                "time": [
                    {
                        "label": "Total",
                        "name": "total",
                        "direct": null,
                        "populated": false,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null,
                        "parent": 0
                    },
                    {
                        "label": "2021-12",
                        "name": "2021-12",
                        "direct": null,
                        "populated": false,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null,
                        "parent": -1
                    },
                    {
                        "label": "2022-12",
                        "name": "2022-12",
                        "direct": null,
                        "populated": true,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null,
                        "parent": -1
                    }
                ],
                "Azure-Services": []
            },
            {
                "time": [],
                "Azure-Services": [
                    {
                        "parent": 0,
                        "label": "Total",
                        "name": "total",
                        "direct": false,
                        "populated": null,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null
                    },
                    {
                        "parent": -1,
                        "label": "Storage",
                        "name": "3000",
                        "direct": false,
                        "populated": null,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null
                    },
                    {
                        "parent": 0,
                        "label": "Storage Account",
                        "name": "3001",
                        "direct": true,
                        "populated": null,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null
                    }
                ]
            }
        ],
        "measures": [
            {
                "name": "total_cost",
                "label": "Total Cost ($)",
                "metadata": {
                    "type": "cost",
                    "units": "CAD",
                    "label": "Total Cost ($)",
                    "supports_drilldown": true
                }
            }
        ],
        "interval": "monthly",
        "filters": [
            "Azure-Services:select:4001,4012"
        ],
        "data": [
            [
                [
                    8486.168096050156
                ],
                [
                    8486.168096050156
                ],
                [
                    9.860766100157399
                ],

                [
                    8476.30732995
                ]
            ],
            [
                [
                    null
                ],
                [
                    null
                ],
                [
                    null
                ],
                [
                    null
                ]
            ],
            [
                [
                    388.6801747227753
                ],
                [
                    388.6801747227753
                ],
                [
                    0.5626267227750004
                ],
                [
                    388.1175480000003
                ]
            ],
            [
                [
                    872.0477601498656
                ],
                [
                    872.0477601498656
                ],
                [
                    1.2152157498662994
                ],
                [
                    870.8325443999993
                ],
            ]
        ],
        "status": "ok",
        "updated_at": "2022-12-12T06:38:27Z",
        "bill_drop_info": [],
        "visualization_options": null,
        "enable_dp_popover": false,
        "cube_id": "44326_0419_03"
    }
}
</code>```

This is AzureService.java POJO class:

```<code>public class AzureService {
    @JsonProperty("label")
    private String label;

    @JsonProperty("name")
    private String name;

    @JsonProperty("direct")
    private boolean direct;

    @JsonProperty("populated")
    private Object populated;

    @JsonProperty("excluded")
    private Object excluded;

    @JsonProperty("extended")
    private boolean extended;

    @JsonProperty("sort_order")
    private Object sortOrder;

    private long parent;

}
</code>```

This is Time.java POJO class:

```<code>public class Time {
    @JsonProperty("label")
    private String timeLabel;

    @JsonProperty("name")
    private String timeName;

    @JsonProperty("direct")
    private Object timeDirect;

    @JsonProperty("populated")
    private boolean timePopulated;

    @JsonProperty("excluded")
    private Object timeExcluded;

    @JsonProperty("extended")
    private boolean timeExtended;

    @JsonProperty("sort_order")
    private Object timeSortOrder;

    @JsonProperty("parent")
    private long timeParent;

}
</code>```

Below is my Dimension.java POJO class:

```<code>@Getter
@Setter
public class Dimension {

    @JsonProperty("time")
    private List<Time> time = new ArrayList<Time>();

    @JsonProperty("Azure-Services")
    private List<AzureService> azureServices = new ArrayList<AzureService>();
}
</code>```

This is my CustomReport.java POJO:

```<code>@Getter
@Setter
public class CustomReport{
    private String report;
    private List<Dimension> dimensions = new ArrayList<Dimension>();
    private List<Measure> measures = new ArrayList<Measure>();
    private String interval;
    private List<String> filters = new ArrayList<String>();

    @JsonProperty("updated_at")
    private String updatedAt;

    @JsonProperty("bill_drop_info")
    private List<Object> billDropInfo = new ArrayList<Object>();

    @JsonProperty("visualization_options")
    private Object visualizationOptions;

    private List<List<List<Double>>> data = new ArrayList<List<List<Double>>>();
    private String status;

    @JsonProperty("enable_dp_popover")
    private boolean enableDpPopover;

    @JsonProperty("cube_id")
    private String cubeId;
}
</code>```

These two classes have properties. I am unable to figure out why these two object showing each others JSON Object response. So is there any JSON property or anything that I need to write before mapping JSON object to POJO?

Body:
How to map JSON object with POJO class in Spring Boot. I have JSON data as below:

    {
    "report": "Cost History",
    "dimensions": [
        {
            "time": [
                {
                    "label": "Total",
                    "name": "total"
                },
                {
                    "name": "2021-12",
                    "label": "2021-12",
                    "direct": null,
                    "populated": false,
                    "excluded": null,
                    "extended": false,
                    "sort_order": null,
                    "parent": -1
                },
                {
                    "name": "2022-12",
                    "label": "2022-12",
                    "direct": null,
                    "populated": true,
                    "excluded": null,
                    "extended": false,
                    "sort_order": null,
                    "parent": -1
                }
                // etc... etc ....
            ]
        },
        {
            "Azure-Services": [
                {
                    "label": "Total",
                    "name": "total"
                },
                {
                    "name": "3000",
                    "label": "Storage",
                    "direct": null,
                    "populated": null,
                    "excluded": null,
                    "extended": false,
                    "sort_order": null,
                    "parent": -1
                },
                {
                    "name": "3001",
                    "label": "Storage Account",
                    "direct": true,
                    "populated": null,
                    "excluded": null,
                    "extended": false,
                    "sort_order": null,
                    "parent": 0
                }
                // .. etc etc
            ]
        }
    ],
    "measures": [
        {
            "name": "total_cost",
            "label": "Total Cost ($)",
            "metadata": {
                "type": "cost",
                "units": "CAD",
                "supports_drilldown": true,
                "label": "Total Cost ($)"
            }
        }
    ],
    "interval": "monthly",
    "filters": [
        "Azure-Services:select:4001,4012"
    ],
    "updated_at": "2022-12-10T06:17:08Z",
    "bill_drop_info": [],
    "visualization_options": null,
    "data": [
        [
            [
                8421.915094617003
            ],
            [
                null
            ],
            [
                null
            ],
            [
                null
            ]
        ],
        [
            [
                null
            ],
            [
                null
            ],
            [
                null
            ],
            [
                null
            ]
        ],
        [
            [
                null
            ],
            [
                null
            ],
            [
                null
            ],
            [
                null
            ]
        ],
        [
            [
                388.6801747227753
            ],
            [
                388.6801747227753
            ],
            [
                0.5626267227750004
            ],
            [
                388.1175480000003
            ]
        ],
        [
            [
                872.0477601498656
            ],
            [
                872.0477601498656
            ],
            [
                1.2152157498662994
            ],
            [
                870.8325443999993
            ]
        ]
    ],
    "status": "ok",
    "enable_dp_popover": false,
    "cube_id": "44326_0419_03"
}

and I am getting response from my REST Api like this:

    {
    "responseMessage": "SUCCESS",
    "status": "OK",
    "statusCode": 1,
    "response": {
        "report": "Cost History",
        "dimensions": [
            {
                "time": [
                    {
                        "label": "Total",
                        "name": "total",
                        "direct": null,
                        "populated": false,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null,
                        "parent": 0
                    },
                    {
                        "label": "2021-12",
                        "name": "2021-12",
                        "direct": null,
                        "populated": false,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null,
                        "parent": -1
                    },
                    {
                        "label": "2022-12",
                        "name": "2022-12",
                        "direct": null,
                        "populated": true,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null,
                        "parent": -1
                    }
                ],
                "Azure-Services": []
            },
            {
                "time": [],
                "Azure-Services": [
                    {
                        "parent": 0,
                        "label": "Total",
                        "name": "total",
                        "direct": false,
                        "populated": null,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null
                    },
                    {
                        "parent": -1,
                        "label": "Storage",
                        "name": "3000",
                        "direct": false,
                        "populated": null,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null
                    },
                    {
                        "parent": 0,
                        "label": "Storage Account",
                        "name": "3001",
                        "direct": true,
                        "populated": null,
                        "excluded": null,
                        "extended": false,
                        "sort_order": null
                    }
                ]
            }
        ],
        "measures": [
            {
                "name": "total_cost",
                "label": "Total Cost ($)",
                "metadata": {
                    "type": "cost",
                    "units": "CAD",
                    "label": "Total Cost ($)",
                    "supports_drilldown": true
                }
            }
        ],
        "interval": "monthly",
        "filters": [
            "Azure-Services:select:4001,4012"
        ],
        "data": [
            [
                [
                    8486.168096050156
                ],
                [
                    8486.168096050156
                ],
                [
                    9.860766100157399
                ],

                [
                    8476.30732995
                ]
            ],
            [
                [
                    null
                ],
                [
                    null
                ],
                [
                    null
                ],
                [
                    null
                ]
            ],
            [
                [
                    388.6801747227753
                ],
                [
                    388.6801747227753
                ],
                [
                    0.5626267227750004
                ],
                [
                    388.1175480000003
                ]
            ],
            [
                [
                    872.0477601498656
                ],
                [
                    872.0477601498656
                ],
                [
                    1.2152157498662994
                ],
                [
                    870.8325443999993
                ],
            ]
        ],
        "status": "ok",
        "updated_at": "2022-12-12T06:38:27Z",
        "bill_drop_info": [],
        "visualization_options": null,
        "enable_dp_popover": false,
        "cube_id": "44326_0419_03"
    }
}

This is AzureService.java POJO class:

public class AzureService {
    @JsonProperty("label")
    private String label;

    @JsonProperty("name")
    private String name;

    @JsonProperty("direct")
    private boolean direct;

    @JsonProperty("populated")
    private Object populated;

    @JsonProperty("excluded")
    private Object excluded;

    @JsonProperty("extended")
    private boolean extended;

    @JsonProperty("sort_order")
    private Object sortOrder;

    private long parent;

}

This is Time.java POJO class:

public class Time {
    @JsonProperty("label")
    private String timeLabel;

    @JsonProperty("name")
    private String timeName;

    @JsonProperty("direct")
    private Object timeDirect;

    @JsonProperty("populated")
    private boolean timePopulated;

    @JsonProperty("excluded")
    private Object timeExcluded;

    @JsonProperty("extended")
    private boolean timeExtended;

    @JsonProperty("sort_order")
    private Object timeSortOrder;

    @JsonProperty("parent")
    private long timeParent;

}

Below is my Dimension.java POJO class:

@Getter
@Setter
public class Dimension {

    @JsonProperty("time")
    private List<Time> time = new ArrayList<Time>();

    @JsonProperty("Azure-Services")
    private List<AzureService> azureServices = new ArrayList<AzureService>();
}

This is my CustomReport.java POJO:

@Getter
@Setter
public class CustomReport{
    private String report;
    private List<Dimension> dimensions = new ArrayList<Dimension>();
    private List<Measure> measures = new ArrayList<Measure>();
    private String interval;
    private List<String> filters = new ArrayList<String>();

    @JsonProperty("updated_at")
    private String updatedAt;

    @JsonProperty("bill_drop_info")
    private List<Object> billDropInfo = new ArrayList<Object>();

    @JsonProperty("visualization_options")
    private Object visualizationOptions;

    private List<List<List<Double>>> data = new ArrayList<List<List<Double>>>();
    private String status;

    @JsonProperty("enable_dp_popover")
    private boolean enableDpPopover;

    @JsonProperty("cube_id")
    private String cubeId;
}

These two classes have properties. I am unable to figure out why these two object showing each others JSON Object response. So is there any JSON property or anything that I need to write before mapping JSON object to POJO?


来源: stackexchange

问:
Is termios supported in msys2? If not, is there a portable way of getting unbuffered I/O?
The following code works on linux:

```<code>include <termios.h>

using namespace std;
static struct termios old_terminal_settings;

void setterm() {
  tcgetattr(STDIN_FILENO, &old_terminal_settings);

  // Set terminal to unbuffered input mode
  struct termios new_terminal_settings = old_terminal_settings;
  new_terminal_settings.c_lflag &= ~ICANON;
  tcsetattr(STDIN_FILENO, TCSANOW, &new_terminal_settings);
}

void resetterm() {
  // Restore the original terminal settings
  tcsetattr(STDIN_FILENO, TCSANOW, &old_terminal_settings);

}

int main() {
  int c;
    setterm();
  while (c = getc(stdin)) {
    putc(c, stdout);
  }
    resetterm();
  return 0;
}
</code>```

When compiled under msys2 with:

```<code>g++ -g -I/usr/include term.cc
</code>```

it fails to link. I can't find any library with the missing symbols:

```<code>tcgetattr
tcsetattr
</code>```

I tried:

```<code>nm /usr/lib/*.a | grep tcgetattr
nm /mingw64/lib/*.s | grep tcsetattr
</code>```

Since there is an include file termios.h I assume there must be a library with the corresponding symbols? If so, how?

If not, is there anything else I can do?

I found a symbol containing the name _nc_term_tcgetattr and tcsetattr  in libncurses.a in /mingw64/lib but it's only part of the curses package. Presumably to use it I would have to use curses.

ContentLicense: CC BY-SA 4.0

Body:
The following code works on linux:

include <termios.h>

using namespace std;
static struct termios old_terminal_settings;

void setterm() {
  tcgetattr(STDIN_FILENO, &old_terminal_settings);

  // Set terminal to unbuffered input mode
  struct termios new_terminal_settings = old_terminal_settings;
  new_terminal_settings.c_lflag &= ~ICANON;
  tcsetattr(STDIN_FILENO, TCSANOW, &new_terminal_settings);
}

void resetterm() {
  // Restore the original terminal settings
  tcsetattr(STDIN_FILENO, TCSANOW, &old_terminal_settings);

}

int main() {
  int c;
    setterm();
  while (c = getc(stdin)) {
    putc(c, stdout);
  }
    resetterm();
  return 0;
}

When compiled under msys2 with:

g++ -g -I/usr/include term.cc

it fails to link. I can't find any library with the missing symbols:

tcgetattr
tcsetattr

I tried:

nm /usr/lib/*.a | grep tcgetattr
nm /mingw64/lib/*.s | grep tcsetattr

Since there is an include file termios.h I assume there must be a library with the corresponding symbols? If so, how?

If not, is there anything else I can do?

I found a symbol containing the name _nc_term_tcgetattr and tcsetattr  in libncurses.a in /mingw64/lib but it's only part of the curses package. Presumably to use it I would have to use curses.


问:
Display product tags on Woocommerce Shop Page
I would like to display product tags of the items shown on the product page.

The major complication with this is that is causes the theme to throw exceptions.

I wanted it to display the tags on the shop page

```<code>Uncaught TypeError: sizeof(): Argument #1 ($value) must be of type Countable|array, bool given in wp-content/themes/elessi-theme/functions.php:33Stack trace:#0 wp-includes/class-wp-hook.php(308): woocommerce_product_loop_tags(false)#1 wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters('', Array)#2 wp-includes/plugin.php(517): WP_Hook->do_action(Array)``

</code>```
```<code>add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_product_loop_tags', 5 );

function woocommerce_product_loop_tags() {
    global $post, $product;

    $tag_count = sizeof( get_the_terms( $post->ID, 'product_tag' ) );

    echo $product->get_tags( ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.</span>' );
}
</code>```

Body:
I would like to display product tags of the items shown on the product page.

The major complication with this is that is causes the theme to throw exceptions.

I wanted it to display the tags on the shop page

Uncaught TypeError: sizeof(): Argument #1 ($value) must be of type Countable|array, bool given in wp-content/themes/elessi-theme/functions.php:33Stack trace:#0 wp-includes/class-wp-hook.php(308): woocommerce_product_loop_tags(false)#1 wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters('', Array)#2 wp-includes/plugin.php(517): WP_Hook->do_action(Array)``

add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_product_loop_tags', 5 );

function woocommerce_product_loop_tags() {
    global $post, $product;

    $tag_count = sizeof( get_the_terms( $post->ID, 'product_tag' ) );

    echo $product->get_tags( ', ', '' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.' );
}


问:
statsmodels SARIMAX Model: large dip
I am using the statsmodels SARIMAX implementation to model the Consumer Price Index (CPI).

```<code>from statsmodels.tsa.statespace.sarimax import SARIMAX
import numpy as np
import pandas as pd

raw_data = pd.read_csv("CPI.csv")

cDataFrame = raw_data[raw_data["Country Name"] == "Italy"]
sDataFrame = cDataFrame[cDataFrame["Indicator Code"] == "PCPI_IX"][cDataFrame["Attribute"] == "Value"].transpose()[5:-2].astype('double')

ts = pd.Series(data=np.array(sDataFrame.iloc[:, 0]), index=sDataFrame.index)["1980M1":"1999M12"]

params = [(0, 1, 0), (0, 1, 1, 12)]
model = SARIMAX(endog=np.array(ts.to_numpy()), order=params[0], seasonal_order=params[1]).fit()
pd.Series(model.resid[1:]).plot()
</code>```

The resulting plot of the residuals seems rather odd:

This large dip at index 12 happens for most of the countries and really should not be there.

Here is the CPI of Italy for the selected time frame:

What am I missing?

Running statsmodels-0.13.5. Data was obtained from the IMF, uploaded it here.

Title: statsmodels SARIMAX Model: large dip

Body:
I am using the statsmodels SARIMAX implementation to model the Consumer Price Index (CPI).

from statsmodels.tsa.statespace.sarimax import SARIMAX
import numpy as np
import pandas as pd

raw_data = pd.read_csv("CPI.csv")

cDataFrame = raw_data[raw_data["Country Name"] == "Italy"]
sDataFrame = cDataFrame[cDataFrame["Indicator Code"] == "PCPI_IX"][cDataFrame["Attribute"] == "Value"].transpose()[5:-2].astype('double')

ts = pd.Series(data=np.array(sDataFrame.iloc[:, 0]), index=sDataFrame.index)["1980M1":"1999M12"]

params = [(0, 1, 0), (0, 1, 1, 12)]
model = SARIMAX(endog=np.array(ts.to_numpy()), order=params[0], seasonal_order=params[1]).fit()
pd.Series(model.resid[1:]).plot()

The resulting plot of the residuals seems rather odd:

This large dip at index 12 happens for most of the countries and really should not be there.

Here is the CPI of Italy for the selected time frame:

What am I missing?

Running statsmodels-0.13.5. Data was obtained from the IMF, uploaded it here.


问:
İs this a bug in Python at summation?
I think there is a bug in Python. When I wanted to sum an integer and a float number Python did it wrong.From GeeksForGeeks İ read "it is not a bug and it is problem of floating-point numbers".But i checked in C++ and the results was true.Why?

I wrote print(12+23.12) and the result was 35.120000000000005

Then I wrote print(23+12.23) and the result was 35.230000000000004

If this is not bug,please say this reason

Title: İs this a bug in Python at summation?


问:
"Abstract types are not supported" when deserialising ktor session data
I use kmongo with the kotlinx serialization library and the Id implementation

```<code>implementation("org.litote.kmongo:kmongo-id-serialization:4.8.0") // This is the dependency for the id implementation
</code>```

I declared my ktor deserialiser like that

```<code>    install(ContentNegotiation) {
        json(Json {
            prettyPrint = true
            serializersModule = IdKotlinXSerializationModule
        })
    }
</code>```

And then my session logic:

```<code>    install(Sessions) {
        cookie<UserSessionId>("user_session_id") {
            cookie.path = "/"
            cookie.maxAgeInSeconds = 604800 // 7 days
            cookie.secure = Env.cookie_secure
            cookie.httpOnly = true
        }
    }

    install(Authentication) {

        session<UserSessionId>("auth-session") {
            validate { userSessionId ->
                val session = UserSessionDao.get(userSessionId.session_id)

                // If there is no session or if it has expired (session expires after 7 days)
                if (session == null || (getTimeMillis() - session.iat) >= 604800000)
                    null
                else
                    session
            }
            challenge {
                call.respond(HttpStatusCode.Unauthorized)
            }
        }
    }
</code>```

My Principal makes use of the Id class from KMongo for type safety

```<code>@Serializable
data class UserSessionId(
    @Contextual val session_id: Id<UserSessionId>
) : Principal
</code>```

But when I try to make a request that uses the session, I get the following error when it tries to deserialise the session

```<code>2022-12-10 16:51:16.763 DEBUG ktor.application - Failed to deserialize session: session_id=%23%23id%3D%2523s167068733233394437bc688fc89377889a0dc16cf1105
java.lang.IllegalStateException: Abstract types are not supported: class org.litote.kmongo.Id
    at io.ktor.server.sessions.SessionSerializerReflection.findConstructor(SessionSerializerReflection.kt:142)
    at io.ktor.server.sessions.SessionSerializerReflection.newInstance(SessionSerializerReflection.kt:103)
    at io.ktor.server.sessions.SessionSerializerReflection.deserializeObject(SessionSerializerReflection.kt:411)
    at io.ktor.server.sessions.SessionSerializerReflection.deserializeValue(SessionSerializerReflection.kt:366)
    at io.ktor.server.sessions.SessionSerializerReflection.newInstance(SessionSerializerReflection.kt:114)
    at io.ktor.server.sessions.SessionSerializerReflection.deserializeObject(SessionSerializerReflection.kt:411)
    at io.ktor.server.sessions.SessionSerializerReflection.deserialize(SessionSerializerReflection.kt:89)
    at io.ktor.server.sessions.SessionTrackerByValue.load(SessionTrackerByValue.kt:24)
    at io.ktor.server.sessions.SessionDataKt.receiveSessionData(SessionData.kt:137)
    at io.ktor.server.sessions.SessionsKt$Sessions$2$1.invokeSuspend(Sessions.kt:41)
    at io.ktor.server.sessions.SessionsKt$Sessions$2$1.invoke(Sessions.kt)
    at io.ktor.server.sessions.SessionsKt$Sessions$2$1.invoke(Sessions.kt)
    at io.ktor.server.application.PluginBuilder$onCall$2.invokeSuspend(PluginBuilder.kt:90)
    at io.ktor.server.application.PluginBuilder$onCall$2.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onCall$2.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhase$1.invokeSuspend(PluginBuilder.kt:217)
    at io.ktor.server.application.PluginBuilder$onDefaultPhase$1.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhase$1.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1$1.invokeSuspend(PluginBuilder.kt:200)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1$1.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1$1.invoke(PluginBuilder.kt)
    at io.ktor.util.debug.ContextUtilsKt.addToContextInDebugMode(ContextUtils.kt:30)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1.invokeSuspend(PluginBuilder.kt:196)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1.invoke(PluginBuilder.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
    at io.ktor.server.engine.BaseApplicationEngineKt$installDefaultTransformationChecker$1.invokeSuspend(BaseApplicationEngine.kt:123)
    at io.ktor.server.engine.BaseApplicationEngineKt$installDefaultTransformationChecker$1.invoke(BaseApplicationEngine.kt)
    at io.ktor.server.engine.BaseApplicationEngineKt$installDefaultTransformationChecker$1.invoke(BaseApplicationEngine.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
    at io.ktor.server.application.hooks.CallFailed$install$1$1.invokeSuspend(CommonHooks.kt:43)
    at io.ktor.server.application.hooks.CallFailed$install$1$1.invoke(CommonHooks.kt)
    at io.ktor.server.application.hooks.CallFailed$install$1$1.invoke(CommonHooks.kt)
    at kotlinx.coroutines.intrinsics.UndispatchedKt.startUndispatchedOrReturn(Undispatched.kt:89)
    at kotlinx.coroutines.CoroutineScopeKt.coroutineScope(CoroutineScope.kt:264)
    at io.ktor.server.application.hooks.CallFailed$install$1.invokeSuspend(CommonHooks.kt:42)
    at io.ktor.server.application.hooks.CallFailed$install$1.invoke(CommonHooks.kt)
    at io.ktor.server.application.hooks.CallFailed$install$1.invoke(CommonHooks.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
    at io.ktor.util.pipeline.SuspendFunctionGun.execute$ktor_utils(SuspendFunctionGun.kt:101)
    at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1$invokeSuspend$$inlined$execute$1.invokeSuspend(Pipeline.kt:478)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1$invokeSuspend$$inlined$execute$1.invoke(Pipeline.kt)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1$invokeSuspend$$inlined$execute$1.invoke(Pipeline.kt)
    at io.ktor.util.debug.ContextUtilsKt.initContextInDebugMode(ContextUtils.kt:17)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1.invokeSuspend(DefaultEnginePipeline.kt:118)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1.invoke(DefaultEnginePipeline.kt)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1.invoke(DefaultEnginePipeline.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
    at io.ktor.util.pipeline.SuspendFunctionGun.execute$ktor_utils(SuspendFunctionGun.kt:101)
    at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1$invokeSuspend$$inlined$execute$1.invokeSuspend(Pipeline.kt:478)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1$invokeSuspend$$inlined$execute$1.invoke(Pipeline.kt)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1$invokeSuspend$$inlined$execute$1.invoke(Pipeline.kt)
    at io.ktor.util.debug.ContextUtilsKt.initContextInDebugMode(ContextUtils.kt:17)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invokeSuspend(NettyApplicationCallHandler.kt:119)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invoke(NettyApplicationCallHandler.kt)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invoke(NettyApplicationCallHandler.kt)
    at kotlinx.coroutines.intrinsics.UndispatchedKt.startCoroutineUndispatched(Undispatched.kt:55)
    at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:112)
    at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56)
    at kotlinx.coroutines.BuildersKt.launch(Unknown Source)
    at io.ktor.server.netty.NettyApplicationCallHandler.handleRequest(NettyApplicationCallHandler.kt:37)
    at io.ktor.server.netty.NettyApplicationCallHandler.channelRead(NettyApplicationCallHandler.kt:29)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61)
    at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
    at io.netty.util.concurrent.AbstractEventExecutor.runTask(AbstractEventExecutor.java:174)
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:167)
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:470)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:503)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.ktor.server.netty.EventLoopGroupProxy$Companion.create$lambda-1$lambda-0(NettyApplicationEngine.kt:288)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.base/java.lang.Thread.run(Thread.java:833)
</code>```

Does ktor not make use of the deserialiser I specified when trying to deserialising a session cookie?

Edit: answered in https://youtrack.jetbrains.com/issue/KTOR-5324

Body:
I use kmongo with the kotlinx serialization library and the Id implementation

implementation("org.litote.kmongo:kmongo-id-serialization:4.8.0") // This is the dependency for the id implementation

I declared my ktor deserialiser like that

    install(ContentNegotiation) {
        json(Json {
            prettyPrint = true
            serializersModule = IdKotlinXSerializationModule
        })
    }

And then my session logic:

    install(Sessions) {
        cookie<UserSessionId>("user_session_id") {
            cookie.path = "/"
            cookie.maxAgeInSeconds = 604800 // 7 days
            cookie.secure = Env.cookie_secure
            cookie.httpOnly = true
        }
    }

    install(Authentication) {

        session<UserSessionId>("auth-session") {
            validate { userSessionId ->
                val session = UserSessionDao.get(userSessionId.session_id)

                // If there is no session or if it has expired (session expires after 7 days)
                if (session == null || (getTimeMillis() - session.iat) >= 604800000)
                    null
                else
                    session
            }
            challenge {
                call.respond(HttpStatusCode.Unauthorized)
            }
        }
    }

My Principal makes use of the Id class from KMongo for type safety

@Serializable
data class UserSessionId(
    @Contextual val session_id: Id<UserSessionId>
) : Principal

But when I try to make a request that uses the session, I get the following error when it tries to deserialise the session

2022-12-10 16:51:16.763 DEBUG ktor.application - Failed to deserialize session: session_id=%23%23id%3D%2523s167068733233394437bc688fc89377889a0dc16cf1105
java.lang.IllegalStateException: Abstract types are not supported: class org.litote.kmongo.Id
    at io.ktor.server.sessions.SessionSerializerReflection.findConstructor(SessionSerializerReflection.kt:142)
    at io.ktor.server.sessions.SessionSerializerReflection.newInstance(SessionSerializerReflection.kt:103)
    at io.ktor.server.sessions.SessionSerializerReflection.deserializeObject(SessionSerializerReflection.kt:411)
    at io.ktor.server.sessions.SessionSerializerReflection.deserializeValue(SessionSerializerReflection.kt:366)
    at io.ktor.server.sessions.SessionSerializerReflection.newInstance(SessionSerializerReflection.kt:114)
    at io.ktor.server.sessions.SessionSerializerReflection.deserializeObject(SessionSerializerReflection.kt:411)
    at io.ktor.server.sessions.SessionSerializerReflection.deserialize(SessionSerializerReflection.kt:89)
    at io.ktor.server.sessions.SessionTrackerByValue.load(SessionTrackerByValue.kt:24)
    at io.ktor.server.sessions.SessionDataKt.receiveSessionData(SessionData.kt:137)
    at io.ktor.server.sessions.SessionsKt$Sessions$2$1.invokeSuspend(Sessions.kt:41)
    at io.ktor.server.sessions.SessionsKt$Sessions$2$1.invoke(Sessions.kt)
    at io.ktor.server.sessions.SessionsKt$Sessions$2$1.invoke(Sessions.kt)
    at io.ktor.server.application.PluginBuilder$onCall$2.invokeSuspend(PluginBuilder.kt:90)
    at io.ktor.server.application.PluginBuilder$onCall$2.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onCall$2.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhase$1.invokeSuspend(PluginBuilder.kt:217)
    at io.ktor.server.application.PluginBuilder$onDefaultPhase$1.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhase$1.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1$1.invokeSuspend(PluginBuilder.kt:200)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1$1.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1$1.invoke(PluginBuilder.kt)
    at io.ktor.util.debug.ContextUtilsKt.addToContextInDebugMode(ContextUtils.kt:30)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1.invokeSuspend(PluginBuilder.kt:196)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1.invoke(PluginBuilder.kt)
    at io.ktor.server.application.PluginBuilder$onDefaultPhaseWithMessage$1$1.invoke(PluginBuilder.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
    at io.ktor.server.engine.BaseApplicationEngineKt$installDefaultTransformationChecker$1.invokeSuspend(BaseApplicationEngine.kt:123)
    at io.ktor.server.engine.BaseApplicationEngineKt$installDefaultTransformationChecker$1.invoke(BaseApplicationEngine.kt)
    at io.ktor.server.engine.BaseApplicationEngineKt$installDefaultTransformationChecker$1.invoke(BaseApplicationEngine.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
    at io.ktor.server.application.hooks.CallFailed$install$1$1.invokeSuspend(CommonHooks.kt:43)
    at io.ktor.server.application.hooks.CallFailed$install$1$1.invoke(CommonHooks.kt)
    at io.ktor.server.application.hooks.CallFailed$install$1$1.invoke(CommonHooks.kt)
    at kotlinx.coroutines.intrinsics.UndispatchedKt.startUndispatchedOrReturn(Undispatched.kt:89)
    at kotlinx.coroutines.CoroutineScopeKt.coroutineScope(CoroutineScope.kt:264)
    at io.ktor.server.application.hooks.CallFailed$install$1.invokeSuspend(CommonHooks.kt:42)
    at io.ktor.server.application.hooks.CallFailed$install$1.invoke(CommonHooks.kt)
    at io.ktor.server.application.hooks.CallFailed$install$1.invoke(CommonHooks.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
    at io.ktor.util.pipeline.SuspendFunctionGun.execute$ktor_utils(SuspendFunctionGun.kt:101)
    at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1$invokeSuspend$$inlined$execute$1.invokeSuspend(Pipeline.kt:478)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1$invokeSuspend$$inlined$execute$1.invoke(Pipeline.kt)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1$invokeSuspend$$inlined$execute$1.invoke(Pipeline.kt)
    at io.ktor.util.debug.ContextUtilsKt.initContextInDebugMode(ContextUtils.kt:17)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1.invokeSuspend(DefaultEnginePipeline.kt:118)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1.invoke(DefaultEnginePipeline.kt)
    at io.ktor.server.engine.DefaultEnginePipelineKt$defaultEnginePipeline$1.invoke(DefaultEnginePipeline.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:123)
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:81)
    at io.ktor.util.pipeline.SuspendFunctionGun.execute$ktor_utils(SuspendFunctionGun.kt:101)
    at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1$invokeSuspend$$inlined$execute$1.invokeSuspend(Pipeline.kt:478)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1$invokeSuspend$$inlined$execute$1.invoke(Pipeline.kt)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1$invokeSuspend$$inlined$execute$1.invoke(Pipeline.kt)
    at io.ktor.util.debug.ContextUtilsKt.initContextInDebugMode(ContextUtils.kt:17)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invokeSuspend(NettyApplicationCallHandler.kt:119)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invoke(NettyApplicationCallHandler.kt)
    at io.ktor.server.netty.NettyApplicationCallHandler$handleRequest$1.invoke(NettyApplicationCallHandler.kt)
    at kotlinx.coroutines.intrinsics.UndispatchedKt.startCoroutineUndispatched(Undispatched.kt:55)
    at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:112)
    at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56)
    at kotlinx.coroutines.BuildersKt.launch(Unknown Source)
    at io.ktor.server.netty.NettyApplicationCallHandler.handleRequest(NettyApplicationCallHandler.kt:37)
    at io.ktor.server.netty.NettyApplicationCallHandler.channelRead(NettyApplicationCallHandler.kt:29)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61)
    at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
    at io.netty.util.concurrent.AbstractEventExecutor.runTask(AbstractEventExecutor.java:174)
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:167)
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:470)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:503)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.ktor.server.netty.EventLoopGroupProxy$Companion.create$lambda-1$lambda-0(NettyApplicationEngine.kt:288)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.base/java.lang.Thread.run(Thread.java:833)

Does ktor not make use of the deserialiser I specified when trying to deserialising a session cookie?

Edit: answered in https://youtrack.jetbrains.com/issue/KTOR-5324


问:
MaterialUI TextField not firing onChange when deleting whole field for first time
I have this textField component from Material UI.

```<code><TextField
      defaultValue={formObject.stockname}
      onChange={(e) => handleChange({ key: "stockname", value: e.target.value })
/>
</code>```

Problem is, after page refresh, defaultValue is being loaded, if on input field, I'll press CTRL+A and Delete button, it'll delete text, but once I click away, text returns and "formObject" remains unchanged. Meaning onChange does not fire, however, if I do it the second time, it works properly.

What could be the problem here? Thanks.

Body:
I have this textField component from Material UI.

<TextField
      defaultValue={formObject.stockname}
      onChange={(e) => handleChange({ key: "stockname", value: e.target.value })
/>

Problem is, after page refresh, defaultValue is being loaded, if on input field, I'll press CTRL+A and Delete button, it'll delete text, but once I click away, text returns and "formObject" remains unchanged. Meaning onChange does not fire, however, if I do it the second time, it works properly.

What could be the problem here? Thanks.


问:
program to store cubes of number which are greater than 2 and less than 30 using user defined exception
Write a program that receives 5 integers and stores them and their cubes in a dictionary. If the number entered is less than 3, raise a user-defined exception NumberTooSmall, and if the number entered is more than 30, then raise a user-defined exception NumberTooBig. Regardless of whether an exception occurs, print the dictionary’s contents at the end.

```<code>Sample Input:
4
5
6
7
77
Sample Output:
{'Number too big': 77}
4 : 64
5 : 125
6 : 216
7 : 343
</code>```

I wrote following code but it is not passing all test cases

```<code>n1,n2,n3,n4,n5 = int(input()),int(input()),int(input()),int(input()),int(input())
All = sorted([n1,n2,n3,n4,n5])

class NumberTooSmall(Exception):
    def __init__(self, args):
        self.num = args

class NumberTooBig(Exception):
    def __init__(self, args):
        self.num = args

dic = {}
try:
    for i in All:
        if i <3:
            raise NumberTooSmall(i)
        elif i> 30:
            raise NumberTooBig(i)
        else:
            dic[i] = i**3
except NumberTooSmall as numtosmall:
    dic = {**{'NumberTooSmall':numtosmall.num},**dic}
except NumberTooBig as numtobig:
    dic = {**{'NumberTooBig':numtobig.num},**dic}

keypairs = list(zip(dic.keys(),dic.values()))

for i in keypairs:
    if i[0] == 'NumberTooSmall' or i[0] == 'NumberTooBig':
        print('{'+str(i[0]+' ',':',' '+str(i[1])+'}'))
    else:
        print(str(i[0])+' ',':',' '+str(i[1]))
</code>```

Body:
Write a program that receives 5 integers and stores them and their cubes in a dictionary. If the number entered is less than 3, raise a user-defined exception NumberTooSmall, and if the number entered is more than 30, then raise a user-defined exception NumberTooBig. Regardless of whether an exception occurs, print the dictionary’s contents at the end.

Sample Input:
4
5
6
7
77
Sample Output:
{'Number too big': 77}
4 : 64
5 : 125
6 : 216
7 : 343

I wrote following code but it is not passing all test cases

n1,n2,n3,n4,n5 = int(input()),int(input()),int(input()),int(input()),int(input())
All = sorted([n1,n2,n3,n4,n5])

class NumberTooSmall(Exception):
    def __init__(self, args):
        self.num = args

class NumberTooBig(Exception):
    def __init__(self, args):
        self.num = args

dic = {}
try:
    for i in All:
        if i <3:
            raise NumberTooSmall(i)
        elif i> 30:
            raise NumberTooBig(i)
        else:
            dic[i] = i**3
except NumberTooSmall as numtosmall:
    dic = {**{'NumberTooSmall':numtosmall.num},**dic}
except NumberTooBig as numtobig:
    dic = {**{'NumberTooBig':numtobig.num},**dic}

keypairs = list(zip(dic.keys(),dic.values()))

for i in keypairs:
    if i[0] == 'NumberTooSmall' or i[0] == 'NumberTooBig':
        print('{'+str(i[0]+' ',':',' '+str(i[1])+'}'))
    else:
        print(str(i[0])+' ',':',' '+str(i[1]))


问:
Need Assistance with a Compilation Error on PineScript
I am very new to PineScript and coding in general but interested in finance and trading bots. I have this code that I think is decent but I keep running into an error that says "Compilation error. Script could not be translated from: null". I am trying to run the trading bot for Bitcoin "BTC" but not sure where I should put this distinction in the code. Any help would be greatly appreciated.

```<code>// Define the trading parameters
strategy("My Trading Strategy", overlay=true)

length = input(14, minval=1)
fastMA = input(12, minval=1)
slowMA = input(26, minval=1)
signalMA = input(9, minval=1)
risk = input(0.01, minval=0.0001, maxval=0.1)
position = input(1, minval=1)

// Calculate the moving averages
fastMA = ema(close, fastMA)
slowMA = ema(close, slowMA)

// Calculate the MACD
macd = fastMA - slowMA
signal = sma(macd, signalMA)

// Check if the MACD values are valid
if !isnan(macd) and !isnan(signal)
    // Calculate the Fibonacci levels
    ret = fibonacci(length)

    // Calculate the Sharpe ratio
    sharpe = (macd - signal) / stdev(macd, signalMA)

    // Calculate the Kelly criterion
    kelly = (macd - signal) / stdev(macd, signalMA)
    if kelly > 0
        kelly = 1 / (1 + (1 - kelly) / kelly)
    else
        kelly = (1 + kelly) / (1 - kelly)

    // Calculate the optimal f ratio
    f_opt = (kelly * sharpe) / (1 + kelly)

    // Calculate the Monte Carlo simulation
    monte_carlo = (macd - signal) / stdev(macd, signalMA)

    // Calculate the Value at Risk (VaR)
    var = (macd - signal) / stdev(macd, signalMA)

    // Calculate the Black-Litterman model
    black_litterman = (macd - signal) / stdev(macd, signalMA)

    // Calculate the mean-variance optimization (MVO)
    mvo = (macd - signal) / stdev(macd, signalMA)

    // Define the trading logic
    if (macd > signal)
        // Calculate the position size using the Black-Litterman model
        trade_amount = (black_litterman * account.equity) / (position * (high[1] - ret*atr(length)))
        // Place the trade
        strategy.entry("Long", strategy.long, stop=high[1] - ret*atr(length), qty=trade_amount, comment="Buy")
    else
        strategy.close("Long", comment="Sell")

    if (macd < signal)
        // Calculate the position size using the mean-variance optimization (MVO) method
        trade_amount = (mvo * account.equity) / (position * (low[1] + ret*atr(length)))
        // Place the trade
        strategy.entry("Short", strategy.short, stop=low[1] + ret*atr(length), qty=trade_amount, comment="Sell")
    else
        strategy.close("Short", comment="Buy")

// If the MACD is not valid, do not place trades
else
    strategy.close("Long", comment="Invalid MACD")
    strategy.close("Short", comment="Invalid MACD")
</code>```

I am pretty much at my maximum at this point. I have asked my friends that code, but they are not familiar with PineScript or finance for that matter.

Body:
I am very new to PineScript and coding in general but interested in finance and trading bots. I have this code that I think is decent but I keep running into an error that says "Compilation error. Script could not be translated from: null". I am trying to run the trading bot for Bitcoin "BTC" but not sure where I should put this distinction in the code. Any help would be greatly appreciated.

// Define the trading parameters
strategy("My Trading Strategy", overlay=true)

length = input(14, minval=1)
fastMA = input(12, minval=1)
slowMA = input(26, minval=1)
signalMA = input(9, minval=1)
risk = input(0.01, minval=0.0001, maxval=0.1)
position = input(1, minval=1)

// Calculate the moving averages
fastMA = ema(close, fastMA)
slowMA = ema(close, slowMA)

// Calculate the MACD
macd = fastMA - slowMA
signal = sma(macd, signalMA)

// Check if the MACD values are valid
if !isnan(macd) and !isnan(signal)
    // Calculate the Fibonacci levels
    ret = fibonacci(length)

    // Calculate the Sharpe ratio
    sharpe = (macd - signal) / stdev(macd, signalMA)

    // Calculate the Kelly criterion
    kelly = (macd - signal) / stdev(macd, signalMA)
    if kelly > 0
        kelly = 1 / (1 + (1 - kelly) / kelly)
    else
        kelly = (1 + kelly) / (1 - kelly)

    // Calculate the optimal f ratio
    f_opt = (kelly * sharpe) / (1 + kelly)

    // Calculate the Monte Carlo simulation
    monte_carlo = (macd - signal) / stdev(macd, signalMA)

    // Calculate the Value at Risk (VaR)
    var = (macd - signal) / stdev(macd, signalMA)

    // Calculate the Black-Litterman model
    black_litterman = (macd - signal) / stdev(macd, signalMA)

    // Calculate the mean-variance optimization (MVO)
    mvo = (macd - signal) / stdev(macd, signalMA)

    // Define the trading logic
    if (macd > signal)
        // Calculate the position size using the Black-Litterman model
        trade_amount = (black_litterman * account.equity) / (position * (high[1] - ret*atr(length)))
        // Place the trade
        strategy.entry("Long", strategy.long, stop=high[1] - ret*atr(length), qty=trade_amount, comment="Buy")
    else
        strategy.close("Long", comment="Sell")

    if (macd < signal)
        // Calculate the position size using the mean-variance optimization (MVO) method
        trade_amount = (mvo * account.equity) / (position * (low[1] + ret*atr(length)))
        // Place the trade
        strategy.entry("Short", strategy.short, stop=low[1] + ret*atr(length), qty=trade_amount, comment="Sell")
    else
        strategy.close("Short", comment="Buy")

// If the MACD is not valid, do not place trades
else
    strategy.close("Long", comment="Invalid MACD")
    strategy.close("Short", comment="Invalid MACD")

I am pretty much at my maximum at this point. I have asked my friends that code, but they are not familiar with PineScript or finance for that matter.


问:
Securing request for files in Spring
how I can secure user files in spring ?

For example: I have registered users, and they upload documents into server and stored to some location of the server.
How I can secure user files by username (Or any param) that another user does not access the files of the current (authorized)?

Title: Securing request for files in Spring


问:
How can I set my x higher? I need it to be at least 1000e8, but the I get a overflow error
How do I prevent the Overflow Error? It only happens once I set my x higher than 400e4 I need it to go at least to 1000e5
I need the derivative of the function f and after that I would like to plot it for different gamma. It works fine, when I set my x low enough. How do I get rid of the overflow though?
The results I am Expecting are in the range of e-8 - e-9, I only need numbers with about 20 digits</p>
```<code>import sympy as smp
import matplotlib.pyplot as plt
import numpy as np

x, k_1, k_2, k_3, T_0, T_S, T, f_p, gamma = smp.symbols('x k_1 k_2 k_3 T_0 T_S T f_p gamma', real=True)
aT = 10**((8.86*(T_0 - T_S)/(101.6 + (T_0 - T_S))-(8.86*(T-T_S-f_p*x)/(101.6+(T-T_S)))))
f = smp.log((k_1 * aT) / ((1 + gamma * k_2 * aT) ** k_3))

dfdx = smp.diff(f, x)
dfdx_f = smp.lambdify((gamma, x, k_1, k_2, k_3, T_0, T_S, T, f_p), dfdx)
gamma = np.linspace(0, 10000, 1000)

y = (dfdx_f(gamma,  x=400e5, k_1=1000, k_2=0.01, k_3=0.94, T_0=243.9243, T_S=178.73, T=250.0, f_p=0.001001412))
plt.plot(gamma, y)
</code>```

Body:
How do I prevent the Overflow Error? It only happens once I set my x higher than 400e4 I need it to go at least to 1000e5
I need the derivative of the function f and after that I would like to plot it for different gamma. It works fine, when I set my x low enough. How do I get rid of the overflow though?
The results I am Expecting are in the range of e-8 - e-9, I only need numbers with about 20 digits

import sympy as smp
import matplotlib.pyplot as plt
import numpy as np

x, k_1, k_2, k_3, T_0, T_S, T, f_p, gamma = smp.symbols('x k_1 k_2 k_3 T_0 T_S T f_p gamma', real=True)
aT = 10**((8.86*(T_0 - T_S)/(101.6 + (T_0 - T_S))-(8.86*(T-T_S-f_p*x)/(101.6+(T-T_S)))))
f = smp.log((k_1 * aT) / ((1 + gamma * k_2 * aT) ** k_3))

dfdx = smp.diff(f, x)
dfdx_f = smp.lambdify((gamma, x, k_1, k_2, k_3, T_0, T_S, T, f_p), dfdx)
gamma = np.linspace(0, 10000, 1000)

y = (dfdx_f(gamma,  x=400e5, k_1=1000, k_2=0.01, k_3=0.94, T_0=243.9243, T_S=178.73, T=250.0, f_p=0.001001412))
plt.plot(gamma, y)


问:
how to make download feature work on hosted backend
My team is working on a react app built with a nodejs backend which is hosted on vercel. now we have a feature that converts data collected to pdf to view and download in the browser. this works locally, but online it gives a 504 error. i'm not sure why and I'm not very good at backend. the frontend was hosted on netlify.

Here are the functions that downloads the pdf, converts the data to pdf and view the pdf

```<code>const downloadTermSheet = (id, name) => {
    ApiGet(`transaction/termSheet/${id}`).then(res => {
        let data = res.data.data
        if(name === 'view'){
            ViewRiskAssessment(data)
        } else if (name === 'download'){
            converBase64toBlob(data);
        }
    }
    ).catch(e => console.log(e))
}

const converBase64toBlob = (content, contentType) => {
    const linkSource = `data:application/pdf;base64,${content}`;
    const downloadLink = document.createElement("a");
    const fileName = "TermSheet.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();

}
const ViewRiskAssessment = (contents) => {
    const linkSources = `data:application/pdf;base64,${contents}`;
    let pdfWindow = window.open("")
    pdfWindow.document.write(`<iframe width='100%' height='100%' src=${linkSources}></iframe>`)
}
</code>```

in the backend, when I run the DB locally, it works as normal. when I click on download termsheet, it downloads the pdf file. if I click on view, it views the pdf file in the browser. but none of these work in the hosted backend link on vercel.

Body:
My team is working on a react app built with a nodejs backend which is hosted on vercel. now we have a feature that converts data collected to pdf to view and download in the browser. this works locally, but online it gives a 504 error. i'm not sure why and I'm not very good at backend. the frontend was hosted on netlify.

Here are the functions that downloads the pdf, converts the data to pdf and view the pdf

const downloadTermSheet = (id, name) => {
    ApiGet(`transaction/termSheet/${id}`).then(res => {
        let data = res.data.data
        if(name === 'view'){
            ViewRiskAssessment(data)
        } else if (name === 'download'){
            converBase64toBlob(data);
        }
    }
    ).catch(e => console.log(e))
}

const converBase64toBlob = (content, contentType) => {
    const linkSource = `data:application/pdf;base64,${content}`;
    const downloadLink = document.createElement("a");
    const fileName = "TermSheet.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();

}
const ViewRiskAssessment = (contents) => {
    const linkSources = `data:application/pdf;base64,${contents}`;
    let pdfWindow = window.open("")
    pdfWindow.document.write(`<iframe width='100%' height='100%' src=${linkSources}></iframe>`)
}

in the backend, when I run the DB locally, it works as normal. when I click on download termsheet, it downloads the pdf file. if I click on view, it views the pdf file in the browser. but none of these work in the hosted backend link on vercel.


问:
entityType can get and save data
I've 4 entities Company, Network, Customer and Process.

I don't know why I use fucntion create and edit don't save process in my DB !

Cutomers Netwoks and Compny this saved well.

Perhaps I forget somethings.

Some one can help please.

Company Form `

```<code><?php

namespace App\Form;

use App\Entity\Company;
use App\Entity\Process;
use App\Form\NetworkType;
use App\Form\CustomerType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TelType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class CompanyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name', TextType::class, [
                'label' => 'Nom',
                'required' => 'true',
                'attr' => [
                    'class' => 'mt-1',
                ],
                'label_attr' => [
                    'class' => 'mt-1'
                ],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Ce champ ne peut-être vide'
                    ])
                ]
            ])
            ->add('phone', TelType::class, [
                'required' => 'true',
                'label' => 'Téléphone',
                'attr' => [
                    'class' => 'mt-1',
                    'placeholder' => 'xx xx xx xx xx'
                ],
                'label_attr' => [
                    'class' => 'mt-1'
                ],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Ce champ ne peut-être vide'
                    ])
                ]
            ])
            ->add('location', TextType::class, [
                'label' => 'Ville',
                'required' => 'true',
                'attr' => [
                    'class' => 'mt-1'
                ],
                'label_attr' => [
                    'class' => 'mt-1'
                ],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Ce champ ne peut-être vide'
                    ])
                ]
            ])
            ->add('customers', CollectionType::class, [
                'entry_type' => CustomerType::class,
                'entry_options' => ['label' => false],
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'label' => false
            ])
            ->add('networks', CollectionType::class, [
                'entry_type' => NetworkType::class,
                'entry_options' => ['label' => false],
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'label' => false
            ])
            ->add('processes', EntityType::class, [
                'class' => Process::class,
                // 'entry_options' => ['label' => false],
                // 'allow_add' => true,
                // 'allow_delete' => true,
                // 'by_reference' => false,
                'choice_label' => 'software',
                'label' => 'process',
                'multiple' => true,
                // 'expanded' => true
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Company::class,
        ]);
    }
}
</code>```

Company View

```<code>{% extends 'base.html.twig' %}

{% block title %}
    {{company.name}}
{% endblock %}

{% block body %}

    <nav class="navbar navbar-expand bg-light navbar-light sticky-top px-4 py-0">
        {% include "navigation/_nav-horizontal.html.twig" %}
    </nav>
    <div class="container-fluid pt-4 px-4">
        <div class="row row-cols-1 row-cols-md-3 g-4">
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title text-center">Process</h5>
                        {% for process in company.processes %}
                            {# {% for key in process.software %} #}
                                <p class="card-text">{{process.software}}</p>
                            {# {% endfor %} #}
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title text-center">Architecture réseau</h5>
                        {% for network in company.networks %}
                            <h6>{{network.title}}</h6>
                            <p class="card-text">{{network.content}}</p>
                            {% if network.attachment %}
                                <p class="card-text">{{network.attachment}}</p>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title text-center">Contacts</h5>
                        {% for customer in company.customers %}
                            <!-- Button trigger modal -->
                            <button type="button" class="btn btn-outline-info" data-bs-toggle="modal" data-bs-target="#{{customer.firstname}}">
                                {{customer.firstname}}
                            </button>

                            <!-- Modal -->
                            <div class="modal fade" id="{{customer.firstname}}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h1 class="modal-title fs-5" id="exampleModalLabel">{{customer.firstname}}</h1>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="my-3">{{customer.firstname}}</div>
                                            <div class="my-3">{{customer.lastname}}</div>
                                            <div class="my-3">{{customer.mobile}}</div>
                                            <div class="my-3">{{customer.email}}</div>
                                            <div>
                                                <a class="btn btn-primary" href="#" role="button">Modifier</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    {% include "partiel/_footer.html.twig" %}
{% endblock %}

</code>```

Company Controller

```<code><?php

namespace App\Controller;

use App\Entity\Company;
use App\Form\CompanyType;
use App\Repository\CompanyRepository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class CompanyController extends AbstractController
{
    #[Route('/company', name: 'company', methods: ['GET'])]
    public function index(CompanyRepository $repo, PaginatorInterface $paginator, Request $request): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $companies = $repo->findAll();
        $companies = $paginator->paginate(
            $companies, /* query NOT result */
            $request->query->getInt('page', 1), /*page number*/
            15 /*limit per page*/
        );
        return $this->render('company/index.html.twig', [
            'companies' => $companies,
        ]);
    }

    #[Route('/company/add', name: 'company_add', methods: ['GET', 'POST'])]
    #[Route('/company/edit/{slug}', name: 'company_edit', methods: ['GET', 'POST'])]
    public function addOrEdit(Company $company = null, Request $request, EntityManagerInterface $em): Response
    {
        $user = $this->getUser();

        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

        $message = 'Société modifié avec succès';
        $messageType = 'info';
        if (is_null($company)) {
            $company = new Company();
            $message = 'Société ajouté avec succès';
            $messageType = 'success';
        }
        $form = $this->createForm(CompanyType::class, $company);
        $form->handleRequest($request);
        // dd($form);

        if ($form->isSubmitted() && $form->isValid()) {
            // dd($form);
            // Ajout de Contacts
            foreach ($company->getCustomers() as $customer) {
                $customer->setIsActive(true);
            }
            $company->setIsActive(true);
            // dd($company);
            $em->persist($company->setUser($user));
            $em->flush();
            $this->addFlash($messageType, $message);

            return $this->redirectToRoute('company');
        }

        return $this->renderForm('company/add_or_edit.html.twig', [
            'company' => $company,
            'form' => $form,
        ]);
    }

    #[Route('/company/{slug}', name: 'company_show', methods: ['GET'])]
    public function show(Company $company): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        if (!$company) {
            throw $this->createNotFoundException('La société est introuvable');
        }
// dd($company);
        return $this->render('company/show.html.twig', [
            'company' => $company,
        ]);
    }

    #[Route('/company/status/{slug}', name: 'company_status', methods: ['GET'])]
    public function status(Company $company, ManagerRegistry $doctrine): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        if (!$company) {
            throw $this->createNotFoundException('La société est introuvable');
        }
        $oldStatus = $company->getIsActive();
        if ($oldStatus === true) {
            $newStatus = false;
        } else {
            $newStatus = true;
        }
        $company->setIsActive($newStatus);

        $em = $doctrine->getManager();
        $em->flush();

        return $this->redirectToRoute('company');
    }
}

</code>```

`

Thank's indeed

I try to get a add or edit Company but I can't get and save processes

Title: entityType can get and save data

Body:
I've 4 entities Company, Network, Customer and Process.

I don't know why I use fucntion create and edit don't save process in my DB !

Cutomers Netwoks and Compny this saved well.

Perhaps I forget somethings.

Some one can help please.

Company Form `

<?php

namespace App\Form;

use App\Entity\Company;
use App\Entity\Process;
use App\Form\NetworkType;
use App\Form\CustomerType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TelType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class CompanyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name', TextType::class, [
                'label' => 'Nom',
                'required' => 'true',
                'attr' => [
                    'class' => 'mt-1',
                ],
                'label_attr' => [
                    'class' => 'mt-1'
                ],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Ce champ ne peut-être vide'
                    ])
                ]
            ])
            ->add('phone', TelType::class, [
                'required' => 'true',
                'label' => 'Téléphone',
                'attr' => [
                    'class' => 'mt-1',
                    'placeholder' => 'xx xx xx xx xx'
                ],
                'label_attr' => [
                    'class' => 'mt-1'
                ],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Ce champ ne peut-être vide'
                    ])
                ]
            ])
            ->add('location', TextType::class, [
                'label' => 'Ville',
                'required' => 'true',
                'attr' => [
                    'class' => 'mt-1'
                ],
                'label_attr' => [
                    'class' => 'mt-1'
                ],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Ce champ ne peut-être vide'
                    ])
                ]
            ])
            ->add('customers', CollectionType::class, [
                'entry_type' => CustomerType::class,
                'entry_options' => ['label' => false],
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'label' => false
            ])
            ->add('networks', CollectionType::class, [
                'entry_type' => NetworkType::class,
                'entry_options' => ['label' => false],
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'label' => false
            ])
            ->add('processes', EntityType::class, [
                'class' => Process::class,
                // 'entry_options' => ['label' => false],
                // 'allow_add' => true,
                // 'allow_delete' => true,
                // 'by_reference' => false,
                'choice_label' => 'software',
                'label' => 'process',
                'multiple' => true,
                // 'expanded' => true
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Company::class,
        ]);
    }
}

Company View

{% extends 'base.html.twig' %}

{% block title %}
    {{company.name}}
{% endblock %}

{% block body %}

        {% include "navigation/_nav-horizontal.html.twig" %}

Process

                        {% for process in company.processes %}
                            {# {% for key in process.software %} #}

{{process.software}}

                            {# {% endfor %} #}
                        {% endfor %}

Architecture réseau

                        {% for network in company.networks %}

{{network.title}}

{{network.content}}

                            {% if network.attachment %}

{{network.attachment}}

                            {% endif %}
                        {% endfor %}

Contacts

                        {% for customer in company.customers %}

                            <button type="button" class="btn btn-outline-info" data-bs-toggle="modal" data-bs-target="#{{customer.firstname}}">
                                {{customer.firstname}}
                            </button>

{{customer.firstname}}

                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

{{customer.firstname}}

{{customer.lastname}}

{{customer.mobile}}

{{customer.email}}

                                                Modifier

                        {% endfor %}

    {% include "partiel/_footer.html.twig" %}
{% endblock %}

Company Controller

<?php

namespace App\Controller;

use App\Entity\Company;
use App\Form\CompanyType;
use App\Repository\CompanyRepository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class CompanyController extends AbstractController
{
    #[Route('/company', name: 'company', methods: ['GET'])]
    public function index(CompanyRepository $repo, PaginatorInterface $paginator, Request $request): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $companies = $repo->findAll();
        $companies = $paginator->paginate(
            $companies, /* query NOT result */
            $request->query->getInt('page', 1), /*page number*/
            15 /*limit per page*/
        );
        return $this->render('company/index.html.twig', [
            'companies' => $companies,
        ]);
    }

    #[Route('/company/add', name: 'company_add', methods: ['GET', 'POST'])]
    #[Route('/company/edit/{slug}', name: 'company_edit', methods: ['GET', 'POST'])]
    public function addOrEdit(Company $company = null, Request $request, EntityManagerInterface $em): Response
    {
        $user = $this->getUser();

        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

        $message = 'Société modifié avec succès';
        $messageType = 'info';
        if (is_null($company)) {
            $company = new Company();
            $message = 'Société ajouté avec succès';
            $messageType = 'success';
        }
        $form = $this->createForm(CompanyType::class, $company);
        $form->handleRequest($request);
        // dd($form);

        if ($form->isSubmitted() && $form->isValid()) {
            // dd($form);
            // Ajout de Contacts
            foreach ($company->getCustomers() as $customer) {
                $customer->setIsActive(true);
            }
            $company->setIsActive(true);
            // dd($company);
            $em->persist($company->setUser($user));
            $em->flush();
            $this->addFlash($messageType, $message);

            return $this->redirectToRoute('company');
        }

        return $this->renderForm('company/add_or_edit.html.twig', [
            'company' => $company,
            'form' => $form,
        ]);
    }

    #[Route('/company/{slug}', name: 'company_show', methods: ['GET'])]
    public function show(Company $company): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        if (!$company) {
            throw $this->createNotFoundException('La société est introuvable');
        }
// dd($company);
        return $this->render('company/show.html.twig', [
            'company' => $company,
        ]);
    }

    #[Route('/company/status/{slug}', name: 'company_status', methods: ['GET'])]
    public function status(Company $company, ManagerRegistry $doctrine): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        if (!$company) {
            throw $this->createNotFoundException('La société est introuvable');
        }
        $oldStatus = $company->getIsActive();
        if ($oldStatus === true) {
            $newStatus = false;
        } else {
            $newStatus = true;
        }
        $company->setIsActive($newStatus);

        $em = $doctrine->getManager();
        $em->flush();

        return $this->redirectToRoute('company');
    }
}

`

Thank's indeed

I try to get a add or edit Company but I can't get and save processes


问:
Cant write a value to a txt file in r+ mode with either fwrite() or fprintf
Okay so i get some values from the user and then i save them to a txt file called orders.txt
and it looks like this

```<code>Marios22    100.000000  3000.000000 Sat Dec 10 18:20:32 `F!v
</code>```

This is the function which i use to get my values and write to

```<code>struct order RegisterOrder(){
    FILE *ft;
    struct order o;
    time_t temp;
    char temp1[20];

    printf("Enter the name of the customer:");
    scanf("%s",&o.onoma);
    printf("Enter The number of the small bottles:\n");
    scanf("%f",&o.smallbnum);
    printf("Enter The number of the big bottles:\n");
    scanf("%f",&o.bigbnum);

    time(&temp);   // dinei to execution date

    strcpy(o.executiondate,ctime(&temp));

    ft=fopen("orders.txt","a"); // creates and opens a file called orders.txt
    fprintf(ft,"%s\t%f\t%f\t%s\n", o.onoma, o.smallbnum, o.bigbnum, o.executiondate);
    fclose(ft);

    return o;
}
</code>```

Now next i want to call the CalculateCost() function in order to calculate o.cost and write it into the txt file but it doesnt work and reamains unchanged

```<code>struct order calculateCost(struct order o){
    float discount;
    float finalcost;
    float smallbnum, bigbnum;
    FILE *ft;
    ft=fopen("orders.txt", "r+");
    fscanf(ft,"%f %f", &o.smallbnum, &o.bigbnum);

    o.cost=(o.smallbnum*SMALLPRICE + o.bigbnum*BIGPRICE);

    if (o.cost>600)
        discount=0.2;
    else if ((o.cost>200)|| (o.bigbnum+o.smallbnum>3000)){
        discount=0.08;}

        finalcost = o.cost *(1-discount);
        o.cost=finalcost;

        fprintf(ft,"%g\t", o.cost);
        //fwrite(&o.cost, sizeof(float), 1, ft);

        printf("The cost is:%f\n",finalcost);
        fclose(ft);

        return o;

}
</code>```

I tried for example: r+ mode/ a+ mode or using

```<code>fwrite(&o.cost, sizeof(float), 1, ft);
</code>```

or

```<code>fprintf(ft,"%g\t", o.cost);
</code>```

but i just cant get it to write anything

Body:
Okay so i get some values from the user and then i save them to a txt file called orders.txt
and it looks like this

Marios22    100.000000  3000.000000 Sat Dec 10 18:20:32 `F!v

This is the function which i use to get my values and write to

struct order RegisterOrder(){
    FILE *ft;
    struct order o;
    time_t temp;
    char temp1[20];

    printf("Enter the name of the customer:");
    scanf("%s",&o.onoma);
    printf("Enter The number of the small bottles:\n");
    scanf("%f",&o.smallbnum);
    printf("Enter The number of the big bottles:\n");
    scanf("%f",&o.bigbnum);

    time(&temp);   // dinei to execution date

    strcpy(o.executiondate,ctime(&temp));

    ft=fopen("orders.txt","a"); // creates and opens a file called orders.txt
    fprintf(ft,"%s\t%f\t%f\t%s\n", o.onoma, o.smallbnum, o.bigbnum, o.executiondate);
    fclose(ft);

    return o;
}

Now next i want to call the CalculateCost() function in order to calculate o.cost and write it into the txt file but it doesnt work and reamains unchanged

struct order calculateCost(struct order o){
    float discount;
    float finalcost;
    float smallbnum, bigbnum;
    FILE *ft;
    ft=fopen("orders.txt", "r+");
    fscanf(ft,"%f %f", &o.smallbnum, &o.bigbnum);

    o.cost=(o.smallbnum*SMALLPRICE + o.bigbnum*BIGPRICE);

    if (o.cost>600)
        discount=0.2;
    else if ((o.cost>200)|| (o.bigbnum+o.smallbnum>3000)){
        discount=0.08;}

        finalcost = o.cost *(1-discount);
        o.cost=finalcost;

        fprintf(ft,"%g\t", o.cost);
        //fwrite(&o.cost, sizeof(float), 1, ft);

        printf("The cost is:%f\n",finalcost);
        fclose(ft);

        return o;

}

I tried for example: r+ mode/ a+ mode or using

fwrite(&o.cost, sizeof(float), 1, ft);

or

fprintf(ft,"%g\t", o.cost);

but i just cant get it to write anything


问:
angularFireAuth.signInWithPopup not working in Web View of Mobile Apps
I have an Angular Web App that User AngularFire Auth which is a Angular plugin for Firebase.

I am using the below code to login with Google:

```<code>this.angularFireAuth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then(
  // login success
  userInfo => {
      console.log(userInfo);
      alert(`Welcome ${userInfo.user.displayName}`)
      this._router.navigate( [''] )
   },
      // login fail
      error => {
        alert('Login failed. Please try again.')
      }
)
</code>```

The login works well when opened in a regular Desktop or Mobile browser but when I open the link from Instagram or TikTok ads which open an inner Web View Window the login is not working.

I see the below error when opening the link from IOS Instagram App:

```<code>Eroare 403: disallowed _useragent
You can't sign in from this screen because this app doesn't
comply with Google's secure browsers policy. If this app has
a website, you can open a web browser and try signing in
from there.
You can let the app developer know that this app doesn't
comply with Google's secure browsers policy.
</code>```

Is there a solution for this? Basically people who click the link in ads of a mobile app they can't create an account through Google.

Body:
I have an Angular Web App that User AngularFire Auth which is a Angular plugin for Firebase.

I am using the below code to login with Google:

this.angularFireAuth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then(
  // login success
  userInfo => {
      console.log(userInfo);
      alert(`Welcome ${userInfo.user.displayName}`)
      this._router.navigate( [''] )
   },
      // login fail
      error => {
        alert('Login failed. Please try again.')
      }
)

The login works well when opened in a regular Desktop or Mobile browser but when I open the link from Instagram or TikTok ads which open an inner Web View Window the login is not working.

I see the below error when opening the link from IOS Instagram App:

Eroare 403: disallowed _useragent
You can't sign in from this screen because this app doesn't
comply with Google's secure browsers policy. If this app has
a website, you can open a web browser and try signing in
from there.
You can let the app developer know that this app doesn't
comply with Google's secure browsers policy.

Is there a solution for this? Basically people who click the link in ads of a mobile app they can't create an account through Google.


问:
How to mix asynchronous request handling with synchronous in microservice architecture
I have an API gateway that interacts with services. At the moment, the gateway accepts HTTP requests from various external servers, calls a certain service, waits for processing (for example, transactions, authorizations, etc.) and returns a response to the external server. But now one of the servers wants us to accept asynchronous requests, but only for transaction processing (only for certain endpoints). How should I properly mix async and sync request handling. Should I handle this in the gateway or in the service that process the transactions?

I drew simple diagrams showing the request processing flow.
Requests flow


问:
TencentCloud CDN vs ECDN vs GAAP
Any TencentCloud users out there?

Tencent CDN and Tencent ECDN used to have 2 different consoles in TencentCloud. Then, around July 2021 the two have been merged into a single CDN console with two different "Acceleration types" to choose from. While creating a new CDN, it gives you a choice saying:

CDN accelerates static content, while ECDN accelerates dynamic content.

Fine. That's a fair difference.

Now, enter Tencent GAAP (Global Application Acceleration Platform). From its product overview and descriptions, it tends to feel like a ECDN?

I am wondering what is the actual difference between a ECDN and a GAAP. And when should I use one over the other?

Title: TencentCloud CDN vs ECDN vs GAAP


问:
Android - how to separate and manage the core module of a few apps?
I have two similar Android apps - each one is dedicated to the users in different country. Despite the fact that, the core functions are the same, I develop them separately. Each time I provide a new feature to one of them, I need to repeat all the development for the other. My aim is to separate the core code in one module to make the process easier.

The best workflow for me would be:

I develop some new feature in App1. It requires new code in Core module and, maybe, some changes in the code that is specific for App1.

I release App1

I merge all the Core changes to App2 with git.

I write App2 specific code if needed.

I release App2.

The question is: how to do it properly in Android Studio? Shall I create a new project and then include it as a module to both apps? The other important thing is: how to organize git repositories? Any advice is very welcome.


问:
Using Retrofit 2 and Aws Signed Url to Upload File
I'm trying to upload a file to Amazon's S3 using a pre-signed URL. I get the URL from a server which generates the URL. I already successfully used this URL and postman to upload a file to s3.

Now I want to do the same with Retrofit in android. To do that, I have written the following code:

```<code>@PUT
    Call<Void> updateImage(@Url String url, @Body RequestBody image);
</code>```
```<code>String CONTENT = "application/zip";

                        RequestBody requestFile = RequestBody.create(MediaType.parse(CONTENT), gpxfile);

                        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("http://www.dummy.com/")
                                .build();

                        APIService imageInterface = retrofit.create(APIService.class);

                        Call<Void> call = imageInterface.updateImage(url, requestFile);
                        call.enqueue(new Callback<Void>() {
                            @Override
                            public void onResponse(Call<Void> call, Response<Void> response) {
                                Log.d(response.message(), response.raw().toString());
                            }

                            @Override
                            public void onFailure(Call<Void> call, Throwable t) {

                            }
                        });
</code>```

But the response i get is: Forbidden: Response{protocol=http/1.1, code=403, message=Forbidden, url=https://...

Can you tell me what i am doing wrong or provide me an tutorial to fix this?

Body:
I'm trying to upload a file to Amazon's S3 using a pre-signed URL. I get the URL from a server which generates the URL. I already successfully used this URL and postman to upload a file to s3.

Now I want to do the same with Retrofit in android. To do that, I have written the following code:

@PUT
    Call<Void> updateImage(@Url String url, @Body RequestBody image);

String CONTENT = "application/zip";

                        RequestBody requestFile = RequestBody.create(MediaType.parse(CONTENT), gpxfile);

                        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("http://www.dummy.com/")
                                .build();

                        APIService imageInterface = retrofit.create(APIService.class);

                        Call<Void> call = imageInterface.updateImage(url, requestFile);
                        call.enqueue(new Callback<Void>() {
                            @Override
                            public void onResponse(Call<Void> call, Response<Void> response) {
                                Log.d(response.message(), response.raw().toString());
                            }

                            @Override
                            public void onFailure(Call<Void> call, Throwable t) {

                            }
                        });

But the response i get is: Forbidden: Response{protocol=http/1.1, code=403, message=Forbidden, url=https://...

Can you tell me what i am doing wrong or provide me an tutorial to fix this?


问:
How to use isomorphic Apollo link with nextjs 13?
I tried to use this, but it doesn't work with app directory. This got an error:
error - ./node_modules/nexus/dist-esm/typegenAutoConfig.js:55:0
Module not found: Can't resolve 'fs'</p>


问:
Feature not found when predicting?
Why does the following code produce an error?

The error is still present even if I remove the CO-APPLICANT feature.

I'm using the censored package in R

```<code>remotes::install_github("tidymodels/censored")
library(censored)

cph_fit <-
  proportional_hazards() %>%
  fit(Surv(DURATION, DEFAULT) ~ . , data = train)

applicant <- data.frame(
  PURPOSE = "Radio/Tv",
  SEX= "Male_single",
  RESIDENCE = "Own_res",
  PROPERTY = "Real_Estate",
  CHK_ACCT = "<0",

  HISTORY = "2",
  AMOUNT = 3200,
  SAV_ACCT = "1",
  EMPLOYMENT = "1Yr<=...<4Yr",
  INSTALL_RATE = 2,

  `CO-APPLICANT` = "Yes",
  GUARANTOR = "No",

  PRESENT_RESIDENT = "2Yr<...<=3Yr",
  AGE = 35,
  OTHER_INSTALL = "No",
  NUM_CREDITS = 2,
  JOB = "SkilledEmployee/Official",
  NUM_DEPENDENTS = 2,
  TELEPHONE = "Yes",
  FOREIGN = "No"
)

predict(cph_fit, applicant, type = "survival", time = 1:30)
</code>```

Error in eval(predvars, data, env) : object 'CO-APPLICANT' not found

OwnerDisplayName: Antonio

Title: Feature not found when predicting?

Body:
Why does the following code produce an error?

The error is still present even if I remove the CO-APPLICANT feature.

I'm using the censored package in R

remotes::install_github("tidymodels/censored")
library(censored)

cph_fit <-
  proportional_hazards() %>%
  fit(Surv(DURATION, DEFAULT) ~ . , data = train)

applicant <- data.frame(
  PURPOSE = "Radio/Tv",
  SEX= "Male_single",
  RESIDENCE = "Own_res",
  PROPERTY = "Real_Estate",
  CHK_ACCT = "<0",

  HISTORY = "2",
  AMOUNT = 3200,
  SAV_ACCT = "1",
  EMPLOYMENT = "1Yr<=...<4Yr",
  INSTALL_RATE = 2,

  `CO-APPLICANT` = "Yes",
  GUARANTOR = "No",

  PRESENT_RESIDENT = "2Yr<...<=3Yr",
  AGE = 35,
  OTHER_INSTALL = "No",
  NUM_CREDITS = 2,
  JOB = "SkilledEmployee/Official",
  NUM_DEPENDENTS = 2,
  TELEPHONE = "Yes",
  FOREIGN = "No"
)

predict(cph_fit, applicant, type = "survival", time = 1:30)

Error in eval(predvars, data, env) : object 'CO-APPLICANT' not found