问:
Grafana Loki, AlertManager - unable to read rule dir, open /tmp/loki/rules/fake: no such file or directory
I've deployed promtail, Grafana, Loki and AlertManager using Helm charts on k3d cluster on my local machine. I would like to have some rules in Loki such that if something will happen, AlertManager should be informed. Now I tried only with some simple rule, just to check if it works.

My Loki version: {"version":"2.6.1","revision":"6bd05c9a4","branch":"HEAD","buildUser":"root@ea1e89b8da02","buildDate":"2022-07-18T08:49:07Z","goVersion":""}

My Grafana version:

And the Loki configuration:

```<code>loki:
  # should loki be deployed on cluster?
  enabled: true

  image:
    repository: grafana/loki
    pullPolicy: Always
    pullSecrets:
      - registry
  priorityClassName: normal
  resources:
    limits:
      memory: 3Gi
      cpu: 0
    requests:
      memory: 0
      cpu: 0
  config:
    chunk_store_config:
      max_look_back_period: 30d
    table_manager:
      retention_deletes_enabled: true
      retention_period: 30d
    query_range:
      split_queries_by_interval: 0
      parallelise_shardable_queries: false
    querier:
      max_concurrent: 2048
    frontend:
      max_outstanding_per_tenant: 4096
      compress_responses: true
    ingester:
      wal:
        enabled: true
        dir: /tmp/wal
    schema_config:
      configs:
        - from: 2022-12-05
          store: boltdb-shipper
          object_store: filesystem
          schema: v11
          index:
            prefix: index_
            period: 24h
    storage_config:
      boltdb_shipper:
        active_index_directory: /tmp/loki/boltdb-shipper-active
        cache_location: /tmp/loki/boltdb-shipper-cache
        cache_ttl: 24h         # Can be increased for faster performance over longer query periods, uses more disk space
        shared_store: filesystem
      filesystem:
        directory: /tmp/loki/chunks
    compactor:
      working_directory: /tmp/loki/boltdb-shipper-compactor
      shared_store: filesystem
    ruler:
      storage:
        type: local
        local:
          directory: /tmp/loki/rules/
      ring:
        kvstore:
          store: inmemory
      rule_path: /tmp/loki/rules-temp
      alertmanager_url: http://onprem-kube-prometheus-alertmanager.svc.mylocal-monitoring:9093
      enable_api: true
      enable_alertmanager_v2: true
  write:
    extraVolumeMounts:
      - name: rules-config
        mountPath: /tmp/loki/rules/fake/
    extraVolumes:
      - name: rules-config
        configMap:
          name: rules-cfgmap
          items:
            - key: "rules.yaml"
              path: "rules.yaml"
  read:
    extraVolumeMounts:
      - name: rules-config
        mountPath: /tmp/loki/rules/fake/
    extraVolumes:
      - name: rules-config
        configMap:
          name: rules-cfgmap
          items:
            - key: "rules.yaml"
              path: "rules.yaml"

promtail:
  image:
    registry: docker
    pullPolicy: Always
  imagePullSecrets:
    - name: registry
  priorityClassName: normal
  resources:
    limits:
      memory: 256Mi
      cpu: 0
    requests:
      memory: 0
      cpu: 0
  livenessProbe:
    failureThreshold: 5
    httpGet:
      path: /ready
      port: http-metrics
    initialDelaySeconds: 10
    periodSeconds: 10
    successThreshold: 1
    timeoutSeconds: 1
  config:
    snippets:
      pipelineStages:
        - cri: {}
      common:
        - action: replace
          source_labels:
            - __meta_kubernetes_pod_node_name
          target_label: node_name
        - action: replace
          source_labels:
            - __meta_kubernetes_namespace
          target_label: namespace
        - action: replace
          source_labels:
            - __meta_kubernetes_pod_container_name
          target_label: container
        - action: replace
          replacement: /var/log/pods/*$1/*.log
          separator: /
          source_labels:
            - __meta_kubernetes_pod_uid
            - __meta_kubernetes_pod_container_name
          target_label: __path__
        - action: replace
          replacement: /var/log/pods/*$1/*.log
          regex: true/(.*)
          separator: /
          source_labels:
            - __meta_kubernetes_pod_annotationpresent_kubernetes_io_config_hash
            - __meta_kubernetes_pod_annotation_kubernetes_io_config_hash
            - __meta_kubernetes_pod_container_name
          target_label: __path__

monitoring:
  enabled: false

networkPolicies:
  enabled: false
</code>```

The problem is, when I want to check the rules, doing curl -X GET localhost:3100/loki/api/v1/rules it shows me: unable to read rule dir /tmp/loki/rules/fake: open /tmp/loki/rules/fake: no such file or directory.

So it seems it can't find the rules file.

I also tried to change the config like this:

```<code>write:
    extraVolumeMounts:
      - name: rules-conf
        mountPath: /tmp/loki/rules/fake/rules.yaml
    extraVolumes:
      - name: rules-conf
  read:
    extraVolumeMounts:
      - name: rules-conf
        mountPath: /tmp/loki/rules/fake/rules.yaml
    extraVolumes:
      - name: rules-conf
</code>```

And my configmap:

```<code>---
apiVersion: v1
kind: ConfigMap
metadata:
  name: rules-cfgmap
  namespace: mylocal-monitoring
data:
  rules.yaml: |
    groups:
      - name: PrometheusAlertsGroup
    rules:
      - alert: test1
      expr: |
        1 > 0
        for: 0m
        labels:
          severity: critical
        annotations:
          summary: TEST: testing test
          description: test
</code>```

And the rules file:

```<code>groups:
  - name: PrometheusAlertsGroup
  rules:
    - alert: test1
      expr: |
        1 > 0
        for: 0m
        labels:
          severity: critical
        annotations:
          summary: TEST: testing test
          description: test
</code>```

But the problem is the same. Any ideas?

It finally worked when I created /tmp/loki/rules/fake/rules.yaml manually, but thats not the point to create it manually.

Body:
I've deployed promtail, Grafana, Loki and AlertManager using Helm charts on k3d cluster on my local machine. I would like to have some rules in Loki such that if something will happen, AlertManager should be informed. Now I tried only with some simple rule, just to check if it works.

My Loki version: {"version":"2.6.1","revision":"6bd05c9a4","branch":"HEAD","buildUser":"root@ea1e89b8da02","buildDate":"2022-07-18T08:49:07Z","goVersion":""}

My Grafana version:

And the Loki configuration:

loki:
  # should loki be deployed on cluster?
  enabled: true

  image:
    repository: grafana/loki
    pullPolicy: Always
    pullSecrets:
      - registry
  priorityClassName: normal
  resources:
    limits:
      memory: 3Gi
      cpu: 0
    requests:
      memory: 0
      cpu: 0
  config:
    chunk_store_config:
      max_look_back_period: 30d
    table_manager:
      retention_deletes_enabled: true
      retention_period: 30d
    query_range:
      split_queries_by_interval: 0
      parallelise_shardable_queries: false
    querier:
      max_concurrent: 2048
    frontend:
      max_outstanding_per_tenant: 4096
      compress_responses: true
    ingester:
      wal:
        enabled: true
        dir: /tmp/wal
    schema_config:
      configs:
        - from: 2022-12-05
          store: boltdb-shipper
          object_store: filesystem
          schema: v11
          index:
            prefix: index_
            period: 24h
    storage_config:
      boltdb_shipper:
        active_index_directory: /tmp/loki/boltdb-shipper-active
        cache_location: /tmp/loki/boltdb-shipper-cache
        cache_ttl: 24h         # Can be increased for faster performance over longer query periods, uses more disk space
        shared_store: filesystem
      filesystem:
        directory: /tmp/loki/chunks
    compactor:
      working_directory: /tmp/loki/boltdb-shipper-compactor
      shared_store: filesystem
    ruler:
      storage:
        type: local
        local:
          directory: /tmp/loki/rules/
      ring:
        kvstore:
          store: inmemory
      rule_path: /tmp/loki/rules-temp
      alertmanager_url: http://onprem-kube-prometheus-alertmanager.svc.mylocal-monitoring:9093
      enable_api: true
      enable_alertmanager_v2: true
  write:
    extraVolumeMounts:
      - name: rules-config
        mountPath: /tmp/loki/rules/fake/
    extraVolumes:
      - name: rules-config
        configMap:
          name: rules-cfgmap
          items:
            - key: "rules.yaml"
              path: "rules.yaml"
  read:
    extraVolumeMounts:
      - name: rules-config
        mountPath: /tmp/loki/rules/fake/
    extraVolumes:
      - name: rules-config
        configMap:
          name: rules-cfgmap
          items:
            - key: "rules.yaml"
              path: "rules.yaml"

promtail:
  image:
    registry: docker
    pullPolicy: Always
  imagePullSecrets:
    - name: registry
  priorityClassName: normal
  resources:
    limits:
      memory: 256Mi
      cpu: 0
    requests:
      memory: 0
      cpu: 0
  livenessProbe:
    failureThreshold: 5
    httpGet:
      path: /ready
      port: http-metrics
    initialDelaySeconds: 10
    periodSeconds: 10
    successThreshold: 1
    timeoutSeconds: 1
  config:
    snippets:
      pipelineStages:
        - cri: {}
      common:
        - action: replace
          source_labels:
            - __meta_kubernetes_pod_node_name
          target_label: node_name
        - action: replace
          source_labels:
            - __meta_kubernetes_namespace
          target_label: namespace
        - action: replace
          source_labels:
            - __meta_kubernetes_pod_container_name
          target_label: container
        - action: replace
          replacement: /var/log/pods/*$1/*.log
          separator: /
          source_labels:
            - __meta_kubernetes_pod_uid
            - __meta_kubernetes_pod_container_name
          target_label: __path__
        - action: replace
          replacement: /var/log/pods/*$1/*.log
          regex: true/(.*)
          separator: /
          source_labels:
            - __meta_kubernetes_pod_annotationpresent_kubernetes_io_config_hash
            - __meta_kubernetes_pod_annotation_kubernetes_io_config_hash
            - __meta_kubernetes_pod_container_name
          target_label: __path__

monitoring:
  enabled: false

networkPolicies:
  enabled: false

The problem is, when I want to check the rules, doing curl -X GET localhost:3100/loki/api/v1/rules it shows me: unable to read rule dir /tmp/loki/rules/fake: open /tmp/loki/rules/fake: no such file or directory.

So it seems it can't find the rules file.

I also tried to change the config like this:

write:
    extraVolumeMounts:
      - name: rules-conf
        mountPath: /tmp/loki/rules/fake/rules.yaml
    extraVolumes:
      - name: rules-conf
  read:
    extraVolumeMounts:
      - name: rules-conf
        mountPath: /tmp/loki/rules/fake/rules.yaml
    extraVolumes:
      - name: rules-conf

And my configmap:

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: rules-cfgmap
  namespace: mylocal-monitoring
data:
  rules.yaml: |
    groups:
      - name: PrometheusAlertsGroup
    rules:
      - alert: test1
      expr: |
        1 > 0
        for: 0m
        labels:
          severity: critical
        annotations:
          summary: TEST: testing test
          description: test

And the rules file:

groups:
  - name: PrometheusAlertsGroup
  rules:
    - alert: test1
      expr: |
        1 > 0
        for: 0m
        labels:
          severity: critical
        annotations:
          summary: TEST: testing test
          description: test

But the problem is the same. Any ideas?

It finally worked when I created /tmp/loki/rules/fake/rules.yaml manually, but thats not the point to create it manually.


来源: stackexchange

问:
Why linux defines `__LITTLE/BIG_ENDIAN_BITFIELD` MACRO in `byteorder.h` for bitfields allocation order?
This question is related to Why bit endianness is an issue in bitfields? and __LITTLE_ENDIAN_BITFIELD and __BIG_ENDIAN_BITFIELD?, but is different: Why linux names the MACROs as __LITTLE/BIG_ENDIAN_BITFIELD and places them in byteorder.h?

Instead of __LEAST_TO_MOST/MOST_TO_LEAST_BITFIELD(or something similar) in bitfield.h(or something similar)?

Linux

include/uapi/linux/ip.h

struct iphdr {
#if defined(__LITTLE_ENDIAN_BITFIELD)
    __u8    ihl:4,
        version:4;
#elif defined (__BIG_ENDIAN_BITFIELD)
    __u8    version:4,
        ihl:4;
#else
#error  "Please fix <asm/byteorder.h>"
#endif
    __u8    tos;
    __be16  tot_len;
    __be16  id;
    __be16  frag_off;
    __u8    ttl;
    __u8    protocol;
    __sum16 check;
    __struct_group(/* no tag */, addrs, /* no attrs */,
        __be32  saddr;
        __be32  daddr;
    );
    /*The options start here. */
};
```
<p>include/uapi/linux/byteorder/little_endian.h</p>
<pre class="lang-c prettyprint-override"><code>#ifndef __LITTLE_ENDIAN
#define __LITTLE_ENDIAN 1234
#endif
#ifndef __LITTLE_ENDIAN_BITFIELD
#define __LITTLE_ENDIAN_BITFIELD
#endif
</code>```

Bitfields Allocation Order

"Endian"(i.e. byteorder) should have nothing to do with bitfields allocation order.

C17 Standard

Similar draft: N2310

6.7.2.1 Structure and union specifiers

[...]

Semantics

[...]

An implementation may allocate any addressable storage unit large enough to hold a bit-field. If
enough space remains, a bit-field that immediately follows another bit-field in a structure shall be
packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that
does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The
order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is
implementation-defined. The alignment of the addressable storage unit is unspecified.

Linux Standard Base 5.0 Specification

Take "Big-Endian" S390 as an example.
"Byte ordering" and "Bit-fields" are same-level sections, despite that "Bit-fields" requires "Bit-fields are allocated from left to right (most to least significant)." which aligns with byte order.

Bit Transmission Order

"Endian"(i.e. byteorder) should have nothing to do with bit transmission order(transmit most or least significant bit first), which should be dealt with in bus controller and NIC.

Expectation

There should be something like __LEAST_TO_MOST_BITFIELD/__MOST_TO_LEAST_BITFIELD MACRO in something like bitfield.h, instead of __LITTLE_ENDIAN_BITFIELD/__BIG_ENDIAN_BITFIELD MACRO in byteorder.h, because they are independent.

Other References

RFC791

Despite that there is "The order of transmission of the header and data described in this document is resolved to the octet level." in Appendix B, RFC791 still requires that Version = bytes[0] >> 4 and IHL = bytes[0] & 0x0f in Appendix B

```<code>Whenever an octet represents a numeric quantity the left most bit in the
diagram is the high order or most significant bit.  That is, the bit
labeled 0 is the most significant bit.  For example, the following
diagram represents the value 170 (decimal).

                            0 1 2 3 4 5 6 7
                           +-+-+-+-+-+-+-+-+
                           |1 0 1 0 1 0 1 0|
                           +-+-+-+-+-+-+-+-+

                          Significance of Bits
                               Figure 11.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This question is related to Why bit endianness is an issue in bitfields? and __LITTLE_ENDIAN_BITFIELD and __BIG_ENDIAN_BITFIELD?, but is different: Why linux names the MACROs as __LITTLE/BIG_ENDIAN_BITFIELD and places them in byteorder.h?

Instead of __LEAST_TO_MOST/MOST_TO_LEAST_BITFIELD(or something similar) in bitfield.h(or something similar)?

Linux

include/uapi/linux/ip.h

struct iphdr {
#if defined(__LITTLE_ENDIAN_BITFIELD)
    __u8    ihl:4,
        version:4;
#elif defined (__BIG_ENDIAN_BITFIELD)
    __u8    version:4,
        ihl:4;
#else
#error  "Please fix <asm/byteorder.h>"
#endif
    __u8    tos;
    __be16  tot_len;
    __be16  id;
    __be16  frag_off;
    __u8    ttl;
    __u8    protocol;
    __sum16 check;
    __struct_group(/* no tag */, addrs, /* no attrs */,
        __be32  saddr;
        __be32  daddr;
    );
    /*The options start here. */
};

include/uapi/linux/byteorder/little_endian.h

#ifndef __LITTLE_ENDIAN
#define __LITTLE_ENDIAN 1234
#endif
#ifndef __LITTLE_ENDIAN_BITFIELD
#define __LITTLE_ENDIAN_BITFIELD
#endif

Bitfields Allocation Order

"Endian"(i.e. byteorder) should have nothing to do with bitfields allocation order.

C17 Standard

Similar draft: N2310

6.7.2.1 Structure and union specifiers

[...]

Semantics

[...]

An implementation may allocate any addressable storage unit large enough to hold a bit-field. If
enough space remains, a bit-field that immediately follows another bit-field in a structure shall be
packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that
does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The
order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is
implementation-defined. The alignment of the addressable storage unit is unspecified.

Linux Standard Base 5.0 Specification

Take "Big-Endian" S390 as an example.
"Byte ordering" and "Bit-fields" are same-level sections, despite that "Bit-fields" requires "Bit-fields are allocated from left to right (most to least significant)." which aligns with byte order.

Bit Transmission Order

"Endian"(i.e. byteorder) should have nothing to do with bit transmission order(transmit most or least significant bit first), which should be dealt with in bus controller and NIC.

Expectation

There should be something like __LEAST_TO_MOST_BITFIELD/__MOST_TO_LEAST_BITFIELD MACRO in something like bitfield.h, instead of __LITTLE_ENDIAN_BITFIELD/__BIG_ENDIAN_BITFIELD MACRO in byteorder.h, because they are independent.

Other References

RFC791

Despite that there is "The order of transmission of the header and data described in this document is resolved to the octet level." in Appendix B, RFC791 still requires that Version = bytes[0] >> 4 and IHL = bytes[0] & 0x0f in Appendix B

Whenever an octet represents a numeric quantity the left most bit in the
diagram is the high order or most significant bit.  That is, the bit
labeled 0 is the most significant bit.  For example, the following
diagram represents the value 170 (decimal).

                            0 1 2 3 4 5 6 7
                           +-+-+-+-+-+-+-+-+
                           |1 0 1 0 1 0 1 0|
                           +-+-+-+-+-+-+-+-+

                          Significance of Bits
                               Figure 11.


问:
PacketTunnelProvider does not trigger the startTunnelWithOptions function
I downloaded an app about PacketTunnelProvider from github, and changed the bundleid of the app. The program can run and the function is easy to use.
But when I deleted the target of the PacketTunnel and tried to create a new target of the PacketTunnel myself, I found that the code was not executed, and the bundleid ID was still used, which was applied from the developer center.

I use xcode 13.2.1. I want to ask you to tell me why the new target is difficult to use, but the original one is. I guarantee that the bundleid is available.

I've tried many times, but I can't realize it. What configurations are missing


问:
How to highlight a row in a QTableWidget with a rounded rectangle?
I am using Pyside2 for python GUI. I am currently working on a QTableWidget. This QTableWidget has 3 columns and 10 rows.

First, when I click on any item in the QTableWidget, I want the entire row to be selected. So I set the selection behaviour using

```<code>self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
</code>```

Next, I want the entire row to be highlighted in a rounded rectangle shape, so I set the qt style sheet:

```<code>QTableWidget::item:selected{
    outline: none;
    background-color: #dbe7f4;
    border-radius: 9px;
}
</code>```

But the result is like this:

This is not what I expected. As shown in the picture, every cell in this row is highlighted with a rounded rectangle. But I expect the entire row to be highlighted with a rounded rectangle, which means I want the item in the first row to be 'rounded' in the top-left corner and bottom-left corner, and the item in the third row to be 'rounded' in the top-right corner and bottom-right corner.

Later I tried the qss below:

```<code>QTableWidget::item:column(0) {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    background-color: #dbe7f4;
}
QTableWidget::item:column(2) {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    background-color: #dbe7f4;
}
</code>```

However, it is not working. I also tried:

```<code>QTableWidget::item:selected:column(0) {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    background-color: #dbe7f4;
}
QTableWidget::item:selected:column(2) {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    background-color: #dbe7f4;
}
</code>```

It is not working either. It just didn't make any difference.

What am I supposed to do? Is there a better way?

Body:
I am using Pyside2 for python GUI. I am currently working on a QTableWidget. This QTableWidget has 3 columns and 10 rows.

First, when I click on any item in the QTableWidget, I want the entire row to be selected. So I set the selection behaviour using

self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

Next, I want the entire row to be highlighted in a rounded rectangle shape, so I set the qt style sheet:

QTableWidget::item:selected{
    outline: none;
    background-color: #dbe7f4;
    border-radius: 9px;
}

But the result is like this:

This is not what I expected. As shown in the picture, every cell in this row is highlighted with a rounded rectangle. But I expect the entire row to be highlighted with a rounded rectangle, which means I want the item in the first row to be 'rounded' in the top-left corner and bottom-left corner, and the item in the third row to be 'rounded' in the top-right corner and bottom-right corner.

Later I tried the qss below:

QTableWidget::item:column(0) {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    background-color: #dbe7f4;
}
QTableWidget::item:column(2) {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    background-color: #dbe7f4;
}

However, it is not working. I also tried:

QTableWidget::item:selected:column(0) {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    background-color: #dbe7f4;
}
QTableWidget::item:selected:column(2) {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    background-color: #dbe7f4;
}

It is not working either. It just didn't make any difference.

What am I supposed to do? Is there a better way?


问:
Windows Compilation problems: gcc with pkg-config error
OS: Windows 10, desktop pc

pkg-config --cflags gtk+-2.0
-mms-bitfields -Ik:/gtk/include/gtk-2.0 -Ik:/gtk/lib/gtk-2.0/include -Ik:/gtk/include/atk-1.0 -Ik:/gtk/include/cairo -Ik:/gtk/include/gdk-pixbuf-2.0 -Ik:/gtk/include/pango-1.0 -Ik:/gtk/include/glib-2.0 -Ik:/gtk/lib/glib-2.0/include -Ik:/gtk/include -Ik:/gtk/include/freetype2 -Ik:/gtk/include/libpng14

all ok

gcc pkg-config --cflags gtk+-2.0 test.cpp
gcc.exe error: pkg-config: No such file or directory
gcc.exe error: gtk+-2.0`: No such file or directory
gcc.exe error: unrecognized command line option '--cflags'

On other pc with Windows 10 i have not this problem.

What is the problem on this pc ?


问:
ActionMailer failed while using SMTP in production mode
Rails 7.0.1
I have tried and succeeded using ActionMailer in development environment, however it doesn't work in production environment. It seems that I am not able to receive the mail that I sent.

Here is the success(able to send mail) code of ActionMailer in config/environments/development.rb

```<code>config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
    address: '157.xxx.xxx.xxx',
    port: 25,
    authentication: :plain,
    enable_starttls_auto: false
  }
config.action_mailer.perform_deliveries = true
config.action_mailer.default_options = {from: 'hogehoge@example.com'}
</code>```

Here is the failed(not able to send mail) code of ActionMailer in config/environment/production.rb
after adding sidekiq and redis

```<code>config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
    port: 25,
    address: '157.xxx.xxx.xxx', #same as development one
    authentication: :plain,
    enable_starttls_auto: false
  }
config.action_mailer.perform_deliveries = true
config.action_mailer.default_options = {from: 'hogehoge@example.com'}
</code>```

Except raise_delivery_errors, everything remains in config/environment between development and production. Is there any place needs to be fix except config while turning into production?

Body:
Rails 7.0.1
I have tried and succeeded using ActionMailer in development environment, however it doesn't work in production environment. It seems that I am not able to receive the mail that I sent.

Here is the success(able to send mail) code of ActionMailer in config/environments/development.rb

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
    address: '157.xxx.xxx.xxx',
    port: 25,
    authentication: :plain,
    enable_starttls_auto: false
  }
config.action_mailer.perform_deliveries = true
config.action_mailer.default_options = {from: 'hogehoge@example.com'}

Here is the failed(not able to send mail) code of ActionMailer in config/environment/production.rb
after adding sidekiq and redis

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
    port: 25,
    address: '157.xxx.xxx.xxx', #same as development one
    authentication: :plain,
    enable_starttls_auto: false
  }
config.action_mailer.perform_deliveries = true
config.action_mailer.default_options = {from: 'hogehoge@example.com'}

Except raise_delivery_errors, everything remains in config/environment between development and production. Is there any place needs to be fix except config while turning into production?


问:
Dialog Window to flash when non parent form is clicked
I have a parent form (let's call it formA) which opens other forms (formB and formC) using the Show method. It also opens dialog a dialog (dialog1) using ShowDialog.

When dialog1 is open and the user clicks formA, the dialog window flashes. However if the user clicks on formB or formC the dialog does not flash (or come to the foreground).

If the formA and dialog1 are behind some other application and the user clicks on formB (which may be on a different monitor) they may get the impression that the application is froze.

Is there a way to have a blocking dialog (dialog1 in this case) flash regardless of what open form is clicked on.

A very quick way to reproduce this is to create a WinForms app with 2 buttons on it and the following code.

```<code>namespace DialogTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            Form1 form2 = new Form1();
            form2.Show();
        }

        private void btnShowDialog_Click(object sender, EventArgs e)
        {
            Form1 form3 = new Form1();
            form3.ShowDialog();
        }
    }
}
</code>```

I have tried to adjust the parent of the dialog and that simply changes which form it will flash for, it looks like a hierarchy approach works. For example, if formB shows the dialog and formB's parent is formA then clicking on formA or formB makes the dialog flash. But clicking on formC still does not make the dialog flash

Body:
I have a parent form (let's call it formA) which opens other forms (formB and formC) using the Show method. It also opens dialog a dialog (dialog1) using ShowDialog.

When dialog1 is open and the user clicks formA, the dialog window flashes. However if the user clicks on formB or formC the dialog does not flash (or come to the foreground).

If the formA and dialog1 are behind some other application and the user clicks on formB (which may be on a different monitor) they may get the impression that the application is froze.

Is there a way to have a blocking dialog (dialog1 in this case) flash regardless of what open form is clicked on.

A very quick way to reproduce this is to create a WinForms app with 2 buttons on it and the following code.

namespace DialogTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            Form1 form2 = new Form1();
            form2.Show();
        }

        private void btnShowDialog_Click(object sender, EventArgs e)
        {
            Form1 form3 = new Form1();
            form3.ShowDialog();
        }
    }
}

I have tried to adjust the parent of the dialog and that simply changes which form it will flash for, it looks like a hierarchy approach works. For example, if formB shows the dialog and formB's parent is formA then clicking on formA or formB makes the dialog flash. But clicking on formC still does not make the dialog flash


问:
THC-HYDRA ERROR: optional parameters must have the format X=value
This is my THC-Hydra command with json body form:

```<code>hydra -v -V -l abcd -p abcd -s 5000 192.168.162.130 http-post-form "/api/auth/login:{\"username\"\:\"^USER^\",\"password\"\:\"^PASS^\"}:H=Accept: application/json:H=Accept-Language: vi,en;q=0.9,en-GB;q=0.8,en-US;q=0.7:H=Accept-Encoding: gzip, deflate, br:H=Referer: http\://192.168.162.130:4200/:H=Origin: http\://192.168.162.130:4200:H=Connection: keep-alive"
</code>```

Note: 5000 is port for back-end and 4200 is port for front-end.

This is the error i get:

```<code>[INFORMATION] escape sequence \: detected in module option, no parameter verification is performed.
[DATA] max 1 task per 1 server, overall 1 task, 1 login try (l:1/p:1), ~1 try per task
[DATA] attacking http-post-form://192.168.162.130:5000/api/auth/login:{"username"\:"^USER^","password"\:"^PASS^"}:H=Accept: application/json:H=Accept-Language: vi,en;q=0.9,en-GB;q=0.8,en-US;q=0.7:H=Accept-Encoding: gzip, deflate, br:H=Referer: http\://192.168.162.130:4200/:H=Origin: http\://192.168.162.130:4200:H=Connection: keep-alive
[VERBOSE] Resolving addresses ... [VERBOSE] resolving done
[ERROR] optional parameters must have the format X=value:  application/json:H=Accept-Language: vi,en;q=0.9,en-GB;q=0.8,en-US;q=0.7:H=Accept-Encoding: gzip, deflate, br:H=Referer: http\://192.168.162.130:4200/:H=Origin: http\://192.168.162.130:4200:H=Connection: keep-alive
</code>```

Where do i miss ?

Body:
This is my THC-Hydra command with json body form:

hydra -v -V -l abcd -p abcd -s 5000 192.168.162.130 http-post-form "/api/auth/login:{\"username\"\:\"^USER^\",\"password\"\:\"^PASS^\"}:H=Accept: application/json:H=Accept-Language: vi,en;q=0.9,en-GB;q=0.8,en-US;q=0.7:H=Accept-Encoding: gzip, deflate, br:H=Referer: http\://192.168.162.130:4200/:H=Origin: http\://192.168.162.130:4200:H=Connection: keep-alive"

Note: 5000 is port for back-end and 4200 is port for front-end.

This is the error i get:

[INFORMATION] escape sequence \: detected in module option, no parameter verification is performed.
[DATA] max 1 task per 1 server, overall 1 task, 1 login try (l:1/p:1), ~1 try per task
[DATA] attacking http-post-form://192.168.162.130:5000/api/auth/login:{"username"\:"^USER^","password"\:"^PASS^"}:H=Accept: application/json:H=Accept-Language: vi,en;q=0.9,en-GB;q=0.8,en-US;q=0.7:H=Accept-Encoding: gzip, deflate, br:H=Referer: http\://192.168.162.130:4200/:H=Origin: http\://192.168.162.130:4200:H=Connection: keep-alive
[VERBOSE] Resolving addresses ... [VERBOSE] resolving done
[ERROR] optional parameters must have the format X=value:  application/json:H=Accept-Language: vi,en;q=0.9,en-GB;q=0.8,en-US;q=0.7:H=Accept-Encoding: gzip, deflate, br:H=Referer: http\://192.168.162.130:4200/:H=Origin: http\://192.168.162.130:4200:H=Connection: keep-alive

Where do i miss ?


问:
Conversion of plain PostgreSQL query to Slick query
I have a single table ABC with these (relevant) columns

```<code>create table abc
(
    transaction_id                   uuid                     not null,
    store_items                      jsonb                    not null,
);
</code>```

store_items is a Sequence[StoreItem] that looks like this:

```<code>{"itemId": "123",
"isAccountSafe": false
},
{"itemId": "456",
"isAccountSafe": true
},
{"itemId": "789",
"isAccountSafe": false
}
</code>```

I want to query the count of store_items in abc where isAccountSafe is false, in the above example the result would be 2. The tricky part is that I'm not joining multiple tables, I'm joining a single table with one of its columns.

Here's the postgres SQL that I got so far:

```<code>select count(transaction_id)
from abc
cross join jsonb_array_elements(store_items) elem
where not (elem->>'isAccountSafe')::boolean
</code>```

I've been wracking my brain figuring out how to do this in slick. My guess was to first do a query of the store_items first and then do a joinLeft, something like below, but it's wrong. I don't know how to filter isAccountSafe that sits inside the jsonb column.

```<code>
val getStoreItems = abc.map(_.storeItems)
val finalQuery = abc
  .joinLeft(getStoreItems)

</code>```

Body:
I have a single table ABC with these (relevant) columns

create table abc
(
    transaction_id                   uuid                     not null,
    store_items                      jsonb                    not null,
);

store_items is a Sequence[StoreItem] that looks like this:

{"itemId": "123",
"isAccountSafe": false
},
{"itemId": "456",
"isAccountSafe": true
},
{"itemId": "789",
"isAccountSafe": false
}

I want to query the count of store_items in abc where isAccountSafe is false, in the above example the result would be 2. The tricky part is that I'm not joining multiple tables, I'm joining a single table with one of its columns.

Here's the postgres SQL that I got so far:

select count(transaction_id)
from abc
cross join jsonb_array_elements(store_items) elem
where not (elem->>'isAccountSafe')::boolean

I've been wracking my brain figuring out how to do this in slick. My guess was to first do a query of the store_items first and then do a joinLeft, something like below, but it's wrong. I don't know how to filter isAccountSafe that sits inside the jsonb column.

val getStoreItems = abc.map(_.storeItems)
val finalQuery = abc
  .joinLeft(getStoreItems)


问:
How to use structural pattern matching (match-case) with regex?
What would be a "pythonic" way of expressing regex'es with Python 3.10's (and later) match-case statements (i.e, pattern matching)? It intuitively sounds like a good use case, but I cannot figure out a "clean" way of expressing something like:

```<code>s = "ham@spam.com"
match s:
    # cases matches s using regex
</code>```

Body:
What would be a "pythonic" way of expressing regex'es with Python 3.10's (and later) match-case statements (i.e, pattern matching)? It intuitively sounds like a good use case, but I cannot figure out a "clean" way of expressing something like:

s = "ham@spam.com"
match s:
    # cases matches s using regex


问:
can not use authentication with OAuth 2.0 with JavaMail 1.4
I want to use oauth with IMAP to authenticate to Microsoft Exchange Online in my project. I have log4j that has a dependency of javax.mail 1.4 so in all my project this version is used. To use oauth I have to update javax.mail to 1.6 and I was not successful to do that.

I tried to use javax.mail 1.6 and import it without log4j but it broke my project:

<dependency>
       <groupId>com.sun.mail</groupId>
       <artifactId>javax.mail</artifactId>
       <version>1.6.2</version>
</dependency>
```

I tried to find a version of log4j that uses javax.mail that supports oauth, but I didn't find anything.
Javax.mail is used in other parts of my project, so I don't want to touch those parts if possible.

I'm working on a legacy code, so for me it's important backwards compatibility and to not break my base code.

Body:
I want to use oauth with IMAP to authenticate to Microsoft Exchange Online in my project. I have log4j that has a dependency of javax.mail 1.4 so in all my project this version is used. To use oauth I have to update javax.mail to 1.6 and I was not successful to do that.

I tried to use javax.mail 1.6 and import it without log4j but it broke my project:

<dependency>
       <groupId>com.sun.mail</groupId>
       <artifactId>javax.mail</artifactId>
       <version>1.6.2</version>
</dependency>

I tried to find a version of log4j that uses javax.mail that supports oauth, but I didn't find anything.
Javax.mail is used in other parts of my project, so I don't want to touch those parts if possible.

I'm working on a legacy code, so for me it's important backwards compatibility and to not break my base code.


问:
How to get a list of Kubernetes resources from Terraform?
I need to get a list of Kubernetes resources (e.g. services) in a namespace that match a specific pattern. kubernetes_service will select a service with a known name, how do I find a list of services whose name is not known in advance?

A script around kubectl that implements an External Data Source might be able to do it, but was hoping that there's some way to do this with the native Kubernetes provider.


问:
How to Stop AWS aurora cluster using terraform?
I have set up Aurora regional clustor with terrafrm with one writer instance. But I am not currently using it as it is not needed at the moment, therefore I want to stop it using terraform.
In aws console i cant see that i can stop it but temporarily for 7 days and then it will be started again.I want to stop it using terraform unless i want it back.</p>
```<code>Is there any property that i can use in terraform to acheive this ?
</code>```

Body:
I have set up Aurora regional clustor with terrafrm with one writer instance. But I am not currently using it as it is not needed at the moment, therefore I want to stop it using terraform.
In aws console i cant see that i can stop it but temporarily for 7 days and then it will be started again.I want to stop it using terraform unless i want it back.

Is there any property that i can use in terraform to acheive this ?


问:
Date Validation end date must be greater or equal than start date using Yup
Hi I want to validate date in react using Yup
I want that the end date should be equal or greater than the start date

This what I have did but its not working for the equal dates

const validationSchema = Yup.object().shape({

  startDate: Yup.date().required('Please select start date'),
  endDate: Yup.date().min(
    Yup.ref('startDate'),
    "end date can't be before start date"
  ),

});```


问:
How to add exclutions to dependencies on maven
I have the following dependencies that unfortunately requires some classes which are not present on the default packages. First it is 'spring-cloud-starter-sleuth', when I add the local maven jar updated to version 3.1.5 it requires 'brave-context-slf4j' version 5.14.1 and I have added them without problems.

The problem is the standard dependencies which includes those jars e.g 'spring-cloud-dependencies' should exclude the other versions so this way I can use only spring-cloud-starter-sleuth:3.1.5 and brave-context-slf4j:5.14.1.

How could I add those exclusions to that dependencies?


问:
How to properly align Kivy/KivyMD widgets
I developed a GUI with KivyMD. It consists of eight box layout arranged vertically in another Box Layout. I started adding checkbox, labels and DropDownItem. Everything appears aligned except for the DropDownItem in the second row. I tried with pos_hint but I cannot move it along the x axis. I would like that the DropDownItem begins where the first checkbox of row1 begins.

Here is the full Kivy kv code:

```<code><InitializeComponent>:
   orientation: 'vertical'
   padding: 20

   MDBoxLayout:
      MDLabel:
         text: 'row 1'
      MDCheckbox:
      MDLabel:
         text: 'Item 1'
      MDCheckbox:
      MDLabel:
         text: 'Item 2'
      MDCheckbox:
      MDLabel:
         text: 'Item 3'
      MDCheckbox:
      MDLabel:
         text: 'Item 4'
      Widget:
         size_hint_x: None
         width: myCombo.width
      Widget:
         size_hint_x: None
         width: myCombo.width

   MDBoxLayout:
      MDLabel:
         text: 'row 2___________'
      MDDropDownItem:
         text: 'select'
         pos_hint: {"left":1, "center_y":0.5}
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         id: myCombo
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         id: myCombo
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____3'
      MDCheckbox:
      MDLabel:
         text: 'Item 5'
      MDCheckbox:
      MDLabel:
         text: 'Item 6'
      MDCheckbox:
      MDLabel:
         text: 'Item 7'
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____4_____'
      MDCheckbox:
      MDLabel:
         text: 'Item 8'
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____5'
      MDCheckbox:
      MDLabel:
         text: 'Item 9'
      MDCheckbox:
      MDLabel:
         text: 'Item 10'
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____6'
      MDCheckbox:
      MDLabel:
         text: 'Item 11'
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____7_______'
      MDCheckbox:
      MDLabel:
         text: 'Item 12'
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDRaisedButton:
         text: 'BUTTON'
         size_hint: 1, None
         pos_hint: {"center_x":0.5, "center_y":0.5}
</code>```

Any tip to keep the widgets aligned?

Body:
I developed a GUI with KivyMD. It consists of eight box layout arranged vertically in another Box Layout. I started adding checkbox, labels and DropDownItem. Everything appears aligned except for the DropDownItem in the second row. I tried with pos_hint but I cannot move it along the x axis. I would like that the DropDownItem begins where the first checkbox of row1 begins.

Here is the full Kivy kv code:

<InitializeComponent>:
   orientation: 'vertical'
   padding: 20

   MDBoxLayout:
      MDLabel:
         text: 'row 1'
      MDCheckbox:
      MDLabel:
         text: 'Item 1'
      MDCheckbox:
      MDLabel:
         text: 'Item 2'
      MDCheckbox:
      MDLabel:
         text: 'Item 3'
      MDCheckbox:
      MDLabel:
         text: 'Item 4'
      Widget:
         size_hint_x: None
         width: myCombo.width
      Widget:
         size_hint_x: None
         width: myCombo.width

   MDBoxLayout:
      MDLabel:
         text: 'row 2___________'
      MDDropDownItem:
         text: 'select'
         pos_hint: {"left":1, "center_y":0.5}
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         id: myCombo
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         id: myCombo
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____3'
      MDCheckbox:
      MDLabel:
         text: 'Item 5'
      MDCheckbox:
      MDLabel:
         text: 'Item 6'
      MDCheckbox:
      MDLabel:
         text: 'Item 7'
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____4_____'
      MDCheckbox:
      MDLabel:
         text: 'Item 8'
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____5'
      MDCheckbox:
      MDLabel:
         text: 'Item 9'
      MDCheckbox:
      MDLabel:
         text: 'Item 10'
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____6'
      MDCheckbox:
      MDLabel:
         text: 'Item 11'
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDLabel:
         text: 'row____7_______'
      MDCheckbox:
      MDLabel:
         text: 'Item 12'
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      Widget:
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}
      MDDropDownItem:
         text: 'select'
         pos_hint: {"center_y":0.5}

   MDBoxLayout:
      MDRaisedButton:
         text: 'BUTTON'
         size_hint: 1, None
         pos_hint: {"center_x":0.5, "center_y":0.5}

Any tip to keep the widgets aligned?


问:
Decrement model value in django
It's my first time using django to clear my schoolwork, I want to lower  Stock in my Book class by Quantity value,
ex.
Stock = 10 and Quantity = 1
Stock = 9 because 10 - 1 for Stock - Quantity
this is my code

main.html

```<code>{% load static %}
<html>
    <head>
        <title>
            Bookstore Management System
        </title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    </head>
    <body>
        {% include 'book/navbar.html' %}
        {% block content %}
        {% endblock %}
        <br>

        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    </body>
</html>
</code>```

home.html

```<code>{% extends 'book/main.html' %}
{% block content %}
<br>
    <div class="container jumbotron">
        <div class="container row">
            <div class="col-lg-10">
                <table class="table table-sm">
                    <tr>
                        <th>title</th>
                        <th>Author</th>
                        <th>Edition</th>
                        <th>Stock</th>
                        <th>Price</th>
                    </tr>
                    {% for book in books %}
                    <tr>
                        <td>{{book.title}}</td>
                        <td>{{book.Author}}</td>
                        <td>{{book.Edition}}</td>
                        <td>{{book.Stock}}</td>
                        <td>{{book.Price}}</td>
                        <td><a class="btn btn-sm btn-info" href="{% url 'addtocart' book.id %}">Add to cart</a></td>
                    </tr>
                    {% endfor %}
                </table>
            </div>
        </div>
    </div>
{% endblock %}
</code>```

viewcart.html

```<code>{% extends 'book/main.html' %}
{% load static %}
{% block content %}
<div class="container">
    <div class="row">
        <div class="col-lg-10"></div>
        <br>
        <h5>BOOKS:</h5>
        <div class="card card-body">
            <table>
                <tr>
                    <th>title</th>
                    <th>Author</th>
                    <th>Edition</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Total</th>

                </tr>
                {% for book in cart.books.all %}
                <tr>
                    <td>{{book.title}}</td>
                    <td>{{book.Author}}</td>
                    <td>{{book.Edition}}</td>
                    <td>{{book.Quantity}}</td>
                    <td>{{book.Price}}</td>
                    <td>{{book.Total}}</td>
                </tr>
                {% endfor %}
            </table>
        </div>
    </div>
</div>
{% endblock %}
</code>```

Model.py

```<code>from django.db import models
from django.db.models import F
from django.contrib.auth.models import User

class Book(models.Model):
    title=models.CharField(max_length=300, null=True)
    Author=models.CharField(max_length=300, null=True)
    Edition=models.IntegerField()
    Price=models.IntegerField()
    Stock=models.IntegerField()
    Quantity=models.IntegerField()
    Total=models.IntegerField()
    def decrementStock(self):
        self.Quantity += 1
        self.update(Stock=F('Stock') - F('Quantity'))
        self.save()
    def Tprice(self):
        self.update(Total=F('Price') * F('Quantity'))
        self.save()
    def _str_(self):
        return str(self.title)

class Customer(models.Model):
    user=models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name=models.CharField(max_length=200, null=True)
    phone=models.CharField(max_length=200, null=True)
    email=models.CharField(max_length=200, null=True)
    date_created=models.DateTimeField(auto_now_add=True, null=True)
    def _str_ (self):
        return str(self.name)

class Cart(models.Model):
    customer=models.OneToOneField(Customer, null=True, on_delete=models.CASCADE)
    books=models.ManyToManyField(Book)
    def _str_ (self):
        return str(self.customer)

</code>```

views.py

```<code>from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from django.contrib.auth import login,logout,authenticate
from .forms import *

def home(request):
    books=Book.objects.all()
    context={'books':books}
    if request.user.is_staff:
        return render(request, 'book/adminhome.html', context)
    else:
        return render(request, 'book/home.html', context)

def logoutPage(request):
    logout(request)
    return redirect('/')

def loginPage(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
        if request.method=="POST":
            username=request.POST.get('username')
            password=request.POST.get('password')
            user=authenticate(request,username=username, password=password)
            if user is not None:
                print("working")
                login(request,user)
                return redirect('/')
        context ={}
        return render(request,'book/login.html',context)

def registerPage(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
        form=createuserform()
        cust_form=createcustomerform()
        if request.method=='POST':
            form=createuserform(request.POST)
            cust_form=createcustomerform(request.POST)
            if form.is_valid() and cust_form.is_valid:
                user=form.save()
                customer=cust_form.save(commit=False)
                customer.user=user
                customer.save()
                return redirect('login')
        context={
            'form':form,
            'cust_form':cust_form
        }
        return render(request,'book/register.html', context)

def addbook(request):
    form=createbookform()
    if request.method=='POST':
        form=createbookform(request.POST)
        if form.is_valid():
            form.save()
        return redirect('/')
    context={'form':form}
    return render(request,'book.addbook.html', context)

def viewcart(request):
    cust=Customer.objects.filter(user=request.user)
    for c in cust:
        carts=Cart.objects.all()
        for cart in carts:
            if(cart.customer==c):
                context={
                    'cart':cart
                }
                return render(request, 'book/viewcart.html', context)
        else:
            return render(request,'book/emptycart.html')

def addtocart(request,pk):
    book=Book.objects.get(id=pk)
    Book.objects.get(Quantity=pk).decrementStock()
    cust=Customer.objects.filter(user=request.user)

    for c in cust:
        carts=Cart.objects.all()
        reqcart=''
        for cart in carts:
            if(cart.customer==c):
                reqcart=cart
                break
        if(reqcart==''):
            reqcart=Cart.objects.create(
                customer=c,
            )
        reqcart.books.add(book)
    return redirect('/')
</code>```

in model.py and views.py are wrong but i dont know to fix it
sorry for my bad english writing and i thank you for poeple to helped me.

I try by editing model.py by using this but its failed and get these error
`

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/addtocart/1

Django Version: 3.2
Python Version: 3.10.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'book']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "C:\coding python\MHB\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\coding python\MHB\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\coding python\MHB\Scripts\bookstore\book\views.py", line 80, in addtocart
    Book.objects.get(Quantity=pk).decrementStock()
  File "C:\coding python\MHB\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\coding python\MHB\lib\site-packages\django\db\models\query.py", line 435, in get
    raise self.model.DoesNotExist(

Exception Type: DoesNotExist at /addtocart/1
Exception Value: Book matching query does not exist.
</code>```

`

Title: Decrement model value in django

Body:
It's my first time using django to clear my schoolwork, I want to lower  Stock in my Book class by Quantity value,
ex.
Stock = 10 and Quantity = 1
Stock = 9 because 10 - 1 for Stock - Quantity
this is my code

main.html

{% load static %}

        <title>
            Bookstore Management System
        </title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

        {% include 'book/navbar.html' %}
        {% block content %}
        {% endblock %}

home.html

{% extends 'book/main.html' %}
{% block content %}

                        title
                        Author
                        Edition
                        Stock
                        Price

                    {% for book in books %}

                        {{book.title}}
                        {{book.Author}}
                        {{book.Edition}}
                        {{book.Stock}}
                        {{book.Price}}
                        Add to cart

                    {% endfor %}

{% endblock %}

viewcart.html

{% extends 'book/main.html' %}
{% load static %}
{% block content %}

BOOKS:

                    title
                    Author
                    Edition
                    Quantity
                    Price
                    Total

                {% for book in cart.books.all %}

                    {{book.title}}
                    {{book.Author}}
                    {{book.Edition}}
                    {{book.Quantity}}
                    {{book.Price}}
                    {{book.Total}}

                {% endfor %}

{% endblock %}

Model.py

from django.db import models
from django.db.models import F
from django.contrib.auth.models import User

class Book(models.Model):
    title=models.CharField(max_length=300, null=True)
    Author=models.CharField(max_length=300, null=True)
    Edition=models.IntegerField()
    Price=models.IntegerField()
    Stock=models.IntegerField()
    Quantity=models.IntegerField()
    Total=models.IntegerField()
    def decrementStock(self):
        self.Quantity += 1
        self.update(Stock=F('Stock') - F('Quantity'))
        self.save()
    def Tprice(self):
        self.update(Total=F('Price') * F('Quantity'))
        self.save()
    def _str_(self):
        return str(self.title)

class Customer(models.Model):
    user=models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name=models.CharField(max_length=200, null=True)
    phone=models.CharField(max_length=200, null=True)
    email=models.CharField(max_length=200, null=True)
    date_created=models.DateTimeField(auto_now_add=True, null=True)
    def _str_ (self):
        return str(self.name)

class Cart(models.Model):
    customer=models.OneToOneField(Customer, null=True, on_delete=models.CASCADE)
    books=models.ManyToManyField(Book)
    def _str_ (self):
        return str(self.customer)

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from django.contrib.auth import login,logout,authenticate
from .forms import *

def home(request):
    books=Book.objects.all()
    context={'books':books}
    if request.user.is_staff:
        return render(request, 'book/adminhome.html', context)
    else:
        return render(request, 'book/home.html', context)

def logoutPage(request):
    logout(request)
    return redirect('/')

def loginPage(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
        if request.method=="POST":
            username=request.POST.get('username')
            password=request.POST.get('password')
            user=authenticate(request,username=username, password=password)
            if user is not None:
                print("working")
                login(request,user)
                return redirect('/')
        context ={}
        return render(request,'book/login.html',context)

def registerPage(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
        form=createuserform()
        cust_form=createcustomerform()
        if request.method=='POST':
            form=createuserform(request.POST)
            cust_form=createcustomerform(request.POST)
            if form.is_valid() and cust_form.is_valid:
                user=form.save()
                customer=cust_form.save(commit=False)
                customer.user=user
                customer.save()
                return redirect('login')
        context={
            'form':form,
            'cust_form':cust_form
        }
        return render(request,'book/register.html', context)

def addbook(request):
    form=createbookform()
    if request.method=='POST':
        form=createbookform(request.POST)
        if form.is_valid():
            form.save()
        return redirect('/')
    context={'form':form}
    return render(request,'book.addbook.html', context)

def viewcart(request):
    cust=Customer.objects.filter(user=request.user)
    for c in cust:
        carts=Cart.objects.all()
        for cart in carts:
            if(cart.customer==c):
                context={
                    'cart':cart
                }
                return render(request, 'book/viewcart.html', context)
        else:
            return render(request,'book/emptycart.html')

def addtocart(request,pk):
    book=Book.objects.get(id=pk)
    Book.objects.get(Quantity=pk).decrementStock()
    cust=Customer.objects.filter(user=request.user)

    for c in cust:
        carts=Cart.objects.all()
        reqcart=''
        for cart in carts:
            if(cart.customer==c):
                reqcart=cart
                break
        if(reqcart==''):
            reqcart=Cart.objects.create(
                customer=c,
            )
        reqcart.books.add(book)
    return redirect('/')

in model.py and views.py are wrong but i dont know to fix it
sorry for my bad english writing and i thank you for poeple to helped me.

I try by editing model.py by using this but its failed and get these error
`

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/addtocart/1

Django Version: 3.2
Python Version: 3.10.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'book']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "C:\coding python\MHB\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\coding python\MHB\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\coding python\MHB\Scripts\bookstore\book\views.py", line 80, in addtocart
    Book.objects.get(Quantity=pk).decrementStock()
  File "C:\coding python\MHB\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\coding python\MHB\lib\site-packages\django\db\models\query.py", line 435, in get
    raise self.model.DoesNotExist(

Exception Type: DoesNotExist at /addtocart/1
Exception Value: Book matching query does not exist.

`


问:
Not able to RemoveFromGroupAsync (signalr)
I am trying to remove a connectionId from a Group in Signalr. The method I want to call from the client (JS) is called UbsubscribeFromProject.

Here is the Hub file:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using OptTurnaroundApi.Repositories;
using OptTurnaroundApi.Services;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace OptTurnaroundApi.Hubs
{
    [Authorize]
    public class MyHub : Hub
    {
        private readonly IUserRepository _userRepository;
        private readonly IAuthService _authService;
        private readonly ILogger<MyHub> _logger;

        public MyHub(IUserRepository userRepository, IAuthService authService, ILogger<MyHub> logger)
        {
            _userRepository = userRepository;
            _authService = authService;
            _logger = logger;
        }

        public async Task SubscribeToProject(string projectId)
        {
            var user = _userRepository.GetCurrentUser(true);

            try
            {

                await Groups.AddToGroupAsync(Context.ConnectionId, $"Project{projectId}");
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"User {user.UserName} could not subscribe to project {projectId}: {ex.Message}");
            }
        }
        public async Task UnsubscribeFromProject(string projectId)
        {
            var user = _userRepository.GetCurrentUser(true);

            try
            {

                await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"Project{projectId}");
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"User {user.UserName} could not unsubscribe  project {projectId}: {ex.Message}");
            }
        }

        public string GetConnectionId()
        {
            return Context.ConnectionId;
        }
    }
}

```
<p>I am able to call the SubscribeToProject function from the frontend, but when I try to call the UnsubscribeFromProject I am not even seeing that it is being sent in the Websockets window in the network tab for chrome developer tools.</p>
<p>I have no idea why it is not being called, when the code is clearly being run on the frontend (tried debugging to see that UnsubscribeFromProject is indeed called with defined parameters)</p>
<p>The function that is being triggered on the client is the following:</p>
<pre class="lang-js prettyprint-override"><code>  const subscribeToNewProject = useCallback(
    ({ previousProjectId, connection }) => {
      // subscribe to new project when user changes project
      if (
        previousProjectId &&
        connection &&
        projectId &&
        previousProjectId !== projectId
      ) {
        // subscribe to a new project Id if the user changes project
        connection.invoke("SubscribeToProject", projectId.toString());
        connection.invoke(
          "UnsubscribeFromProject",
          previousProjectId.toString()
        );
        setPreviousProjectId(projectId);
      }
    },
    [projectId]
  );

</code>```

Body:
I am trying to remove a connectionId from a Group in Signalr. The method I want to call from the client (JS) is called UbsubscribeFromProject.

Here is the Hub file:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using OptTurnaroundApi.Repositories;
using OptTurnaroundApi.Services;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace OptTurnaroundApi.Hubs
{
    [Authorize]
    public class MyHub : Hub
    {
        private readonly IUserRepository _userRepository;
        private readonly IAuthService _authService;
        private readonly ILogger<MyHub> _logger;

        public MyHub(IUserRepository userRepository, IAuthService authService, ILogger<MyHub> logger)
        {
            _userRepository = userRepository;
            _authService = authService;
            _logger = logger;
        }

        public async Task SubscribeToProject(string projectId)
        {
            var user = _userRepository.GetCurrentUser(true);

            try
            {

                await Groups.AddToGroupAsync(Context.ConnectionId, $"Project{projectId}");
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"User {user.UserName} could not subscribe to project {projectId}: {ex.Message}");
            }
        }
        public async Task UnsubscribeFromProject(string projectId)
        {
            var user = _userRepository.GetCurrentUser(true);

            try
            {

                await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"Project{projectId}");
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"User {user.UserName} could not unsubscribe  project {projectId}: {ex.Message}");
            }
        }

        public string GetConnectionId()
        {
            return Context.ConnectionId;
        }
    }
}

I am able to call the SubscribeToProject function from the frontend, but when I try to call the UnsubscribeFromProject I am not even seeing that it is being sent in the Websockets window in the network tab for chrome developer tools.

I have no idea why it is not being called, when the code is clearly being run on the frontend (tried debugging to see that UnsubscribeFromProject is indeed called with defined parameters)

The function that is being triggered on the client is the following:

  const subscribeToNewProject = useCallback(
    ({ previousProjectId, connection }) => {
      // subscribe to new project when user changes project
      if (
        previousProjectId &&
        connection &&
        projectId &&
        previousProjectId !== projectId
      ) {
        // subscribe to a new project Id if the user changes project
        connection.invoke("SubscribeToProject", projectId.toString());
        connection.invoke(
          "UnsubscribeFromProject",
          previousProjectId.toString()
        );
        setPreviousProjectId(projectId);
      }
    },
    [projectId]
  );


问:
Container query units in sizes attribute image tag not working
When using container query width (cqw) in the sizes attribute of an image tag the incorrect image variation is requested.

```

When running this code you will see that the 1000w variation is requested. While you would expect that 100w or 400w to be requested (depending on your screen DPI), because the container has a width of 100px.

Does someone know if container query width is supported by the sizes attribute?

Body:
When using container query width (cqw) in the sizes attribute of an image tag the incorrect image variation is requested.

When running this code you will see that the 1000w variation is requested. While you would expect that 100w or 400w to be requested (depending on your screen DPI), because the container has a width of 100px.

Does someone know if container query width is supported by the sizes attribute?


问:
Javascript:How to trigger input field to simulate change after dynamically inputting value?
I am triggering a modal on Swagger UI page load then setting the value of input field of Bearer token and then wish to click on the 'Authorize' button programmatically to close the bearer token modal(Screenshot below).But the button seems disabled and unless I manually type something in the input it does not get enabled.What could be the issue?

```<code>   window.addEventListener('load', function() {

        // On Load triggers Modal Popup
        const authorizeButton = document.getElementsByClassName('authorize')[0];
        authorizeButton.click();

        //Set Input Field
        const abcd = document.querySelectorAll('[aria-label="auth-bearer-value"]');
        abcd[0].value = 'abcd';

        abcd[0].dispatchEvent(new Event('change'));
        abcd[0].dispatchEvent(new Event('keydown'));
        abcd[0].dispatchEvent(new Event('keypress'));
        abcd[0].dispatchEvent(new Event('keyup'));
        abcd[0].dispatchEvent(new Event('input'));

       // Need to Click on 'Authorize' button as shown in screenshot but it seems to be disabled
}
</code>```

Body:
I am triggering a modal on Swagger UI page load then setting the value of input field of Bearer token and then wish to click on the 'Authorize' button programmatically to close the bearer token modal(Screenshot below).But the button seems disabled and unless I manually type something in the input it does not get enabled.What could be the issue?

   window.addEventListener('load', function() {

        // On Load triggers Modal Popup
        const authorizeButton = document.getElementsByClassName('authorize')[0];
        authorizeButton.click();

        //Set Input Field
        const abcd = document.querySelectorAll('[aria-label="auth-bearer-value"]');
        abcd[0].value = 'abcd';

        abcd[0].dispatchEvent(new Event('change'));
        abcd[0].dispatchEvent(new Event('keydown'));
        abcd[0].dispatchEvent(new Event('keypress'));
        abcd[0].dispatchEvent(new Event('keyup'));
        abcd[0].dispatchEvent(new Event('input'));

       // Need to Click on 'Authorize' button as shown in screenshot but it seems to be disabled
}


问:
RTK Query pagination not working with custom baseQuery and createApiAdapter
I created a react application with RTK Query to build a generic base query for a project but I faced an issue the creatSelector method because the selectors it creates don't update the ids and entitle the array when the data changes

Store

```<code>
    import { configureStore } from "@reduxjs/toolkit";
    import { apiSlice, authSlice, genericSlice } from "../features/api/apiSlice";

    export const store = configureStore({
      reducer: {
        [apiSlice.reducerPath]: apiSlice.reducer,
        [authSlice.reducerPath]: authSlice.reducer,
        [genericSlice.reducerPath]: genericSlice.reducer,
      },
      middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware()
          .concat(apiSlice.middleware)
          .concat(authSlice.middleware)
          .concat(genericSlice.middleware),
      devTools: true,
    });

</code>```

Custom base query

```<code>
    import { BaseQueryFn } from "@reduxjs/toolkit/dist/query";

    export const genericBaseQuery =
      (): BaseQueryFn<any, unknown, unknown> => async (fn: any) => {
        try {
          const result = await fn;
          return {
            data: {
              data: result,
              success: true,
              message: result,
            },
          };
        } catch (error) {
          throw new Error("errrorrrrsss");
        }
      };

</code>```

API slice

```<code>export const genericSlice = createApi({
  reducerPath: "genericApi",
  tagTypes: ["bookingRecords"],
  baseQuery: genericBaseQuery(),
  endpoints: (builder) => ({}),
});
</code>```

Booking records slice

```<code>const bookingRecordsAdapter = createEntityAdapter({
  selectId: (bookingRecord: any) => bookingRecord.id,
});

const initialState = bookingRecordsAdapter.getInitialState();

export const extendedApiSlice = genericSlice.injectEndpoints({
  endpoints: (builder) => ({
    listBookingRecords: builder.query({
      query: (request: FindBookingRecords) =>
        axiosApi.findBookingRecords(request),
      transformResponse: (response: any) => {
        const changedBookingRecords: IBookingRecordResponse[] =
          response.data.data.bookingRecords;
        return bookingRecordsAdapter.setAll(
          initialState,
          changedBookingRecords
        );
      },
      async onQueryStarted(
        { pagination, filter, sort, ...patch },
        { dispatch, queryFulfilled }
      ) {
        console.log("fsafasfasfa")
        const patchResult = dispatch(
          extendedApiSlice.util.updateQueryData(
            "listBookingRecords",
            { pagination, filter, sort },
            (draft) => {
              console.log("draft", draft);
              console.log("patch", patch);
              Object.assign(draft, patch);
            }
          )
        );
        try {
          await (await queryFulfilled).data;
        } catch {
          extendedApiSlice.util.invalidateTags(["bookingRecords"])
          patchResult.undo();

          /**
           * Alternatively, on failure you can invalidate the corresponding cache tags
           * to trigger a re-fetch:
           * dispatch(api.util.invalidateTags(['Post']))
           */
        }
      },
      providesTags: (result: any) => [
        { type: "bookingRecords", id: "LIST" },
        ...result.ids.map((id: any) => ({ type: "bookingRecords", id })),
      ],
    }),
    listBookingRecordById: builder.query({
      query: (request: FindBookingRecord) =>
        axiosApi.findBookingRecord(request),
      transformResponse: (response: any) => {
        const changedBookingRecord: IBookingRecordResponse = response.data.data;
        return changedBookingRecord;
      },
    }),
    addBookingRecord: builder.mutation({
</code>```

list

```<code>export default function BookingRecordsList() {
  const [pageSize, setPageSize] = useState<number>(10);
  const [offset, setOffset] = useState<number>(0);

  const { data, isError, isLoading, isSuccess, isFetching, originalArgs } =
    useListBookingRecordsQuery({
      pagination: { limit: pageSize, offset: offset },
    });

  const navigate = useNavigate();

  const bookingRecordIds = useSelector(selectBookingRecordsIds);

  console.log("data", data);
  console.log("bookingRecordIds", bookingRecordIds);
  console.log("originalArgs", originalArgs);

  const [signOut, { isLoading: signOutLoading }] = useSignOutMutation();
  const canSignOut = !signOutLoading;

  const test = () => {
    if (isLoading || isFetching) {
      return <div>loading...</div>;
    }
    if (isSuccess) {
      return bookingRecordIds?.map((id: any) => {
        return <BookingRecordListItem id={id.toString()} key={id} />;
      });
    }
    if (isError) {
      return <div>error</div>;
    }
  };

  const onSignOutClicked = async () => {
    if (canSignOut) {
      try {
        await signOut({}).unwrap();
        navigate("/signIn");
      } catch (err) {
        console.error("Failed to sign out", err);
      }
    }
  };

  return (
    <div>
      <button
        onClick={() => {
          navigate("/bookingRecords/add");
        }}
        style={{ padding: "5px", margin: "10px" }}
      >
        add booking record
      </button>
      <select
        onChange={(e) => {
          let offset = parseInt(e.target.value);
          setOffset(Math.abs((offset - 1) * pageSize));
        }}
        style={{ padding: "5px", margin: "10px" }}
      >
        <option value={0}>0</option>
        <option value={1}>1</option>
        <option value={2}>2</option>
        <option value={3}>3</option>
        <option value={4}>4</option>
      </select>
      <button
        onClick={onSignOutClicked}
        style={{ padding: "5px", margin: "10px" }}
      >
        signOut
      </button>
      {test()}
      {/* <button onClick={() => addUser({ iata: "tst", name: "test" })}>
        add user
      </button> */}
    </div>
  );}
</code>```

when i fetch the data for the first time every thing works fine. when i change the offset a request is sent and the new data is fetched but the ids array and entities array didnt change keeping the old data even the the data got from the hook is updated

Body:
I created a react application with RTK Query to build a generic base query for a project but I faced an issue the creatSelector method because the selectors it creates don't update the ids and entitle the array when the data changes

Store

    import { configureStore } from "@reduxjs/toolkit";
    import { apiSlice, authSlice, genericSlice } from "../features/api/apiSlice";

    export const store = configureStore({
      reducer: {
        [apiSlice.reducerPath]: apiSlice.reducer,
        [authSlice.reducerPath]: authSlice.reducer,
        [genericSlice.reducerPath]: genericSlice.reducer,
      },
      middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware()
          .concat(apiSlice.middleware)
          .concat(authSlice.middleware)
          .concat(genericSlice.middleware),
      devTools: true,
    });

Custom base query

    import { BaseQueryFn } from "@reduxjs/toolkit/dist/query";

    export const genericBaseQuery =
      (): BaseQueryFn<any, unknown, unknown> => async (fn: any) => {
        try {
          const result = await fn;
          return {
            data: {
              data: result,
              success: true,
              message: result,
            },
          };
        } catch (error) {
          throw new Error("errrorrrrsss");
        }
      };

API slice

export const genericSlice = createApi({
  reducerPath: "genericApi",
  tagTypes: ["bookingRecords"],
  baseQuery: genericBaseQuery(),
  endpoints: (builder) => ({}),
});

Booking records slice

const bookingRecordsAdapter = createEntityAdapter({
  selectId: (bookingRecord: any) => bookingRecord.id,
});

const initialState = bookingRecordsAdapter.getInitialState();

export const extendedApiSlice = genericSlice.injectEndpoints({
  endpoints: (builder) => ({
    listBookingRecords: builder.query({
      query: (request: FindBookingRecords) =>
        axiosApi.findBookingRecords(request),
      transformResponse: (response: any) => {
        const changedBookingRecords: IBookingRecordResponse[] =
          response.data.data.bookingRecords;
        return bookingRecordsAdapter.setAll(
          initialState,
          changedBookingRecords
        );
      },
      async onQueryStarted(
        { pagination, filter, sort, ...patch },
        { dispatch, queryFulfilled }
      ) {
        console.log("fsafasfasfa")
        const patchResult = dispatch(
          extendedApiSlice.util.updateQueryData(
            "listBookingRecords",
            { pagination, filter, sort },
            (draft) => {
              console.log("draft", draft);
              console.log("patch", patch);
              Object.assign(draft, patch);
            }
          )
        );
        try {
          await (await queryFulfilled).data;
        } catch {
          extendedApiSlice.util.invalidateTags(["bookingRecords"])
          patchResult.undo();

          /**
           * Alternatively, on failure you can invalidate the corresponding cache tags
           * to trigger a re-fetch:
           * dispatch(api.util.invalidateTags(['Post']))
           */
        }
      },
      providesTags: (result: any) => [
        { type: "bookingRecords", id: "LIST" },
        ...result.ids.map((id: any) => ({ type: "bookingRecords", id })),
      ],
    }),
    listBookingRecordById: builder.query({
      query: (request: FindBookingRecord) =>
        axiosApi.findBookingRecord(request),
      transformResponse: (response: any) => {
        const changedBookingRecord: IBookingRecordResponse = response.data.data;
        return changedBookingRecord;
      },
    }),
    addBookingRecord: builder.mutation({

list

export default function BookingRecordsList() {
  const [pageSize, setPageSize] = useState<number>(10);
  const [offset, setOffset] = useState<number>(0);

  const { data, isError, isLoading, isSuccess, isFetching, originalArgs } =
    useListBookingRecordsQuery({
      pagination: { limit: pageSize, offset: offset },
    });

  const navigate = useNavigate();

  const bookingRecordIds = useSelector(selectBookingRecordsIds);

  console.log("data", data);
  console.log("bookingRecordIds", bookingRecordIds);
  console.log("originalArgs", originalArgs);

  const [signOut, { isLoading: signOutLoading }] = useSignOutMutation();
  const canSignOut = !signOutLoading;

  const test = () => {
    if (isLoading || isFetching) {
      return
loading...
;
    }
    if (isSuccess) {
      return bookingRecordIds?.map((id: any) => {
        return <BookingRecordListItem id={id.toString()} key={id} />;
      });
    }
    if (isError) {
      return
error
;
    }
  };

  const onSignOutClicked = async () => {
    if (canSignOut) {
      try {
        await signOut({}).unwrap();
        navigate("/signIn");
      } catch (err) {
        console.error("Failed to sign out", err);
      }
    }
  };

  return (

      <button
        onClick={() => {
          navigate("/bookingRecords/add");
        }}
        style={{ padding: "5px", margin: "10px" }}
      >
        add booking record
      </button>
      <select
        onChange={(e) => {
          let offset = parseInt(e.target.value);
          setOffset(Math.abs((offset - 1) * pageSize));
        }}
        style={{ padding: "5px", margin: "10px" }}
      >
        <option value={0}>0</option>
        <option value={1}>1</option>
        <option value={2}>2</option>
        <option value={3}>3</option>
        <option value={4}>4</option>
      </select>
      <button
        onClick={onSignOutClicked}
        style={{ padding: "5px", margin: "10px" }}
      >
        signOut
      </button>
      {test()}
      {/* <button onClick={() => addUser({ iata: "tst", name: "test" })}>
        add user
      </button> */}

  );}

when i fetch the data for the first time every thing works fine. when i change the offset a request is sent and the new data is fetched but the ids array and entities array didnt change keeping the old data even the the data got from the hook is updated


问:
Using auto_increment id field value in other columns in the table
I am using mysql 8.0.30.
I have an orders table which is defined as follows:

```<code>create table orders (
id INT AUTO_INCREMENT NOT NULL  PRIMARY KEY,
code varchar (64) NOT NULL,
ord_num varchar(512) NOT NULL );
</code>```

After inserting a rows, I would like to have it as follows:

```<code>+----+------+-------+
| id | code | ord_num|
+----+------+-------+
|  1 | abc  | abc-1 |
|  2 | def  | def-2 |
+----+------+-------+
</code>```

That is ord_num should have concatenation of code-id. I can achieve that by an update statement as follows:

```<code>update orders set ord_num = concat (code, '-', id ) where id = 2;
</code>```

However, I would like to achieve that in the insert statemenet. For ex:

```<code>insert into orders (code, ord_num) values ("xyz", concat(code, '-', id));
</code>```

This actually results in:

```<code>+----+------+-----------+
| id | code | ord_num   |
+----+------+-----------+
|  1 | abc  | abc-0     |
|  2 | def  | def-2     |
|  3 | xyz  | xyz-0     |
+----+------+-----------+
</code>```

I know I can do this by starting a transaction, insert with some dummy value in ord_num, then updating it with the correct value before committing. I would prefer to do it in one insert statement, if possible?

Body:
I am using mysql 8.0.30.
I have an orders table which is defined as follows:

create table orders (
id INT AUTO_INCREMENT NOT NULL  PRIMARY KEY,
code varchar (64) NOT NULL,
ord_num varchar(512) NOT NULL );

After inserting a rows, I would like to have it as follows:

+----+------+-------+
| id | code | ord_num|
+----+------+-------+
|  1 | abc  | abc-1 |
|  2 | def  | def-2 |
+----+------+-------+

That is ord_num should have concatenation of code-id. I can achieve that by an update statement as follows:

update orders set ord_num = concat (code, '-', id ) where id = 2;

However, I would like to achieve that in the insert statemenet. For ex:

insert into orders (code, ord_num) values ("xyz", concat(code, '-', id));

This actually results in:

+----+------+-----------+
| id | code | ord_num   |
+----+------+-----------+
|  1 | abc  | abc-0     |
|  2 | def  | def-2     |
|  3 | xyz  | xyz-0     |
+----+------+-----------+

I know I can do this by starting a transaction, insert with some dummy value in ord_num, then updating it with the correct value before committing. I would prefer to do it in one insert statement, if possible?


问:
Track Elementor form submissions as conversions in GA4
I would really appreciate your help!

The company I work for has an Elementor website with different forms on separate pages. There is no Thank You Page with form submissions.

We want to track the various forms as individual conversions in GA4, but we don't want to track it based on page URL.

If anyone has any tips or resources they could point me to, it would be HIGHLY appreciated!

I tried tracking page URL, but we are afraid URL changes in the future, so we need a different solution please.