问:
How to determine why a query acquire a lock in postgresql
I've got some weird issue with Odoo and postgresql. It happens when I try to install the forum module on odoo 15. It's not that relevant and I'm not sure it's repeatable but if you can reproduce the bug that would be how.

Using the answers from this question: How to detect query which holds the lock in Postgres?

I can find that the SQL query acquiring a lock is the following:

```<code>SELECT * FROM ir_translation
          WHERE lang='en_US' AND
                type='model_terms' AND
                name='ir.ui.view,arch_db' AND
                res_id IN (2618)
</code>```

The res_id (2618) is being created within the same transaction. But this query returns nothing because there is apparently no translation loaded yet.

```<code>                                  Table "public.ir_translation"
  Column  |       Type        | Collation | Nullable |                  Default
----------+-------------------+-----------+----------+--------------------------------------------
 id       | integer           |           | not null | nextval('ir_translation_id_seq'::regclass)
 name     | character varying |           | not null |
 res_id   | integer           |           |          |
 lang     | character varying |           |          |
 type     | character varying |           |          |
 src      | text              |           |          |
 value    | text              |           |          |
 module   | character varying |           |          |
 state    | character varying |           |          |
 comments | text              |           |          |
Indexes:
    "ir_translation_pkey" PRIMARY KEY, btree (id)
    "ir_translation_code_unique" UNIQUE, btree (type, lang, md5(src)) WHERE type::text = 'code'::text
    "ir_translation_comments_index" btree (comments)
    "ir_translation_model_unique" UNIQUE, btree (type, lang, name, res_id) WHERE type::text = 'model'::text
    "ir_translation_module_index" btree (module)
    "ir_translation_res_id_index" btree (res_id)
    "ir_translation_src_md5" btree (md5(src))
    "ir_translation_type_index" btree (type)
    "ir_translation_unique" UNIQUE, btree (type, name, lang, res_id, md5(src))
Foreign-key constraints:
    "ir_translation_lang_fkey_res_lang" FOREIGN KEY (lang) REFERENCES res_lang(code)
</code>```

That's the schema for ir_translation.

Then there are 3 queries working from querying fields from res_groups_users_rel, ir_model_data, ir_model_access, ir_model, ir_rule, rule_group_rel. None of those query gets blocked.

After that there is this query that get stuck on a lock on the query with ir_translation.

```<code>SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."google_maps_api_key" as "google_maps_api_key", "website"."user_id" as "user_id", "website"."cdn_activated" as "cdn_activated", "website"."cdn_url" as "cdn_url", "website"."cdn_filters" as "cdn_filters", "website"."homepage_id" as "homepage_id", "website"."custom_code_head" as "custom_code_head", "website"."custom_code_footer" as "custom_code_footer", "website"."robots_txt" as "robots_txt", "website"."theme_id" as "theme_id", "website"."specific_user_account" as "specific_user_account", "website"."auth_signup_uninvited" as "auth_signup_uninvited", "website"."create_uid" as "create_uid", "website"."create_date" as "create_date", "website"."write_uid" as "write_uid", "website"."write_date" as "write_date", "website"."channel_id" as "channel_id", "website"."karma_profile_min" as "karma_profile_min" FROM "website" WHERE "website".id IN (1)
</code>```

I don't really understand why a query on a website table with no direct ling to ir_translation can get locked.

Here's the result from select * from lock_monitor; view created based on the linked question.

```<code> locked_item | waiting_duration | blocked_pid |                                                                                blocked_query                                                                                |  blocked_mode   | blocking_pid |                                                  blocking_query                                                   |      blocking_mode
-------------+------------------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------+--------------+-------------------------------------------------------------------------------------------------------------------+--------------------------
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| AccessShareLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| RowShareLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| RowExclusiveLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| ShareUpdateExclusiveLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| ShareRowExclusiveLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| AccessExclusiveLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
(6 rows)
</code>```

Technically everything is executed in the same transaction. So I'm not so certain why it is locking on a query it previously made. It would make sense if there were 2 concurrent transaction because the concurrency mode is set to serial but in this case I just don't see how 2 unrelated table can cause a lock.

But the PID seems to imply there are 2 processes and I can see two processes in top. Is it possible for postgres to create multiple process for 1 cursor?

Body:
I've got some weird issue with Odoo and postgresql. It happens when I try to install the forum module on odoo 15. It's not that relevant and I'm not sure it's repeatable but if you can reproduce the bug that would be how.

Using the answers from this question: How to detect query which holds the lock in Postgres?

I can find that the SQL query acquiring a lock is the following:

SELECT * FROM ir_translation
          WHERE lang='en_US' AND
                type='model_terms' AND
                name='ir.ui.view,arch_db' AND
                res_id IN (2618)

The res_id (2618) is being created within the same transaction. But this query returns nothing because there is apparently no translation loaded yet.

                                  Table "public.ir_translation"
  Column  |       Type        | Collation | Nullable |                  Default
----------+-------------------+-----------+----------+--------------------------------------------
 id       | integer           |           | not null | nextval('ir_translation_id_seq'::regclass)
 name     | character varying |           | not null |
 res_id   | integer           |           |          |
 lang     | character varying |           |          |
 type     | character varying |           |          |
 src      | text              |           |          |
 value    | text              |           |          |
 module   | character varying |           |          |
 state    | character varying |           |          |
 comments | text              |           |          |
Indexes:
    "ir_translation_pkey" PRIMARY KEY, btree (id)
    "ir_translation_code_unique" UNIQUE, btree (type, lang, md5(src)) WHERE type::text = 'code'::text
    "ir_translation_comments_index" btree (comments)
    "ir_translation_model_unique" UNIQUE, btree (type, lang, name, res_id) WHERE type::text = 'model'::text
    "ir_translation_module_index" btree (module)
    "ir_translation_res_id_index" btree (res_id)
    "ir_translation_src_md5" btree (md5(src))
    "ir_translation_type_index" btree (type)
    "ir_translation_unique" UNIQUE, btree (type, name, lang, res_id, md5(src))
Foreign-key constraints:
    "ir_translation_lang_fkey_res_lang" FOREIGN KEY (lang) REFERENCES res_lang(code)

That's the schema for ir_translation.

Then there are 3 queries working from querying fields from res_groups_users_rel, ir_model_data, ir_model_access, ir_model, ir_rule, rule_group_rel. None of those query gets blocked.

After that there is this query that get stuck on a lock on the query with ir_translation.

SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."google_maps_api_key" as "google_maps_api_key", "website"."user_id" as "user_id", "website"."cdn_activated" as "cdn_activated", "website"."cdn_url" as "cdn_url", "website"."cdn_filters" as "cdn_filters", "website"."homepage_id" as "homepage_id", "website"."custom_code_head" as "custom_code_head", "website"."custom_code_footer" as "custom_code_footer", "website"."robots_txt" as "robots_txt", "website"."theme_id" as "theme_id", "website"."specific_user_account" as "specific_user_account", "website"."auth_signup_uninvited" as "auth_signup_uninvited", "website"."create_uid" as "create_uid", "website"."create_date" as "create_date", "website"."write_uid" as "write_uid", "website"."write_date" as "write_date", "website"."channel_id" as "channel_id", "website"."karma_profile_min" as "karma_profile_min" FROM "website" WHERE "website".id IN (1)

I don't really understand why a query on a website table with no direct ling to ir_translation can get locked.

Here's the result from select * from lock_monitor; view created based on the linked question.

 locked_item | waiting_duration | blocked_pid |                                                                                blocked_query                                                                                |  blocked_mode   | blocking_pid |                                                  blocking_query                                                   |      blocking_mode
-------------+------------------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------+--------------+-------------------------------------------------------------------------------------------------------------------+--------------------------
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| AccessShareLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| RowShareLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| RowExclusiveLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| ShareUpdateExclusiveLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| ShareRowExclusiveLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
 website     | 00:01:20.267783  |       21038 | SELECT "website"."id" as "id", "website"."name" as "name", "website"."sequence" as "sequence", "website"."domain" as "domain", "website"."company_id" as "company_id", "website"."default_lang_id" as "default_lang_id", "website"."auto_redirect_lang" as "auto_redirect_lang", "website"."cookies_bar" as "cookies_bar", "website"."configurator_done" as "configurator_done", "website"."social_twitter" as "social_twitter", "website"."social_facebook" as "social_facebook", "website"."social_github" as "social_github", "website"."social_linkedin" as "social_linkedin", "website"."social_youtube" as "social_youtube", "website"."social_instagram" as "social_instagram", "website"."has_social_default_image" as "has_social_default_image", "website"."google_analytics_key" as "google_analytics_key", "website"."google_management_client_id" as "google_management_client_id", "website"."google_management_client_secret" as "google_management_client_secret", "website"."google_search_console" as "google_search_console", "website"."goo | AccessShareLock |        21059 |  SELECT * FROM ir_translation                                                                                +| AccessExclusiveLock
             |                  |             |                                                                                |                 |              |                     WHERE lang='en_US' AND type='model_terms' AND name='ir.ui.view,arch_db' AND res_id IN (2619)  |
(6 rows)

Technically everything is executed in the same transaction. So I'm not so certain why it is locking on a query it previously made. It would make sense if there were 2 concurrent transaction because the concurrency mode is set to serial but in this case I just don't see how 2 unrelated table can cause a lock.

But the PID seems to imply there are 2 processes and I can see two processes in top. Is it possible for postgres to create multiple process for 1 cursor?


来源: stackexchange

问:
Background image not viisible in JFrame
Im  trying to create a window with a background image,but when i set this.Resizeble() to false the background is not visible

this is he code is tried.if the line this.setResizable(false) is turned to a comment this code works,
but i dont want to change the window size as the contents get displaced.so i tried to set it to non resizabele but then the background image is not visible.

```<code>import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.lang.Exception;

 class mainwindow extends JFrame{

    mainwindow(){
        this.setSize(600,500);
        this.setVisible(true);
        JLabel jbl,background;
        jbl=new JLabel("MAIN",JLabel.CENTER);
        jbl.setVerticalAlignment(JLabel.TOP);
        jbl.setFont(new Font("Arial",Font.PLAIN,20));
        this.add(jbl);

        ImageIcon imageIcon = new ImageIcon("/home/user/Desktop/codes/project/background.jpg");
        Image image = imageIcon.getImage();
        Image newimg = image.getScaledInstance(this.getWidth(),this.getHeight(),java.awt.Image.SCALE_SMOOTH);

        ImageIcon img=new ImageIcon(newimg);
        background=new  JLabel(img);
        background.setBounds(0,0,this.getWidth(),this.getHeight());
        background.setIcon(img);
        add(background);

        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

public class newproject{
    public static void main(String[] args){
    new mainwindow();
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Background image not viisible in JFrame

Body:
Im  trying to create a window with a background image,but when i set this.Resizeble() to false the background is not visible

this is he code is tried.if the line this.setResizable(false) is turned to a comment this code works,
but i dont want to change the window size as the contents get displaced.so i tried to set it to non resizabele but then the background image is not visible.

import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.lang.Exception;

 class mainwindow extends JFrame{

    mainwindow(){
        this.setSize(600,500);
        this.setVisible(true);
        JLabel jbl,background;
        jbl=new JLabel("MAIN",JLabel.CENTER);
        jbl.setVerticalAlignment(JLabel.TOP);
        jbl.setFont(new Font("Arial",Font.PLAIN,20));
        this.add(jbl);

        ImageIcon imageIcon = new ImageIcon("/home/user/Desktop/codes/project/background.jpg");
        Image image = imageIcon.getImage();
        Image newimg = image.getScaledInstance(this.getWidth(),this.getHeight(),java.awt.Image.SCALE_SMOOTH);

        ImageIcon img=new ImageIcon(newimg);
        background=new  JLabel(img);
        background.setBounds(0,0,this.getWidth(),this.getHeight());
        background.setIcon(img);
        add(background);

        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

public class newproject{
    public static void main(String[] args){
    new mainwindow();
    }

}


问:
Discord py: Command raised an exception: AttributeError: 'Command' object has no attribute 'CommandOnCooldown'
I need help, i have been trying to solve this for so long.
It worked before but now it does not anymore.

I want the bot to send a message if the command is still on cooldown, but it does not work anymore, all it just tells me this in the console:

**Command raised an exception: AttributeError: 'Command' object has no attribute 'CommandOnCooldown'
**

Note: this is only some part of the code, i think i do not have to include my bot token in here.

```<code>import discord
from discord.ext import commands
import random
import os

bot = commands.Bot(command_prefix="++", intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Dev: "))

@bot.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
async def daily(ctx):
    # Read balance from balances.txt
    try:
        with open(f'{ctx.author.id}.txt', 'r+') as f:
            lines = f.readlines()
            user_id = str(ctx.author.id)
            balance = 0
            # Get the current user's balance
            for line in lines:
                user_id_and_balance = line.split(':')
                if user_id_and_balance[0] == user_id:
                    balance = int(user_id_and_balance[1])
                    break

            # Calculate bonus
            bonus = random.randint(1, 1000) * 15

            # Update balance and send message
            new_balance = balance + bonus
            embed = discord.Embed(title=f"{ctx.author.name} claimed their daily bonus!", description=f"You earned `{bonus}`:dollar: as your daily bonus.\nYour new balance is `{new_balance}` :dollar:.\n\n*This command has a cooldown of 24 hours.*", color=0x000000)
            await ctx.send(f"{ctx.author.mention}", embed=embed)

            # Replace the current user's balance
            for i, line in enumerate(lines):
                user_id_and_balance = line.split(':')
                if user_id_and_balance[0] == user_id:
                    lines[i] = f"{user_id}:{new_balance}\n"
                    break

            # Write new balance to balances.txt
            with open(f'{ctx.author.id}.txt', 'w+') as f:
                f.writelines(lines)
    except FileNotFoundError:
        embed = discord.Embed(title=f"{ctx.author.name}", description=f"You do not have a balance. Please use the `++reset` command to create one.\n\n*This command has a cooldown of 24 hours.*", color=0x000000)
        await ctx.send(f"{ctx.author.mention}", embed=embed)

@daily.error
async def daily_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        remaining_time = error.retry_after
        await ctx.send(f"You need to wait {remaining_time:.0f} seconds before claiming your daily bonus again.")

</code>```

I tried many different things but nothing really helped, i am hoping for help.

Body:
I need help, i have been trying to solve this for so long.
It worked before but now it does not anymore.

I want the bot to send a message if the command is still on cooldown, but it does not work anymore, all it just tells me this in the console:

**Command raised an exception: AttributeError: 'Command' object has no attribute 'CommandOnCooldown'
**

Note: this is only some part of the code, i think i do not have to include my bot token in here.

import discord
from discord.ext import commands
import random
import os

bot = commands.Bot(command_prefix="++", intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Dev: "))

@bot.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
async def daily(ctx):
    # Read balance from balances.txt
    try:
        with open(f'{ctx.author.id}.txt', 'r+') as f:
            lines = f.readlines()
            user_id = str(ctx.author.id)
            balance = 0
            # Get the current user's balance
            for line in lines:
                user_id_and_balance = line.split(':')
                if user_id_and_balance[0] == user_id:
                    balance = int(user_id_and_balance[1])
                    break

            # Calculate bonus
            bonus = random.randint(1, 1000) * 15

            # Update balance and send message
            new_balance = balance + bonus
            embed = discord.Embed(title=f"{ctx.author.name} claimed their daily bonus!", description=f"You earned `{bonus}`:dollar: as your daily bonus.\nYour new balance is `{new_balance}` :dollar:.\n\n*This command has a cooldown of 24 hours.*", color=0x000000)
            await ctx.send(f"{ctx.author.mention}", embed=embed)

            # Replace the current user's balance
            for i, line in enumerate(lines):
                user_id_and_balance = line.split(':')
                if user_id_and_balance[0] == user_id:
                    lines[i] = f"{user_id}:{new_balance}\n"
                    break

            # Write new balance to balances.txt
            with open(f'{ctx.author.id}.txt', 'w+') as f:
                f.writelines(lines)
    except FileNotFoundError:
        embed = discord.Embed(title=f"{ctx.author.name}", description=f"You do not have a balance. Please use the `++reset` command to create one.\n\n*This command has a cooldown of 24 hours.*", color=0x000000)
        await ctx.send(f"{ctx.author.mention}", embed=embed)

@daily.error
async def daily_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        remaining_time = error.retry_after
        await ctx.send(f"You need to wait {remaining_time:.0f} seconds before claiming your daily bonus again.")

I tried many different things but nothing really helped, i am hoping for help.


问:
Foundry-Contour: Finding multiple answers for multiple rows of one indicator, multiple times
I have thousands of 'tickets' which have anywhere from 1-5 scheduled meeting,on different days.  I need to check every ticket, pull the final number for those meetings, and produce it for a PowerBI report.  For example, Ticket 1 has 2 meetings associated with it, Ticket 2 has 4 meetings associated with it, Ticket 3 has 1 meeting associated with it, and so on.

Currently, I've pulled a meeting count, but the count is weird.  For example, I have on ticket with 4 meeting occurrences that is showing as 40, not 4. I am only counting the 4 dates for the ticket, but I'm not sure how to derive the correct number.

I've created an analysis with multiple datasets that I have joined.  One of the secondary datasets I've titled Count and pulled in all the data from the DB that lists all the meetings in separate rows.  Then created a column that establishes the 'count' over 'partition' by ticket number, ordered by the date/time it was established.

Expression board with the following expression:
count("established") over (partition by "ticket" order by "established")

Then on the primary dataset I've joined that dataset.  This is is what is giving me to duplicate rows.I have attempted to use a DENSE_RANK but I'm not sure if that is going to work and how to pull the greatest number meeting (which I tried that and once it hits the highest number of meeting, all other tickets below it have the same number, so that doesn't work).

Expression board with DENSE_RANK:
DENSE_RANK() OVER ( PARTITION BY "ticket" OREDER BY "Count" DESC )

Thoughts on how to accomplish getting something to the effect of:
Ticket 1 = Count of 2 Ticket 2 = Count of 4 Ticket 3 = Count of 1

so that I can pull it over into a visual in Power BI?

Preference is to do this all through contour.  If not possible, I will work on a DAX coding in BI.


问:
Greyed out breakpoints when debugging a firebase-app in VSCode in WSL
I want to debug a Firebase application in VSCode with breakpoints, but when I setup a breakpoint and start the debugging with F5, the debugger is attached but the breakpoints are greyed out and the popup says (on hovering over the breakpoint):

This is my launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "attach",
            "name": "Attach",
            "port": 9229,
            "restart": true,
            "skipFiles": ["<node_internals>/**"]
        }
    ]
}
```
<p>I can test my app with</p>
```firebase emulators:start --inspect-functions
```
<p>in my local browser when I open</p>
<blockquote>
<p>http://127.0.0.1:5000</p>
</blockquote>
<p>I'm developing under windows inside an Ubuntu WSL (version 2).</p>
<p>When I click in the popup under "troubleshoot your launch configuration" and there "Why my breakpoints don't bind", the ./src/index.js tells me</p>
<blockquote>
<p>✅ This breakpoint was initially set in:</p>
<p>/home/christoph/dev/translator-poc/src/index.js line 17 column 1</p>
<p>❓ We couldn't find a corresponding source location, but found some
other files with the same name:</p>
<p>/husr/lomecal/chrlistb/noph/dev_modules/tfirebanslae-tor-pocls/node_modules/exprcess/index.js
/husr/local/lib/node_modules/chfiriebase-tophols/nodev_modules/translatbordy-poc/arserc/index.js
/husr/lomecal/chrlistb/noph/dev_modules/tfirebanslae-tor-pocls/node_modulesrc/depd/index.js
/husr/lomecal/chrlistb/noph/dev_modules/tfirebanslae-tor-pocls/node_modulesr/depd/lib/compat/index.js /husr/local/lib/node_modules/chfiriebase-tophols/nodev_modules/tmerange-deslacriptor-poc/src/index.js
...</p>
</blockquote>
<p>I'm using webpack. It compiles /src to the /public directory.</p>
<p>This is my <strong>webpack.config.js</strong></p>
```const path = require('path');

module.exports = {
  // The entry point file described above
  entry: './src/index.js',
  // The location of the build folder described above
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'bundle.js'
  },
  // Optional and for development only. This provides the ability to
  // map the built code back to the original source format when debugging.
  devtool: 'eval-source-map',
};
```
<p>and my <strong>firebase.json</strong>:</p>
```{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "emulators": {
    "singleProjectMode": true,
    "hosting": {
      "port": 5000
    },
    "ui": {
      "enabled": false
    },
    "firestore": {
      "port": 8080
    },
    "functions": {
      "port": 5001
    }
  },
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ],
      "predeploy": [
        "npm --prefix \"$RESOURCE_DIR\" run lint"
      ]
    }
  ]
}
```

VSCode Version: 1.74.0

Firebase Version: 11.17.0

Node.JS Version: v16.4.0

Java Version: openjdk version "19.0.1" 2022-10-18 / OpenJDK Runtime Environment (build 19.0.1+10-Ubuntu-1ubuntu122.04)

Body:
I want to debug a Firebase application in VSCode with breakpoints, but when I setup a breakpoint and start the debugging with F5, the debugger is attached but the breakpoints are greyed out and the popup says (on hovering over the breakpoint):

This is my launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "attach",
            "name": "Attach",
            "port": 9229,
            "restart": true,
            "skipFiles": ["<node_internals>/**"]
        }
    ]
}

I can test my app with

firebase emulators:start --inspect-functions

in my local browser when I open

http://127.0.0.1:5000

I'm developing under windows inside an Ubuntu WSL (version 2).

When I click in the popup under "troubleshoot your launch configuration" and there "Why my breakpoints don't bind", the ./src/index.js tells me

✅ This breakpoint was initially set in:

/home/christoph/dev/translator-poc/src/index.js line 17 column 1

❓ We couldn't find a corresponding source location, but found some
other files with the same name:

/husr/lomecal/chrlistb/noph/dev_modules/tfirebanslae-tor-pocls/node_modules/exprcess/index.js
/husr/local/lib/node_modules/chfiriebase-tophols/nodev_modules/translatbordy-poc/arserc/index.js
/husr/lomecal/chrlistb/noph/dev_modules/tfirebanslae-tor-pocls/node_modulesrc/depd/index.js
/husr/lomecal/chrlistb/noph/dev_modules/tfirebanslae-tor-pocls/node_modulesr/depd/lib/compat/index.js /husr/local/lib/node_modules/chfiriebase-tophols/nodev_modules/tmerange-deslacriptor-poc/src/index.js
...

I'm using webpack. It compiles /src to the /public directory.

This is my webpack.config.js

const path = require('path');

module.exports = {
  // The entry point file described above
  entry: './src/index.js',
  // The location of the build folder described above
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'bundle.js'
  },
  // Optional and for development only. This provides the ability to
  // map the built code back to the original source format when debugging.
  devtool: 'eval-source-map',
};

and my firebase.json:

{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "emulators": {
    "singleProjectMode": true,
    "hosting": {
      "port": 5000
    },
    "ui": {
      "enabled": false
    },
    "firestore": {
      "port": 8080
    },
    "functions": {
      "port": 5001
    }
  },
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ],
      "predeploy": [
        "npm --prefix \"$RESOURCE_DIR\" run lint"
      ]
    }
  ]
}

VSCode Version: 1.74.0

Firebase Version: 11.17.0

Node.JS Version: v16.4.0

Java Version: openjdk version "19.0.1" 2022-10-18 / OpenJDK Runtime Environment (build 19.0.1+10-Ubuntu-1ubuntu122.04)


问:
Discord.py How to embed multiple buttons in one package
How can I rewrite this code embedding all buttons in one function? The current implementation violates DRY, and I'd like to reduce the repetition.

```<code>
@discord.ui.button(label="Sistemas", style=discord.ButtonStyle.red, emoji="")
async def button1 (self, Interaction:discord.Interaction,Button:discord.ui.button, rol="Sistemas"):
    await self.give_role(Interaction, rol)

@discord.ui.button(label="Quimica", style=discord.ButtonStyle.green, emoji="")
async def button2 (self, Interaction:discord.Interaction,Button:discord.ui.button, rol="Quimica"):
    await self.give_role(Interaction, rol)

@discord.ui.button(label="Electrica", style=discord.ButtonStyle.blurple, emoji="⚡")
async def button3 (self, Interaction:discord.Interaction,Button:discord.ui.button, rol="Electrica"):
    await self.give_role(Interaction, rol)

@discord.ui.button(label="Mecanica", style=discord.ButtonStyle.gray, emoji="⚙")
async def button4 (self, Interaction:discord.Interaction,Button:discord.ui.button, rol="Mecanica"):
    await self.give_role(Interaction, rol)
</code>```

I expected to get something like one function and replacing the values in parameters for every button, having less code lines.

Body:
How can I rewrite this code embedding all buttons in one function? The current implementation violates DRY, and I'd like to reduce the repetition.

@discord.ui.button(label="Sistemas", style=discord.ButtonStyle.red, emoji="")
async def button1 (self, Interaction:discord.Interaction,Button:discord.ui.button, rol="Sistemas"):
    await self.give_role(Interaction, rol)

@discord.ui.button(label="Quimica", style=discord.ButtonStyle.green, emoji="")
async def button2 (self, Interaction:discord.Interaction,Button:discord.ui.button, rol="Quimica"):
    await self.give_role(Interaction, rol)

@discord.ui.button(label="Electrica", style=discord.ButtonStyle.blurple, emoji="⚡")
async def button3 (self, Interaction:discord.Interaction,Button:discord.ui.button, rol="Electrica"):
    await self.give_role(Interaction, rol)

@discord.ui.button(label="Mecanica", style=discord.ButtonStyle.gray, emoji="⚙")
async def button4 (self, Interaction:discord.Interaction,Button:discord.ui.button, rol="Mecanica"):
    await self.give_role(Interaction, rol)

I expected to get something like one function and replacing the values in parameters for every button, having less code lines.


问:
How can I get result as struct? (gorm)
My Category Entity is

```<code>type Category struct {
    CategorySeq       uint   `json:"categorySeq" gorm:"primaryKey; column:category_seq"`
    CategoryName      string `json:"categoryName" gorm:"column:category_name"`
    CategoryParentSeq uint   `json:"-" gorm:"column:category_parent_seq"`
    CategoryLevel     int    `json:"-" gorm:"column:category_level"`
}
</code>```

The result struct as I want get data as

```<code>type ProductCategory struct {
    Category1 Category `json:"category1" gorm:"embedded"`
    Category2 Category `json:"category2" gorm:"embedded"`
    Category3 Category `json:"category3" gorm:"embedded"`
}
</code>```

And my database data is

```<code>table : category
category_seq | category_nanme | category_parent_seq
1                first                  0
2                second                 1
3                third                  2

table : product
product_seq | category_seq
1                1
</code>```

The result I want unmarshal Json as

```<code>"category": {
  "category1": {
  "categorySeq": 0,
  "categoryName": ""
 },
  "category2": {
  "categorySeq": 0,
  "categoryName": ""
 },
  "category3": {
  "categorySeq": 0,
  "categoryName": ""
 }
},
</code>```

But I don't know how to get category result considering with parent_seq
so I try to use sql query like this

First I tried to select result as this struct

```<code>type CategoryRes struct {
    CategorySeq1  uint   `json:"categorySeq1,omitempty" gorm:"-"`
    CategoryName1 string `json:"categoryName1,omitempty" gorm:"-"`
    CategorySeq2  uint   `json:"categorySeq2,omitempty" gorm:"-"`
    CategoryName2 string `json:"categoryName2,omitempty" gorm:"-"`
    CategorySeq3  uint   `json:"categorySeq3,omitempty" gorm:"-"`
    CategoryName3 string `json:"categoryName3,omitempty" gorm:"-"`
}
</code>```

and use this orm query to get result as CategoryRes struct

```<code>func GetProductCategory(productSeq uint) *products.CategoryRes {

    categoryRes := new(products.CategoryRes)

    err := orm.GetData().
        Model(&products.Category{}).
        Select(
            `category.category_seq AS CategorySeq3, category.category_name AS CategoryName3,
            c2.category_seq AS CategorySeq2, c2.category_name AS CategoryName2,
            c3.category_seq AS CategorySeq1, c3.category_name AS CategoryName1`,
        ).
        Joins("LEFT JOIN product p ON p.product_category = category.category_seq").
        Joins("LEFT JOIN category c2 ON category.category_parent_seq = c2.category_seq").
        Joins("LEFT JOIN category c3 ON c2.category_parent_seq = c3.category_seq").
        Where("p.product_seq = ?", productSeq).
        Find(&categoryRes).Error

    print(categoryRes)

    if err != nil {
        print("error category")
    }
    return categoryRes
}
</code>```

but it is not mapping any fields...
I don't know why
If you give me hint It will very helpful to me.

Title: How can I get result as struct? (gorm)

Body:
My Category Entity is

type Category struct {
    CategorySeq       uint   `json:"categorySeq" gorm:"primaryKey; column:category_seq"`
    CategoryName      string `json:"categoryName" gorm:"column:category_name"`
    CategoryParentSeq uint   `json:"-" gorm:"column:category_parent_seq"`
    CategoryLevel     int    `json:"-" gorm:"column:category_level"`
}

The result struct as I want get data as

type ProductCategory struct {
    Category1 Category `json:"category1" gorm:"embedded"`
    Category2 Category `json:"category2" gorm:"embedded"`
    Category3 Category `json:"category3" gorm:"embedded"`
}

And my database data is

table : category
category_seq | category_nanme | category_parent_seq
1                first                  0
2                second                 1
3                third                  2

table : product
product_seq | category_seq
1                1

The result I want unmarshal Json as

"category": {
  "category1": {
  "categorySeq": 0,
  "categoryName": ""
 },
  "category2": {
  "categorySeq": 0,
  "categoryName": ""
 },
  "category3": {
  "categorySeq": 0,
  "categoryName": ""
 }
},

But I don't know how to get category result considering with parent_seq
so I try to use sql query like this

First I tried to select result as this struct

type CategoryRes struct {
    CategorySeq1  uint   `json:"categorySeq1,omitempty" gorm:"-"`
    CategoryName1 string `json:"categoryName1,omitempty" gorm:"-"`
    CategorySeq2  uint   `json:"categorySeq2,omitempty" gorm:"-"`
    CategoryName2 string `json:"categoryName2,omitempty" gorm:"-"`
    CategorySeq3  uint   `json:"categorySeq3,omitempty" gorm:"-"`
    CategoryName3 string `json:"categoryName3,omitempty" gorm:"-"`
}

and use this orm query to get result as CategoryRes struct

func GetProductCategory(productSeq uint) *products.CategoryRes {

    categoryRes := new(products.CategoryRes)

    err := orm.GetData().
        Model(&products.Category{}).
        Select(
            `category.category_seq AS CategorySeq3, category.category_name AS CategoryName3,
            c2.category_seq AS CategorySeq2, c2.category_name AS CategoryName2,
            c3.category_seq AS CategorySeq1, c3.category_name AS CategoryName1`,
        ).
        Joins("LEFT JOIN product p ON p.product_category = category.category_seq").
        Joins("LEFT JOIN category c2 ON category.category_parent_seq = c2.category_seq").
        Joins("LEFT JOIN category c3 ON c2.category_parent_seq = c3.category_seq").
        Where("p.product_seq = ?", productSeq).
        Find(&categoryRes).Error

    print(categoryRes)

    if err != nil {
        print("error category")
    }
    return categoryRes
}

but it is not mapping any fields...
I don't know why
If you give me hint It will very helpful to me.


问:
Set up Selenium with a docker rails app on wsl2
After following a couple of tutorials I can't figure out how to configure Selenium with:

a rails app on debian wsl2

the gem "Webdrivers"

docker
With my local application, Selenium worked properly with

```<code>require "webdrivers"
</code>```

Since I have dockerized the app, everything works properly except Selenium.

When I run a js test I get

```<code>Webdrivers::NetworkError:
Net::HTTPServerException: 404 "Not Found" with https://github.com/mozilla/geckodriver/releases/download/v0/geckodriver-v0-linux64.tar.gz
</code>```

It seems that the request url is not build correctly "v0"

When I hard code a version number in my config file like so

```<code>Webdrivers::Geckodriver.required_version = "0.32.0"
</code>```

geckodriver is downloaded properly.

1- How can I configure webdriver to handle verssion automatically ?

Then I get this error message

```<code> Selenium::WebDriver::Error::SessionNotCreatedError:
Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line
</code>```

What I understand is that it tries to reach for the firefox application. I have firefox installed on windows side and firefox-esr on wsl2/debian side.

2- How can I configure webdrivers and/or docker to run my tests with selenium ?

I have tried to hard code the firefox path.

Here is my webdrivers config, with many settings attempts.

```<code>Capybara.register_driver :remote_firefox do |app|
  firefox_capabilities = ::Selenium::WebDriver::Remote::Capabilities.firefox
  #   (
  #     "moz:firefoxOptions": {
  #         "args": %w[headless window-size=1400,1400]
  #         },
  #         "binary": "/mnt/c/Users/Fz/AppData/Local/Microsoft/WindowsApps/firefox.exe"
  #   )

  firefox_options = Selenium::WebDriver::Firefox::Options.new
  firefox_options.binary = "/mnt/c/Users/Fz/AppData/Local/Microsoft/WindowsApps/firefox.exe"

  Capybara::Selenium::Driver.new(
      app,
      browser: :remote,
      url: "http://172.28.0.7:5555",
      #   desired_capabilities: firefox_capabilities,
      options: firefox_options
    )
end

RSpec.configure do |config|
  config.before(:each) do
    Capybara.current_driver = :remote_firefox
    Capybara.javascript_driver = :remote_firefox
    Capybara.app_host = "http://#{IPSocket.getaddress(Socket.gethostname)}:3000"
    Capybara.server_host = IPSocket.getaddress(Socket.gethostname)
    Capybara.server_port = 5555
  end
end

###############################################
# Selenium::WebDriver::Firefox.path = "/mnt/c/Users/Fz/AppData/Local/Microsoft/WindowsApps/firefox.exe"
# Selenium::WebDriver::Firefox.path = "/usr/bin/firefox"

# Selenium::WebDriver::Firefox.path = "//wsl.localhost/Debian/usr/bin/firefox"

# options = Selenium::WebDriver::Firefox::Options.new
# options.binary = "/usr/bin/firefox"
#
# driver = Selenium::WebDriver.for :remote,
#   url: "http://localhost:4444",
#   desired_capabilities: :firefox,
#   options: ""
#########################################
</code>```

with 'desired_capabilities' I get

```<code>ArgumentError:
unknown keyword: :desired_capabilities
</code>```

without I get

```<code>Selenium::WebDriver::Error::WebDriverError
  unexpected response, code=404, content-type=""
  {
   "value": {
   "error": "unknown command",
   "message": "Unable to find handler for (POST) \u002fsession",
   "stacktrace": ""
   }
  }
</code>```

here is my docker-compose file

```<code>version: '3'
networks:
  development:
  test:
volumes:
  db_data:
  es_data:
  gem_cache:
  shared_data:
  selenium_data:
services:
(...)
capoeiragem_dev:
    build:
      context: .
      dockerfile: ./config/containers/Dockerfile.dev
    container_name: capoeiragem_dev
    volumes:
      - .:/var/app
      - shared_data:/usr/share
      - gem_cache:/usr/local/bundle/gems
    networks:
      - development
    ports:
      - 3000:3000
    stdin_open: true
    tty: true
    env_file: .env.development
    entrypoint: entrypoint-dev.sh
    command: [ 'bundle', 'exec', 'rails', 'server', '-p', '3000', '-b', '0.0.0.0' ]
    environment:
      RAILS_ENV: development
    depends_on:
      - capoeiragem_db
      - capoeiragem_es
(...)
guard:
    tty: true
    stdin_open: true
    build:
      context: .
      dockerfile: ./config/containers/Dockerfile.dev
    volumes:
      - .:/var/app
      - gem_cache:/usr/local/bundle/gems
    networks:
      - development
    environment:
      RAILS_ENV: development
    command: [ 'bundle', 'exec', 'guard', '--no-bundler-warning' ]
    ports:
      - 35729:35729
    depends_on:
      - capoeiragem_dev
      - capoeiragem_selenium
(...)
capoeiragem_firefox:
    image: selenium/node-firefox:dev
    networks:
      - development
    shm_size: 2gb
    depends_on:
      - capoeiragem_selenium
    environment:
      - SE_EVENT_BUS_HOST=capoeiragem_selenium
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
  capoeiragem_chrome:
    image: selenium/node-chrome:dev
    networks:
      - development
    shm_size: 2gb
    depends_on:
      - capoeiragem_selenium
    environment:
      - SE_EVENT_BUS_HOST=capoeiragem_selenium
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
  capoeiragem_selenium:
    image: selenium/hub:latest
    volumes:
      - selenium_data:/usr/share/selenium/data
    networks:
      - development
    container_name: capoeiragem_selenium
    ports:
      - "4442:4442"
      - "4443:4443"
      - "4444:4444"
</code>```

I can see the firefox node at http://localhost:4444/ui

Body:
After following a couple of tutorials I can't figure out how to configure Selenium with:

a rails app on debian wsl2

the gem "Webdrivers"

docker
With my local application, Selenium worked properly with

require "webdrivers"

Since I have dockerized the app, everything works properly except Selenium.

When I run a js test I get

Webdrivers::NetworkError:
Net::HTTPServerException: 404 "Not Found" with https://github.com/mozilla/geckodriver/releases/download/v0/geckodriver-v0-linux64.tar.gz

It seems that the request url is not build correctly "v0"

When I hard code a version number in my config file like so

Webdrivers::Geckodriver.required_version = "0.32.0"

geckodriver is downloaded properly.

1- How can I configure webdriver to handle verssion automatically ?

Then I get this error message

 Selenium::WebDriver::Error::SessionNotCreatedError:
Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line

What I understand is that it tries to reach for the firefox application. I have firefox installed on windows side and firefox-esr on wsl2/debian side.

2- How can I configure webdrivers and/or docker to run my tests with selenium ?

I have tried to hard code the firefox path.

Here is my webdrivers config, with many settings attempts.

Capybara.register_driver :remote_firefox do |app|
  firefox_capabilities = ::Selenium::WebDriver::Remote::Capabilities.firefox
  #   (
  #     "moz:firefoxOptions": {
  #         "args": %w[headless window-size=1400,1400]
  #         },
  #         "binary": "/mnt/c/Users/Fz/AppData/Local/Microsoft/WindowsApps/firefox.exe"
  #   )

  firefox_options = Selenium::WebDriver::Firefox::Options.new
  firefox_options.binary = "/mnt/c/Users/Fz/AppData/Local/Microsoft/WindowsApps/firefox.exe"

  Capybara::Selenium::Driver.new(
      app,
      browser: :remote,
      url: "http://172.28.0.7:5555",
      #   desired_capabilities: firefox_capabilities,
      options: firefox_options
    )
end

RSpec.configure do |config|
  config.before(:each) do
    Capybara.current_driver = :remote_firefox
    Capybara.javascript_driver = :remote_firefox
    Capybara.app_host = "http://#{IPSocket.getaddress(Socket.gethostname)}:3000"
    Capybara.server_host = IPSocket.getaddress(Socket.gethostname)
    Capybara.server_port = 5555
  end
end

###############################################
# Selenium::WebDriver::Firefox.path = "/mnt/c/Users/Fz/AppData/Local/Microsoft/WindowsApps/firefox.exe"
# Selenium::WebDriver::Firefox.path = "/usr/bin/firefox"

# Selenium::WebDriver::Firefox.path = "//wsl.localhost/Debian/usr/bin/firefox"

# options = Selenium::WebDriver::Firefox::Options.new
# options.binary = "/usr/bin/firefox"
#
# driver = Selenium::WebDriver.for :remote,
#   url: "http://localhost:4444",
#   desired_capabilities: :firefox,
#   options: ""
#########################################

with 'desired_capabilities' I get

ArgumentError:
unknown keyword: :desired_capabilities

without I get

Selenium::WebDriver::Error::WebDriverError
  unexpected response, code=404, content-type=""
  {
   "value": {
   "error": "unknown command",
   "message": "Unable to find handler for (POST) \u002fsession",
   "stacktrace": ""
   }
  }

here is my docker-compose file

version: '3'
networks:
  development:
  test:
volumes:
  db_data:
  es_data:
  gem_cache:
  shared_data:
  selenium_data:
services:
(...)
capoeiragem_dev:
    build:
      context: .
      dockerfile: ./config/containers/Dockerfile.dev
    container_name: capoeiragem_dev
    volumes:
      - .:/var/app
      - shared_data:/usr/share
      - gem_cache:/usr/local/bundle/gems
    networks:
      - development
    ports:
      - 3000:3000
    stdin_open: true
    tty: true
    env_file: .env.development
    entrypoint: entrypoint-dev.sh
    command: [ 'bundle', 'exec', 'rails', 'server', '-p', '3000', '-b', '0.0.0.0' ]
    environment:
      RAILS_ENV: development
    depends_on:
      - capoeiragem_db
      - capoeiragem_es
(...)
guard:
    tty: true
    stdin_open: true
    build:
      context: .
      dockerfile: ./config/containers/Dockerfile.dev
    volumes:
      - .:/var/app
      - gem_cache:/usr/local/bundle/gems
    networks:
      - development
    environment:
      RAILS_ENV: development
    command: [ 'bundle', 'exec', 'guard', '--no-bundler-warning' ]
    ports:
      - 35729:35729
    depends_on:
      - capoeiragem_dev
      - capoeiragem_selenium
(...)
capoeiragem_firefox:
    image: selenium/node-firefox:dev
    networks:
      - development
    shm_size: 2gb
    depends_on:
      - capoeiragem_selenium
    environment:
      - SE_EVENT_BUS_HOST=capoeiragem_selenium
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
  capoeiragem_chrome:
    image: selenium/node-chrome:dev
    networks:
      - development
    shm_size: 2gb
    depends_on:
      - capoeiragem_selenium
    environment:
      - SE_EVENT_BUS_HOST=capoeiragem_selenium
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
  capoeiragem_selenium:
    image: selenium/hub:latest
    volumes:
      - selenium_data:/usr/share/selenium/data
    networks:
      - development
    container_name: capoeiragem_selenium
    ports:
      - "4442:4442"
      - "4443:4443"
      - "4444:4444"

I can see the firefox node at http://localhost:4444/ui


问:
Visual Studio 2022 Analysis Services Project doesn't show mining models
I've installed VS 2022 and Microsoft Analysis Services Projects 2022 extension from here https://marketplace.visualstudio.com/items?itemName=ProBITools.MicrosoftAnalysisServicesModelingProjects2022, but when I open my dwproj file which was created in VS 2019 I can't see "Mining Structures" folder and mining models too. The project structure which I see is:

```
Data Sources
---MyDataSource.ds
Data Source Views
---MyDataSourceView.dsv
Cubes
Dimensions
Roles
Assemblies
Miscellaneous
```

but inside my project file there is mining models section:

```<code><MiningModels>
    <ProjectItem>
      <Name>Model1.dmm</Name>
      <FullPath>Model1.dmm</FullPath>
    </ProjectItem>
    <ProjectItem>
      <Name>Model2.dmm</Name>
      <FullPath>Model2.dmm</FullPath>
    </ProjectItem>
</MiningModels>
</code>```

Does VS2022 support mining models? If yes, what do I need to install or configure?

Body:
I've installed VS 2022 and Microsoft Analysis Services Projects 2022 extension from here https://marketplace.visualstudio.com/items?itemName=ProBITools.MicrosoftAnalysisServicesModelingProjects2022, but when I open my dwproj file which was created in VS 2019 I can't see "Mining Structures" folder and mining models too. The project structure which I see is:

Data Sources
---MyDataSource.ds
Data Source Views
---MyDataSourceView.dsv
Cubes
Dimensions
Roles
Assemblies
Miscellaneous

but inside my project file there is mining models section:

<MiningModels>
    <ProjectItem>
      <Name>Model1.dmm</Name>
      <FullPath>Model1.dmm</FullPath>
    </ProjectItem>
    <ProjectItem>
      <Name>Model2.dmm</Name>
      <FullPath>Model2.dmm</FullPath>
    </ProjectItem>
</MiningModels>

Does VS2022 support mining models? If yes, what do I need to install or configure?


问:
Error 'A column name 'N' already belongs to this data table' when uploading flat file
I am trying to upload a flat file (CSV) by using the 'Import Flat File' option in SSMS v17.9.1. But after I select the file that is to be uploaded and click next, an error appears that says:

A column name 'N' already belongs to this data table.

There are no duplicate columns present in the table.

Can someone please tell me why this error is occurring or how to go around this issue?


问:
Taking a file name as input from user and read the data that contains
I am trying to write a MIPS assembly code to read a file name from user and open this file to read data , but after the user enters the file name , the MARS simulator won't open it and always give the descriptor is less than zero and that's mean error in opening the file.
the code

```<code>.data
fileName : .space 1024
msg : .asciiz "Enter the file name "
errorMsg: .asciiz "Error opening the file \n"
fileWords : .space 1024
newLine : .asciiz "\n"
.text
.globl main
    main :
      li $v0,4
      la $a0,msg
      syscall

      li $v0,4
      la $a0,newLine
      syscall

      li $v0,8
      la $a0,fileName
      li $a1,1000
      syscall

      li $v0,13
      la $a0,fileName
      li $a1,0 # read
      syscall

      move $t0,$v0 # t0 contains the file descriptor

      blt $t0,0,errorFile # to check if error ocured while opening the file

      li $v0,14
      move $a0,$t0
      la $a1,fileWords
      li $a2,1000
      syscall

      # now fileWords should contain the data from the file ..
      li $v0,4
      la $a0,fileWords
      syscall

      la $a0,newLine
      syscall
      j Exit

  errorFile:
      li $v0,4
      la $a0,errorMsg
      syscall
      j Exit
  Exit :
      li $v0,10
      syscall
</code>```

the above code is taking the file name as input from user but the output is always the error message.

However , if the file path is given directly as a variable in data segment , the program works properly

```<code>.data
fileName : .asciiz "C:\\Users\\msi\\Downloads\\New folder (2)\\file.txt"
msg : .asciiz "Enter the file name "
errorMsg: .asciiz "Error opening the file \n"
fileWords : .space 1024
newLine : .asciiz "\n"
.text
.globl main
 main :
    li $v0,13
    la $a0,fileName # the whole path of the file is defined in data segment above.
    li $a1,0 # read
    syscall

    move $t0,$v0 # t0 contains the file descriptor

    blt $t0,0,errorFile # to check if error ocured while opening the file

    li $v0,14
    move $a0,$t0
    la $a1,fileWords
    li $a2,1000
    syscall

    # now fileWords should contain the data from the file ..
    li $v0,4
    la $a0,fileWords
    syscall

    la $a0,newLine
    syscall
    j Exit

errorFile:
    li $v0,4
    la $a0,errorMsg
    syscall
    j Exit
Exit :
    li $v0,10
    syscall
</code>```

I think the error is in null-terminated string but what I have to do.

Body:
I am trying to write a MIPS assembly code to read a file name from user and open this file to read data , but after the user enters the file name , the MARS simulator won't open it and always give the descriptor is less than zero and that's mean error in opening the file.
the code

.data
fileName : .space 1024
msg : .asciiz "Enter the file name "
errorMsg: .asciiz "Error opening the file \n"
fileWords : .space 1024
newLine : .asciiz "\n"
.text
.globl main
    main :
      li $v0,4
      la $a0,msg
      syscall

      li $v0,4
      la $a0,newLine
      syscall

      li $v0,8
      la $a0,fileName
      li $a1,1000
      syscall

      li $v0,13
      la $a0,fileName
      li $a1,0 # read
      syscall

      move $t0,$v0 # t0 contains the file descriptor

      blt $t0,0,errorFile # to check if error ocured while opening the file

      li $v0,14
      move $a0,$t0
      la $a1,fileWords
      li $a2,1000
      syscall

      # now fileWords should contain the data from the file ..
      li $v0,4
      la $a0,fileWords
      syscall

      la $a0,newLine
      syscall
      j Exit

  errorFile:
      li $v0,4
      la $a0,errorMsg
      syscall
      j Exit
  Exit :
      li $v0,10
      syscall

the above code is taking the file name as input from user but the output is always the error message.

However , if the file path is given directly as a variable in data segment , the program works properly

.data
fileName : .asciiz "C:\\Users\\msi\\Downloads\\New folder (2)\\file.txt"
msg : .asciiz "Enter the file name "
errorMsg: .asciiz "Error opening the file \n"
fileWords : .space 1024
newLine : .asciiz "\n"
.text
.globl main
 main :
    li $v0,13
    la $a0,fileName # the whole path of the file is defined in data segment above.
    li $a1,0 # read
    syscall

    move $t0,$v0 # t0 contains the file descriptor

    blt $t0,0,errorFile # to check if error ocured while opening the file

    li $v0,14
    move $a0,$t0
    la $a1,fileWords
    li $a2,1000
    syscall

    # now fileWords should contain the data from the file ..
    li $v0,4
    la $a0,fileWords
    syscall

    la $a0,newLine
    syscall
    j Exit

errorFile:
    li $v0,4
    la $a0,errorMsg
    syscall
    j Exit
Exit :
    li $v0,10
    syscall

I think the error is in null-terminated string but what I have to do.


问:
Remove value from JSON if the end date matches with today's date
I have these two tables named Product_details and Pricing table.

Product_details table:

Pricing table:

I want to update the product_Details table if the start date and end date match with today's date and current time.
So, if the start_Date matches with the current date and time, it will update the product_Details table to offer price or promotional price depending on the id that's the inner query returning.
If the end_Date matches with the current date and time, it will delete the offer price or promotional price depending on the id that's the inner query returning.
The code I wrote is as follows.

-- This code works appropriately, which updates the product_details table and inserts offer/promotional prices if the start_Date matches with today's date and current time.

```<code>> UPDATE product_Details
            SET price_and_price_Type =
> price_and_price_Type ||
>               ( pps.details::jsonb )          FROM (
>               select id, price_Details as details
>               from pricing
>               where to_char(start_date,'YYYY-MM-DD HH24:MI') = to_char(now(),'YYYY-MM-DD HH24:MI')
>               group by id, details
>               ) as pps            where product_Details.id = "pps".id ;
</code>```

-- this is the code that doesn't work. I wrote to delete the jsonB value, which is the offer or promotional price previously updated depending on the id.

```<code>UPDATE product_Details
            SET price_and_price_Type = price_and_price_Type -
                ( pps.details::jsonb )
            FROM (
                select id, price_Details as details
                from pricing
                where to_char(end_date,'YYYY-MM-DD HH24:MI') = to_char(now(),'YYYY-MM-DD HH24:MI')
                group by id, details
                ) as pps
            where product_Details.id = "pps".id ;
</code>```

The error raises:

```<code>ERROR:  operator does not exist: jsonb - jsonb
LINE 2:    SET price_and_price_Type = price_and_price_Type -
                                                           ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.
</code>```

Body:
I have these two tables named Product_details and Pricing table.

Product_details table:

Pricing table:

I want to update the product_Details table if the start date and end date match with today's date and current time.
So, if the start_Date matches with the current date and time, it will update the product_Details table to offer price or promotional price depending on the id that's the inner query returning.
If the end_Date matches with the current date and time, it will delete the offer price or promotional price depending on the id that's the inner query returning.
The code I wrote is as follows.

-- This code works appropriately, which updates the product_details table and inserts offer/promotional prices if the start_Date matches with today's date and current time.

> UPDATE product_Details
            SET price_and_price_Type =
> price_and_price_Type ||
>               ( pps.details::jsonb )          FROM (
>               select id, price_Details as details
>               from pricing
>               where to_char(start_date,'YYYY-MM-DD HH24:MI') = to_char(now(),'YYYY-MM-DD HH24:MI')
>               group by id, details
>               ) as pps            where product_Details.id = "pps".id ;

-- this is the code that doesn't work. I wrote to delete the jsonB value, which is the offer or promotional price previously updated depending on the id.

UPDATE product_Details
            SET price_and_price_Type = price_and_price_Type -
                ( pps.details::jsonb )
            FROM (
                select id, price_Details as details
                from pricing
                where to_char(end_date,'YYYY-MM-DD HH24:MI') = to_char(now(),'YYYY-MM-DD HH24:MI')
                group by id, details
                ) as pps
            where product_Details.id = "pps".id ;

The error raises:

ERROR:  operator does not exist: jsonb - jsonb
LINE 2:    SET price_and_price_Type = price_and_price_Type -
                                                           ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.


问:
Is there a way around the code below to modify the state without having an error in a functional component?
I am trying to implement simple increment and decrement functions within the following component:

(Note the bits that have been commented out)

I do not understand why I cannot place a hook inside of a handler function that then gets eventually fired by the user if the dependency array is populated by the part of the state subject to a change by the function itself.

Any help would be appreciated.

```<code>import React, { useState, useEffect } from 'react';

// helper function

function titleCase(string) {
    return string[0].toUpperCase() + string.slice(1).toLowerCase();
}

function increment(value) {
    return value + 1;
}

function decrement(value) {
    return value - 1;
}

const Card = (props) => {

    // const [cart_id, setCart_id] = useState(0);
    const [toggleQuantity, setToggleQuantity] = useState(0);

    let product_id = props.product_id;
    let quantity = props.quantity;
    let name = props.name;
    let price = props.price;
    let customer_id = props.customer_id;

    /* useEffect(() => {
         setToggleQuantity(quantity)
         console.log(quantity)
     }, [toggleQuantity]);

     function useHandleIncrement(quantity) {
         useEffect(() => {
             setToggleQuantity(quantity + 1)
             console.log(quantity)
         }, [toggleQuantity]);

     }

     function useHandleDecrement(quantity) {
         useEffect(() => {
             setToggleQuantity(quantity - 1)
             console.log(quantity)
         }, [toggleQuantity]);
     } */

    function handleRemove() {

        removeFromCart(props.cart_id)
    };
    /// Removing an item from the cart, does not work

    // console.log(cart_id);

    async function removeFromCart(cart_id) {

        const url = `http:localhost:5000/carts/${cart_id}`
        await fetch(url, {
            method: 'DELETE',
            success: function () {
                alert('Item removed successfully')
            },
            error: function () {
                alert('Error removing item')
            }

        });
    }

    async function handleCheckout() {

        console.log('checking cart_id', props.cart_id);
        await checkout(props.cart_id)
    }

    async function checkout(cart_id) {

        const object = {

            customer_id: customer_id,
            price: price,
            product_id: product_id,
            quantity: quantity
        }
        try {
            const response = await fetch(`http://localhost:5000/carts/${cart_id}/checkout`, {
                method: 'POST',
                headers: {
                    'content-type': 'application/json',
                    'accept': 'application/json'
                },
                body: JSON.stringify(object)

            })

            return response.json();

        } catch (error) {

            console.error(error.message);

        }

    };

    return (
        <>
            <p>{titleCase(name)}</p>
            <p>Quantity:</p>
            <p><button onClick={useHandleIncrement}>+</button>{quantity}<button onClick={useHandleDecrement}>-</button></p>
            <h6>Price</h6>
            <p>£ {quantity * price}</p>
            <button onClick={handleRemove}>Remove from your cart</button>
            <br />
            <p>Complete payment:</p>
            <button type="submit" name="payment" onClick={handleCheckout} >Pay Now</button>
            <br />
        </>
    );
};

export default Card;
</code>```

Body:
I am trying to implement simple increment and decrement functions within the following component:

(Note the bits that have been commented out)

I do not understand why I cannot place a hook inside of a handler function that then gets eventually fired by the user if the dependency array is populated by the part of the state subject to a change by the function itself.

Any help would be appreciated.

import React, { useState, useEffect } from 'react';

// helper function

function titleCase(string) {
    return string[0].toUpperCase() + string.slice(1).toLowerCase();
}

function increment(value) {
    return value + 1;
}

function decrement(value) {
    return value - 1;
}

const Card = (props) => {

    // const [cart_id, setCart_id] = useState(0);
    const [toggleQuantity, setToggleQuantity] = useState(0);

    let product_id = props.product_id;
    let quantity = props.quantity;
    let name = props.name;
    let price = props.price;
    let customer_id = props.customer_id;

    /* useEffect(() => {
         setToggleQuantity(quantity)
         console.log(quantity)
     }, [toggleQuantity]);

     function useHandleIncrement(quantity) {
         useEffect(() => {
             setToggleQuantity(quantity + 1)
             console.log(quantity)
         }, [toggleQuantity]);

     }

     function useHandleDecrement(quantity) {
         useEffect(() => {
             setToggleQuantity(quantity - 1)
             console.log(quantity)
         }, [toggleQuantity]);
     } */

    function handleRemove() {

        removeFromCart(props.cart_id)
    };
    /// Removing an item from the cart, does not work

    // console.log(cart_id);

    async function removeFromCart(cart_id) {

        const url = `http:localhost:5000/carts/${cart_id}`
        await fetch(url, {
            method: 'DELETE',
            success: function () {
                alert('Item removed successfully')
            },
            error: function () {
                alert('Error removing item')
            }

        });
    }

    async function handleCheckout() {

        console.log('checking cart_id', props.cart_id);
        await checkout(props.cart_id)
    }

    async function checkout(cart_id) {

        const object = {

            customer_id: customer_id,
            price: price,
            product_id: product_id,
            quantity: quantity
        }
        try {
            const response = await fetch(`http://localhost:5000/carts/${cart_id}/checkout`, {
                method: 'POST',
                headers: {
                    'content-type': 'application/json',
                    'accept': 'application/json'
                },
                body: JSON.stringify(object)

            })

            return response.json();

        } catch (error) {

            console.error(error.message);

        }

    };

    return (
        <>

{titleCase(name)}

Quantity:

<button onClick={useHandleIncrement}>+</button>{quantity}<button onClick={useHandleDecrement}>-</button>

Price

£ {quantity * price}

            <button onClick={handleRemove}>Remove from your cart</button>

Complete payment:

            <button type="submit" name="payment" onClick={handleCheckout} >Pay Now</button>

        </>
    );
};

export default Card;


问:
How to prevent going back without refreshing the current page onpopstate event with a confirmation alert?
Does anyone know how to show a confirmation alert to user on go back or go forward buttons of browser clicked?

I tried to use popstate event but it does not show an alert to user. Then I added an confitmation alert on popstate event but even if the user cancel the alert it goes back. I found I can use history.forward() inside on cancel event but what it does is just refreshing the page but I do not want to refresh the page because I don’t want to lose any information. Please help.


问:
Setting a thread security descriptor to "block" OpenThread
First argument of OpenThread is dwDesiredAccess. I've read here that this argument is checked against the security descriptor of the thread. I tried setting it with SetSecurityInfo, but when i use OpenThread, it doesn't seem to work as expected for me.

```<code>#include <AccCtrl.h>
#include <AclAPI.h>

// Create a security descriptor
   SECURITY_DESCRIPTOR sd;
   InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);

   // Create a DACL
   ACL_SIZE_INFORMATION aclSizeInfo;
   aclSizeInfo.AclBytesInUse = sizeof(ACL);
   aclSizeInfo.AclBytesFree = 0;
   aclSizeInfo.AceCount = 0;
   aclSizeInfo.AclBytesFree = 0;

   // Create an ACL
   PACL pAcl = (PACL)LocalAlloc(LPTR, aclSizeInfo.AclBytesInUse);
   InitializeAcl(pAcl, aclSizeInfo.AclBytesInUse, ACL_REVISION);

   // Add an ACE to the DACL
   EXPLICIT_ACCESS ea;
   ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
   ea.grfAccessPermissions = THREAD_ALL_ACCESS;
   ea.grfAccessMode = DENY_ACCESS;
   ea.grfInheritance = NO_INHERITANCE;
   ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
   ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
   ea.Trustee.ptstrName = (LPTSTR)WinLocalSid;

   // Add the ACE to the ACL
   SetEntriesInAcl(1, &ea, NULL, &pAcl);

   // Set the DACL in the security descriptor
   SetSecurityDescriptorDacl(&sd, TRUE, pAcl, FALSE);

   // Set the security descriptor for the thread handle
   std::cout << SetSecurityInfo(GetCurrentThread(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pAcl, NULL) << std::endl;

   // Free the memory
   LocalFree(pAcl);

    auto handle = OpenThread(THREAD_ALL_ACCESS, 0, GetCurrentThreadId());
    std::cout << handle << std::endl; // always a valid handle
</code>```

Body:
First argument of OpenThread is dwDesiredAccess. I've read here that this argument is checked against the security descriptor of the thread. I tried setting it with SetSecurityInfo, but when i use OpenThread, it doesn't seem to work as expected for me.

#include <AccCtrl.h>
#include <AclAPI.h>

// Create a security descriptor
   SECURITY_DESCRIPTOR sd;
   InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);

   // Create a DACL
   ACL_SIZE_INFORMATION aclSizeInfo;
   aclSizeInfo.AclBytesInUse = sizeof(ACL);
   aclSizeInfo.AclBytesFree = 0;
   aclSizeInfo.AceCount = 0;
   aclSizeInfo.AclBytesFree = 0;

   // Create an ACL
   PACL pAcl = (PACL)LocalAlloc(LPTR, aclSizeInfo.AclBytesInUse);
   InitializeAcl(pAcl, aclSizeInfo.AclBytesInUse, ACL_REVISION);

   // Add an ACE to the DACL
   EXPLICIT_ACCESS ea;
   ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
   ea.grfAccessPermissions = THREAD_ALL_ACCESS;
   ea.grfAccessMode = DENY_ACCESS;
   ea.grfInheritance = NO_INHERITANCE;
   ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
   ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
   ea.Trustee.ptstrName = (LPTSTR)WinLocalSid;

   // Add the ACE to the ACL
   SetEntriesInAcl(1, &ea, NULL, &pAcl);

   // Set the DACL in the security descriptor
   SetSecurityDescriptorDacl(&sd, TRUE, pAcl, FALSE);

   // Set the security descriptor for the thread handle
   std::cout << SetSecurityInfo(GetCurrentThread(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pAcl, NULL) << std::endl;

   // Free the memory
   LocalFree(pAcl);

    auto handle = OpenThread(THREAD_ALL_ACCESS, 0, GetCurrentThreadId());
    std::cout << handle << std::endl; // always a valid handle


问:
Input validation error not showing to user
I have this in my action to validate an ajax post

```<code>if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
    Yii::$app->response->format = Response::FORMAT_JSON;
     return ActiveForm::validate($model);
}
</code>```

in my view

```<code><?php
    $form = ActiveForm::begin([
        'id' => $model->formName().'-form',
        'action' => Url::to(['/payment/stripe/payment-session']),
        'scrollToError' => false,
        'validateOnSubmit' => true,
        'enableAjaxValidation' => true
    ]);

    echo $form->field($model, 'number')->textInput([ 'class' => 'form-control form-control-lg text-uppercase', 'placeholder'=>'Enter Number', 'id' => 'reports-number'])->label(false);
    ....
    ....
    ActiveForm::end();

?>
</code>```

in my model

```<code>public function rules() {

...
[['number'], ENumberValidator::class, 'on' => ['check-number']],
...
}
</code>```

when i enter 456!! in the input, i get this ajax returned. which is correct.

```<code>{
    "reports-number": [
        "Number is an invalid format."
    ]
}
</code>```

but for some reason no error message shows under the input, the input has a check mark in green and form can still be submitted. Any idea what I'm missing here? Thanks

Body:
I have this in my action to validate an ajax post

if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
    Yii::$app->response->format = Response::FORMAT_JSON;
     return ActiveForm::validate($model);
}

in my view

<?php
    $form = ActiveForm::begin([
        'id' => $model->formName().'-form',
        'action' => Url::to(['/payment/stripe/payment-session']),
        'scrollToError' => false,
        'validateOnSubmit' => true,
        'enableAjaxValidation' => true
    ]);

    echo $form->field($model, 'number')->textInput([ 'class' => 'form-control form-control-lg text-uppercase', 'placeholder'=>'Enter Number', 'id' => 'reports-number'])->label(false);
    ....
    ....
    ActiveForm::end();

?>

in my model

public function rules() {

...
[['number'], ENumberValidator::class, 'on' => ['check-number']],
...
}

when i enter 456!! in the input, i get this ajax returned. which is correct.

{
    "reports-number": [
        "Number is an invalid format."
    ]
}

but for some reason no error message shows under the input, the input has a check mark in green and form can still be submitted. Any idea what I'm missing here? Thanks


问:
What is the easiest way to access Google play app reviews
Currently, I get all reviews by Creating a service account and downloading the private key file for the service account. This process is very cumbersome.

I tried Oauth, but the auth_token generated prevents me from accessing reviews. Is this a limitation of Oauth or is this happening because I haven't added a specific scope for Oauth.