问:
Spring Boot 3 authorization with requestMatchers does not authorize access to login page
While migrating a Spring Boot 2.7 application to Spring Boot 3.0.0, I am facing a problem with the login form. This is the configuration before the migration and it worked perfectly:

```<code>http.authorizeRequests()
.antMatchers("/login*").permitAll()
.antMatchers("/resources/**").permitAll()
.and().httpBasic().disable();

http.authorizeRequests()
     .antMatchers("/**").access("hasAnyRole('ROLE_USER')")
     .antMatchers("/admin/**").access("hasRole('ROLE_SUPERADMIN')")
</code>```

This would make sure that any request to the application had to be authenticated with the role "USER" while allowing to display the login form anonymously.

With Spring Security 6, I replaced antMatchers with requestsMatchers and there is no way to tell Spring that the login form is authorized without authentication. The only possibility is to allow access to any URL by default. The following is a configuration that works:

```<code>http.authorizeHttpRequests
.requestMatchers("/content/**").hasRole("USER")
.requestMatchers("/admin/**").hasRole("SUPERADMIN")
.requestMatchers("/**").permitAll()
</code>```

But that is not what I really want because this config gives access to any URL by default. What I want is to protect any URL and only give access to the login page, something like this:

```<code>http.authorizeHttpRequests
.requestMatchers("/login**").permitAll()
.requestMatchers("/resources/**").permitAll()
.requestMatchers("/admin/**").hasRole("SUPERADMIN")
.requestMatchers("/**").hasRole("USER")
</code>```

But this does not work any more : Spring considers the login page to be protected. Therefore, on login it generates a loop of redirect to the login page.

I have tried different pattenrs : "/login*", "/login**", "/login.html" (the actual login URL), but it does not work unless I give default access to all URL.

Below is the complete SecurityFilterChain that I am currently using.

```<code>@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

// De-activate XSS protection
http.headers().xssProtection().disable();
http.httpBasic().disable();
http.authorizeHttpRequests()
    .requestMatchers("/content/**").hasRole("USER")
    .requestMatchers("/admin/**").hasRole("SUPERADMIN")
    .requestMatchers("/**").permitAll()
    .and()
    .formLogin()
    .successHandler(customLoginSuccessHandler)
    .failureHandler(customAuthenticationFailureHandle).loginPage("/login.html")
    .usernameParameter("username")//
    .passwordParameter("password")//
    .and().logout().logoutSuccessUrl("/login.html")//
    .and()
    .exceptionHandling().accessDeniedHandler(accessDeniedHandler())//
    .and().rememberMe().tokenRepository(persistentTokenRepository())//
    .tokenValiditySeconds(1209600)// 2 weeks
    .alwaysRemember(true).useSecureCookie(true).and().csrf();

    http.securityContext((securityContext) -> securityContext.requireExplicitSave(true));

    return http.build();
}
</code>```

Body:
While migrating a Spring Boot 2.7 application to Spring Boot 3.0.0, I am facing a problem with the login form. This is the configuration before the migration and it worked perfectly:

http.authorizeRequests()
.antMatchers("/login*").permitAll()
.antMatchers("/resources/**").permitAll()
.and().httpBasic().disable();

http.authorizeRequests()
     .antMatchers("/**").access("hasAnyRole('ROLE_USER')")
     .antMatchers("/admin/**").access("hasRole('ROLE_SUPERADMIN')")

This would make sure that any request to the application had to be authenticated with the role "USER" while allowing to display the login form anonymously.

With Spring Security 6, I replaced antMatchers with requestsMatchers and there is no way to tell Spring that the login form is authorized without authentication. The only possibility is to allow access to any URL by default. The following is a configuration that works:

http.authorizeHttpRequests
.requestMatchers("/content/**").hasRole("USER")
.requestMatchers("/admin/**").hasRole("SUPERADMIN")
.requestMatchers("/**").permitAll()

But that is not what I really want because this config gives access to any URL by default. What I want is to protect any URL and only give access to the login page, something like this:

http.authorizeHttpRequests
.requestMatchers("/login**").permitAll()
.requestMatchers("/resources/**").permitAll()
.requestMatchers("/admin/**").hasRole("SUPERADMIN")
.requestMatchers("/**").hasRole("USER")

But this does not work any more : Spring considers the login page to be protected. Therefore, on login it generates a loop of redirect to the login page.

I have tried different pattenrs : "/login*", "/login**", "/login.html" (the actual login URL), but it does not work unless I give default access to all URL.

Below is the complete SecurityFilterChain that I am currently using.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

// De-activate XSS protection
http.headers().xssProtection().disable();
http.httpBasic().disable();
http.authorizeHttpRequests()
    .requestMatchers("/content/**").hasRole("USER")
    .requestMatchers("/admin/**").hasRole("SUPERADMIN")
    .requestMatchers("/**").permitAll()
    .and()
    .formLogin()
    .successHandler(customLoginSuccessHandler)
    .failureHandler(customAuthenticationFailureHandle).loginPage("/login.html")
    .usernameParameter("username")//
    .passwordParameter("password")//
    .and().logout().logoutSuccessUrl("/login.html")//
    .and()
    .exceptionHandling().accessDeniedHandler(accessDeniedHandler())//
    .and().rememberMe().tokenRepository(persistentTokenRepository())//
    .tokenValiditySeconds(1209600)// 2 weeks
    .alwaysRemember(true).useSecureCookie(true).and().csrf();

    http.securityContext((securityContext) -> securityContext.requireExplicitSave(true));

    return http.build();
}


来源: stackexchange

问:
Append Copied Cell at specific index into table - Apps script | Google Docs
I have two tables with same no of columns and rows.

I want to copy 1st cell (in first row)  from second table and paste it into the first cell (in first row) in 1st table. I tried appending the cell but it appends to the end of row 1 in table 1 and don't at start. I want to copy other cells too from 2nd table and replace them with the ones in 1st table but appending cell method don't allow me to insert cells in first table at specific index in a row.

I can try copying text from cell of 2nd table to cell of table 1 because i have specific formatting that losts when i tried copying. I want to copy all content along with formatting from a cell. I need help to do this.

My script:

```<code>function myFunction() {

  var doc = DocumentApp.openById(my_doc_id);//copy.getId());
var body = doc.getBody();
var tables = body.getTables()

var c1 = tables[1].getRow(0).getCell(0).copy();
tables[0].getRow(0).appendTableCell(c1);

}
</code>```

screenshot

I tried copying text from cell of 2nd table to cell of table 1 because i have specific formatting that losts when i tried copying. I want to copy all content along with formatting from a cell. I need help to do this.

Please see the screenshot attached. I have two tables: (1) 1st table with checklist items (unchecked boxes). (2) 2nd table with checklist items (checked boxes). 2nd table is exact copy of 1st but just the boxes are checked. Now, if i want to tick a any checkbox in table 1, then i want to simply copy that cell from table 2 and paste it into table 1.

ContentLicense: CC BY-SA 4.0

Body:
I have two tables with same no of columns and rows.

I want to copy 1st cell (in first row)  from second table and paste it into the first cell (in first row) in 1st table. I tried appending the cell but it appends to the end of row 1 in table 1 and don't at start. I want to copy other cells too from 2nd table and replace them with the ones in 1st table but appending cell method don't allow me to insert cells in first table at specific index in a row.

I can try copying text from cell of 2nd table to cell of table 1 because i have specific formatting that losts when i tried copying. I want to copy all content along with formatting from a cell. I need help to do this.

My script:

function myFunction() {

  var doc = DocumentApp.openById(my_doc_id);//copy.getId());
var body = doc.getBody();
var tables = body.getTables()

var c1 = tables[1].getRow(0).getCell(0).copy();
tables[0].getRow(0).appendTableCell(c1);

}

screenshot

I tried copying text from cell of 2nd table to cell of table 1 because i have specific formatting that losts when i tried copying. I want to copy all content along with formatting from a cell. I need help to do this.

Please see the screenshot attached. I have two tables: (1) 1st table with checklist items (unchecked boxes). (2) 2nd table with checklist items (checked boxes). 2nd table is exact copy of 1st but just the boxes are checked. Now, if i want to tick a any checkbox in table 1, then i want to simply copy that cell from table 2 and paste it into table 1.


问:
Unable to edit existing Nvidia profile settings of an existing application using NvAPIWrapper
I am using the C# NvAPIWrapper and I am currently trying to modify a driver setting in a game's profile as shown in this code:

```<code>// create a new session
var session = NvAPIWrapper.DRS.DriverSettingsSession.CreateAndLoad();
// edit a profile (all though I want to edit the existing profile called Minecraft, not create a new profile)
var profile = NvAPIWrapper.DRS.DriverSettingsProfile.CreateProfile(session, "Minecraft");
// create the minecraft application (I don't want to create a new application, just edit an existing one)
var application = NvAPIWrapper.DRS.ProfileApplication.CreateApplication(profile, "Minecraft.Windows.exe");
// 0X00DE429A = Hex Setting ID of Raytracing - (DXR), set it to 0x0 (false)
application.Profile.SetSetting(0X00DE429A, 0x00000000);
// save and clear resources
application.Profile.Session.Save();
session.Dispose();
</code>```

As you can see my code does not do the correct functions, because I searched the docs and source code and could not find any obvious functions or ways to edit an existing applications existing profile. I could only find ways to create new profiles for new applications, which is not what I want.

Body:
I am using the C# NvAPIWrapper and I am currently trying to modify a driver setting in a game's profile as shown in this code:

// create a new session
var session = NvAPIWrapper.DRS.DriverSettingsSession.CreateAndLoad();
// edit a profile (all though I want to edit the existing profile called Minecraft, not create a new profile)
var profile = NvAPIWrapper.DRS.DriverSettingsProfile.CreateProfile(session, "Minecraft");
// create the minecraft application (I don't want to create a new application, just edit an existing one)
var application = NvAPIWrapper.DRS.ProfileApplication.CreateApplication(profile, "Minecraft.Windows.exe");
// 0X00DE429A = Hex Setting ID of Raytracing - (DXR), set it to 0x0 (false)
application.Profile.SetSetting(0X00DE429A, 0x00000000);
// save and clear resources
application.Profile.Session.Save();
session.Dispose();

As you can see my code does not do the correct functions, because I searched the docs and source code and could not find any obvious functions or ways to edit an existing applications existing profile. I could only find ways to create new profiles for new applications, which is not what I want.


问:
Virtual machine same session using different account
How I going to connect to virtual machine using different account but with same session with admin. Right now I can login to virtual machine using AAD account but cannot see the same session. Thank you.</p>


问:
Getting error while running goanalysis_metalinter
I am getting the following error when commitlint is enabled for go project, specifically for goanalysis_metalinter package

```<code>bodyclose: failed prerequisites: analysis skipped: errors in package: [/Users/me/Work/go-template/project/svc/pkg/config/config.go:5:2: could not import os (/usr/local/go/src/os/dir.go:8:2: could not import io/fs (/usr/local/go/src/io/fs/fs.go:11:2: could not import internal/oserror
</code>```

Body:
I am getting the following error when commitlint is enabled for go project, specifically for goanalysis_metalinter package

bodyclose: failed prerequisites: analysis skipped: errors in package: [/Users/me/Work/go-template/project/svc/pkg/config/config.go:5:2: could not import os (/usr/local/go/src/os/dir.go:8:2: could not import io/fs (/usr/local/go/src/io/fs/fs.go:11:2: could not import internal/oserror


问:
using nvidia tacotron2 repository
I am using this repository (https://github.com/NVIDIA/tacotron2).

while running this training command (python train.py --output_directory=outdir --log_directory=logdir)

i am getting error(AttributeError: module 'sklearn.metrics.dist_metrics' has no attribute 'DistanceMetric32').
Can anyone guide me?
I am using ubuntu 22.04

I use this command(pip install -U scikit-learn) to update sklearn but it doesnot work

Title: using nvidia tacotron2 repository


问:
How to call stored procedure from SQL Server using Codeigniter
I've been trying to call stored procedure 'sp_ftcSubdiv' from the database 'land'. The Stored Procedure 'sp_ftcSubdiv' takes four parameters - 'Surv', 'dist', 'teh', 'vill'. But, Codeigniter shows a database error.

My Controller

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

    public function __construct()
    {
    parent::__construct();
        $this->load->model('Home_m');
    }

  public function fetchsp() {
    $Surv = "114";
    $dist = "01";
    $teh = "05";
    $vill = "134";
    $data = array(
            'Surv' => $Surv,
            'dist' => $dist,
            'teh' => $teh,
            'vill' => $vill,
        );

    $result = $this->Home_m->executesp($data);
    echo $result;
    }
}
</code>```

My model

```<code><?php
class Home_m extends CI_Model {
public function executesp($data) {
      try {
        $this->db->reconnect();
        $sql = "CALL sp_ftcSubdiv(?, ?, ?, ?)";
        $result = $this->db->query($sql, $data); // $data includes 4 param and binding & query to db
        $this->db->close();

      } catch (Exception $e) {
          echo $e->getMessage();
      }
      return $result;
    }
}
</code>```

Stored Procedure

```<code>USE [land]
GO
/****** Object:  StoredProcedure [dbo].[sp_ftcSubdiv]    Script Date: 12/27/2022 12:07:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE   [dbo].[sp_ftcSubdiv]
@p_Surv char(16),
@p_dist char(2),
@p_teh char(2),
@vill char(3)

AS
BEGIN

  -- routine body goes here, e.g.

select distinct subdiv from link_table
where dist_code=@p_dist and teh=@p_teh and vill=@vill and
surv= @p_Surv and subdiv<>'' order by subdiv

END
</code>```

The Error -
Error Number: 42000/102

[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near '114'.

CALL sp_ftcSubdiv('114', '01', '05', '134')

Body:
I've been trying to call stored procedure 'sp_ftcSubdiv' from the database 'land'. The Stored Procedure 'sp_ftcSubdiv' takes four parameters - 'Surv', 'dist', 'teh', 'vill'. But, Codeigniter shows a database error.

My Controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

    public function __construct()
    {
    parent::__construct();
        $this->load->model('Home_m');
    }

  public function fetchsp() {
    $Surv = "114";
    $dist = "01";
    $teh = "05";
    $vill = "134";
    $data = array(
            'Surv' => $Surv,
            'dist' => $dist,
            'teh' => $teh,
            'vill' => $vill,
        );

    $result = $this->Home_m->executesp($data);
    echo $result;
    }
}

My model

<?php
class Home_m extends CI_Model {
public function executesp($data) {
      try {
        $this->db->reconnect();
        $sql = "CALL sp_ftcSubdiv(?, ?, ?, ?)";
        $result = $this->db->query($sql, $data); // $data includes 4 param and binding & query to db
        $this->db->close();

      } catch (Exception $e) {
          echo $e->getMessage();
      }
      return $result;
    }
}

Stored Procedure

USE [land]
GO
/****** Object:  StoredProcedure [dbo].[sp_ftcSubdiv]    Script Date: 12/27/2022 12:07:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE   [dbo].[sp_ftcSubdiv]
@p_Surv char(16),
@p_dist char(2),
@p_teh char(2),
@vill char(3)

AS
BEGIN

  -- routine body goes here, e.g.

select distinct subdiv from link_table
where dist_code=@p_dist and teh=@p_teh and vill=@vill and
surv= @p_Surv and subdiv<>'' order by subdiv

END

The Error -
Error Number: 42000/102

[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near '114'.

CALL sp_ftcSubdiv('114', '01', '05', '134')


问:
Troubleshooting k8s readiness probe failure
I'm trying to run my django rest framework application in k8s environment but readiness probe fails. I wonder how to get what is wrong.

When I look at pod logs the app seems to be running. It has unapplied migrations, but it is ok:

```<code>C:\Users\user>kubectl logs test-bbdccbc76-8cwg9
Watching for file changes with StatReloader
Performing system checks...

Server initialized for gevent.
System check identified some issues:

WARNINGS:
?: (staticfiles.W004) The directory '/app/staticfiles' in the STATICFILES_DIRS setting does not exist.

System check identified 1 issue (0 silenced).

You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth
Run 'python manage.py migrate' to apply them.
December 27, 2022 - 06:13:28
Django version 4.1.2, using settings 'test.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
</code>```

Here is describe pod output:

```<code>C:\Users\user>kubectl describe pod test-bbdccbc76-8cwg9
Name:                 test-bbdccbc76-8cwg9
Namespace:            test
Priority:             2000
Priority Class Name:  default
Service Account:      default
Node:                 sd2-k8s-stg-n05/10.216.14.52
Start Time:           Tue, 27 Dec 2022 11:11:14 +0500
Labels:               app=test
                      pod-template-hash=bbdccbc76
Annotations:          checksum/config: f0ee0887d3fd078979831f04d13ade8759ef8a4ee9aad23830c5909300e322b4
                      cni.projectcalico.org/containerID: ac4c0c57c0a3baa1c15a78aedb36e3e1890f8b9859547807b1e3587835792efb
                      cni.projectcalico.org/podIP: 10.233.110.84/32
                      cni.projectcalico.org/podIPs: 10.233.110.84/32
                      container.apparmor.security.beta.kubernetes.io/test: runtime/default
                      kubernetes.io/psp: restricted
                      seccomp.security.alpha.kubernetes.io/pod: runtime/default
Status:               Running
IP:                   10.233.110.84
IPs:
  IP:           10.233.110.84
Controlled By:  ReplicaSet/test-bbdccbc76
Containers:
  test:
    Container ID:  containerd://26e3234ba31c09d6d62e3efb999634cb64d26d6ce2e8e734a26104d62b6f2f5f
    Image:         registry/library/test:latest
    Image ID:      registry/library/test-@sha256:12345678b16eb2c90324916756846d5dfa557198bd4aeed9e790db677702b1
    Port:          8000/TCP
    Host Port:     0/TCP
    Command:
      python
      manage.py
      runserver
    State:          Running
      Started:      Tue, 27 Dec 2022 11:11:15 +0500
    Ready:          False
    Restart Count:  0
    Limits:
      cpu:                500m
      ephemeral-storage:  500Mi
      memory:             500Mi
    Requests:
      cpu:                500m
      ephemeral-storage:  500Mi
      memory:             500M
    Liveness:             http-get http://:8000/healthz delay=30s timeout=1s period=10s #success=1 #failure=3
    Readiness:            http-get http://:8000/healthz delay=30s timeout=1s period=10s #success=1 #failure=3
    Environment Variables from:
      test-configmap  ConfigMap  Optional: false
    Environment:
      CONNECTION_STRING:     mongodb://xxx:yyy@zzz:27017
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-tpstr (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  kube-api-access-tpstr:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   Burstable
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s

Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  79s                default-scheduler  Successfully assigned test/test-bbdccbc76-8cwg9 to xx-k8s-xx
  Normal   Pulling    78s                kubelet            Pulling image "registry/library/test:latest"
  Normal   Pulled     78s                kubelet            Successfully pulled image "registry/library/test:latest" in 57.066835ms
  Normal   Created    78s                kubelet            Created container test
  Normal   Started    78s                kubelet            Started container test
  Warning  Unhealthy  29s (x2 over 39s)  kubelet            Readiness probe failed: Get "http://10.233.110.84:8000/healthz": dial tcp 10.233.110.84:8000: connect: connection refused
  Warning  Unhealthy  29s (x2 over 39s)  kubelet            Liveness probe failed: Get "http://10.233.110.84:8000/healthz": dial tcp 10.233.110.84:8000: connect: connection refused
</code>```

Here's service:

```<code>C:\Users\user>kubectl describe service test-service
Name:                     test-service
Namespace:                test
Labels:                   app=test
                          app.kubernetes.io/managed-by=Helm
                          app.kubernetes.io/version=0.1.0
                          helm.sh/chart=my-helm-char-1.0.0
Annotations:              meta.helm.sh/release-name: test
                          meta.helm.sh/release-namespace: test
Selector:                 app=test
Type:                     NodePort
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.233.53.185
IPs:                      10.233.53.185
Port:                     api-port  8000/TCP
TargetPort:               api-port/TCP
NodePort:                 api-port  32426/TCP
Endpoints:
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>
</code>```

Body:
I'm trying to run my django rest framework application in k8s environment but readiness probe fails. I wonder how to get what is wrong.

When I look at pod logs the app seems to be running. It has unapplied migrations, but it is ok:

C:\Users\user>kubectl logs test-bbdccbc76-8cwg9
Watching for file changes with StatReloader
Performing system checks...

Server initialized for gevent.
System check identified some issues:

WARNINGS:
?: (staticfiles.W004) The directory '/app/staticfiles' in the STATICFILES_DIRS setting does not exist.

System check identified 1 issue (0 silenced).

You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth
Run 'python manage.py migrate' to apply them.
December 27, 2022 - 06:13:28
Django version 4.1.2, using settings 'test.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Here is describe pod output:

C:\Users\user>kubectl describe pod test-bbdccbc76-8cwg9
Name:                 test-bbdccbc76-8cwg9
Namespace:            test
Priority:             2000
Priority Class Name:  default
Service Account:      default
Node:                 sd2-k8s-stg-n05/10.216.14.52
Start Time:           Tue, 27 Dec 2022 11:11:14 +0500
Labels:               app=test
                      pod-template-hash=bbdccbc76
Annotations:          checksum/config: f0ee0887d3fd078979831f04d13ade8759ef8a4ee9aad23830c5909300e322b4
                      cni.projectcalico.org/containerID: ac4c0c57c0a3baa1c15a78aedb36e3e1890f8b9859547807b1e3587835792efb
                      cni.projectcalico.org/podIP: 10.233.110.84/32
                      cni.projectcalico.org/podIPs: 10.233.110.84/32
                      container.apparmor.security.beta.kubernetes.io/test: runtime/default
                      kubernetes.io/psp: restricted
                      seccomp.security.alpha.kubernetes.io/pod: runtime/default
Status:               Running
IP:                   10.233.110.84
IPs:
  IP:           10.233.110.84
Controlled By:  ReplicaSet/test-bbdccbc76
Containers:
  test:
    Container ID:  containerd://26e3234ba31c09d6d62e3efb999634cb64d26d6ce2e8e734a26104d62b6f2f5f
    Image:         registry/library/test:latest
    Image ID:      registry/library/test-@sha256:12345678b16eb2c90324916756846d5dfa557198bd4aeed9e790db677702b1
    Port:          8000/TCP
    Host Port:     0/TCP
    Command:
      python
      manage.py
      runserver
    State:          Running
      Started:      Tue, 27 Dec 2022 11:11:15 +0500
    Ready:          False
    Restart Count:  0
    Limits:
      cpu:                500m
      ephemeral-storage:  500Mi
      memory:             500Mi
    Requests:
      cpu:                500m
      ephemeral-storage:  500Mi
      memory:             500M
    Liveness:             http-get http://:8000/healthz delay=30s timeout=1s period=10s #success=1 #failure=3
    Readiness:            http-get http://:8000/healthz delay=30s timeout=1s period=10s #success=1 #failure=3
    Environment Variables from:
      test-configmap  ConfigMap  Optional: false
    Environment:
      CONNECTION_STRING:     mongodb://xxx:yyy@zzz:27017
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-tpstr (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  kube-api-access-tpstr:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   Burstable
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s

Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  79s                default-scheduler  Successfully assigned test/test-bbdccbc76-8cwg9 to xx-k8s-xx
  Normal   Pulling    78s                kubelet            Pulling image "registry/library/test:latest"
  Normal   Pulled     78s                kubelet            Successfully pulled image "registry/library/test:latest" in 57.066835ms
  Normal   Created    78s                kubelet            Created container test
  Normal   Started    78s                kubelet            Started container test
  Warning  Unhealthy  29s (x2 over 39s)  kubelet            Readiness probe failed: Get "http://10.233.110.84:8000/healthz": dial tcp 10.233.110.84:8000: connect: connection refused
  Warning  Unhealthy  29s (x2 over 39s)  kubelet            Liveness probe failed: Get "http://10.233.110.84:8000/healthz": dial tcp 10.233.110.84:8000: connect: connection refused

Here's service:

C:\Users\user>kubectl describe service test-service
Name:                     test-service
Namespace:                test
Labels:                   app=test
                          app.kubernetes.io/managed-by=Helm
                          app.kubernetes.io/version=0.1.0
                          helm.sh/chart=my-helm-char-1.0.0
Annotations:              meta.helm.sh/release-name: test
                          meta.helm.sh/release-namespace: test
Selector:                 app=test
Type:                     NodePort
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.233.53.185
IPs:                      10.233.53.185
Port:                     api-port  8000/TCP
TargetPort:               api-port/TCP
NodePort:                 api-port  32426/TCP
Endpoints:
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>


问:
directory access is forbidden
the project is in php codeigniter3

after uploading the assets folder in the live server the webapp is giving error "directory access forbiden"

here are 3 .htaccess files i have for the project.
this one is for the main folder structure

```<code>DirectoryIndex index.php
RewriteEngine on

RewriteCond $1 !^(index\.php|(.*)\.swf|fonts|images|css|less|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?$1 [L,QSA]
</code>```

/////////////////////////-----2-----///////////////////////////

this one is inside the applications folder

```<code><IfModule authz_core_module>
Require all granted
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
</code>```

/////////////////////////-----3-----///////////////////////////
this one is inside the system folder

```<code><IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
</code>```

Title: directory access is forbidden

Body:
the project is in php codeigniter3

after uploading the assets folder in the live server the webapp is giving error "directory access forbiden"

here are 3 .htaccess files i have for the project.
this one is for the main folder structure

DirectoryIndex index.php
RewriteEngine on

RewriteCond $1 !^(index\.php|(.*)\.swf|fonts|images|css|less|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?$1 [L,QSA]

/////////////////////////-----2-----///////////////////////////

this one is inside the applications folder

<IfModule authz_core_module>
Require all granted
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>

/////////////////////////-----3-----///////////////////////////
this one is inside the system folder

<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>


问:
getting html instead of csv data using url link via python
I am trying to download a csv file from a salesforce report using python 3.7. I know one can use the API but unfortunately I do not have access to the API at the moment.

I have the following code:

```<code>import pandas as pd
data = pd.read_csv("https://site.salesforce.com/00O1H000008Fg49?csv=1&exp=1&enc=UTF-8&isdtp=p1")
data.head()
</code>```

and I get the following result:

```<code>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
0   <html>
1   <head>
2   <meta HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
3   <script src="/jslibrary/1644529820240/ui-sfdc-...
4   <script>
</code>```

How can I get the csv data instead of the HTML? when I paste the URL in a browser, the csv file is automatically downloaded and when I open the file, the data is there. How can I get the data in a pandas dataframe using the url link?

Body:
I am trying to download a csv file from a salesforce report using python 3.7. I know one can use the API but unfortunately I do not have access to the API at the moment.

I have the following code:

import pandas as pd
data = pd.read_csv("https://site.salesforce.com/00O1H000008Fg49?csv=1&exp=1&enc=UTF-8&isdtp=p1")
data.head()

and I get the following result:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
0
1
2   <meta HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
3


问:
How do I add a custom method to grails 5.2.4 service interface?
After using the grails create-all command to generate a service interface, I would like to add some other methods that would require transactional scope for database updates. I'm made to understand that with grails 5 above, the ideal place to do it is in the services. But if I change the type from interface to class, seems like I need to implement all the other method calls, and if I continue to use interface, I can't add a body to the method. Haven't been able to find adequate reference for this yet to understand the full scope of what I need to do.

Thank you.


问:
VSCODE reset only horizontal group sizes
i dont want folded editor to expand when it focused. so i found shortcut "View: Reset Editor Group Sizes", it works similarly. but i want to reset only editors in same horizontal group.

"View: Reset Editor Group Sizes" works like vertical, horizontal sashes double click function at the same time, but i want just vertical sashes double click function. is there any other solution or shortcut?

that shortcut works like double click border in blue highlight

but i want to work like double click in blue highlight border in this picture

i tried other solution like minimum editor size setting or disabled expand editor when it focused, but nothing work like what i want, and nothing supported in vscode


问:
Laravel 500 error when deploying to Elastic Beanstalk (AWS)
Deployed my website to AWS Elastic Beanstalk, getting 500 server error message

This only happends when I cache the config. (php artisan config:cache). It works perfectly when I don't cache the config

This is config file when deploying to AWS-

```<code>option_settings:
-
    namespace: aws:elasticbeanstalk:application:environment
    option_name: COMPOSER_HOME
    value: /root

-
    namespace: aws:elasticbeanstalk:container:php:phpini
    option_name: document_root
    value: /public

container_commands:
    01-no_dev:
        command: "composer.phar install --optimize-autoloader --no-dev"
        cwd: "/var/app/staging"
    02-storage_permission:
        command: "chmod -R 755 ./storage"
    03-bootstrap_permission:
        command: "chmod -R 755 ./bootstrap/cache/"
    05-view_cache:
        command: "php artisan view:cache"
    06-config_cache:
        command: "php artisan config:cache"
    07-route_cache:
        command: "php artisan route:cache"
    08-migrate_db:
        command: "php artisan migrate --force"
    09-seed_db:
        command: "php artisan db:seed --force"
    10-npm:
        command: "sudo npm install"
    11-npm_dependencies:
        command: "sudo npm run build"

files:
    /opt/elasticbeanstalk/tasks/taillogs.d/laravel-logs.conf:
        content: /var/app/current/storage/logs/laravel.log
        group: root
        mode: "000755"
        owner: root
</code>```

This is my nginx config-

```<code>location / {
try_files $uri $uri/ /index.php?$query_string;
gzip_static on;
}
</code>```

If ssh into the instance and execute the "php artisan optimize:clear" (clearing the cache), the issues is solved. But I an unable to get it working with caching the config.

Body:
Deployed my website to AWS Elastic Beanstalk, getting 500 server error message

This only happends when I cache the config. (php artisan config:cache). It works perfectly when I don't cache the config

This is config file when deploying to AWS-

option_settings:
-
    namespace: aws:elasticbeanstalk:application:environment
    option_name: COMPOSER_HOME
    value: /root

-
    namespace: aws:elasticbeanstalk:container:php:phpini
    option_name: document_root
    value: /public

container_commands:
    01-no_dev:
        command: "composer.phar install --optimize-autoloader --no-dev"
        cwd: "/var/app/staging"
    02-storage_permission:
        command: "chmod -R 755 ./storage"
    03-bootstrap_permission:
        command: "chmod -R 755 ./bootstrap/cache/"
    05-view_cache:
        command: "php artisan view:cache"
    06-config_cache:
        command: "php artisan config:cache"
    07-route_cache:
        command: "php artisan route:cache"
    08-migrate_db:
        command: "php artisan migrate --force"
    09-seed_db:
        command: "php artisan db:seed --force"
    10-npm:
        command: "sudo npm install"
    11-npm_dependencies:
        command: "sudo npm run build"

files:
    /opt/elasticbeanstalk/tasks/taillogs.d/laravel-logs.conf:
        content: /var/app/current/storage/logs/laravel.log
        group: root
        mode: "000755"
        owner: root

This is my nginx config-

location / {
try_files $uri $uri/ /index.php?$query_string;
gzip_static on;
}

If ssh into the instance and execute the "php artisan optimize:clear" (clearing the cache), the issues is solved. But I an unable to get it working with caching the config.


问:
Spring cloud stream StreamBridge with GCP Pubsub Binder
I use spring cloud stream in my project for publishing event to multiple kafka cluster by StreamBridge and it work well. Now i need to integrate with multi google pubsub (different projectId, credentials),i found that

```<code><groupId>com.google.cloud</groupId>
<artifactId>spring-cloud-gcp-pubsub-stream-binder</artifactId>
</code>```

but it not work with streamBridge cause by

```<code>No qualifying bean of type 'org.springframework.cloud.stream.binder.Binder<?, ?, ?>' available
</code>```

note:

spring boot 2.7.3

spring-cloud-gcp v3.3.0

here is my sample:

#init binder

```<code>
spring.cloud.stream.binders.pubsub-gcp.type=pubsub
spring.cloud.stream.binders.pubsub-gcp.environment.spring.cloud.stream.gcp.pubsub.project-id=
spring.cloud.stream.binders.pubsub-gcp.environment.spring.cloud.stream.gcp.pubsub.credentials.location=
</code>```

#define function

```<code>
spring.cloud.stream.output-bindings=update

spring.cloud.stream.bindings.update-out-0.binder=pubsub-gcp
spring.cloud.stream.bindings.update-out-0.destination=abc
</code>```

#producer code

```<code>
streamBridge.send("update-out-0", data)
</code>```

Body:
I use spring cloud stream in my project for publishing event to multiple kafka cluster by StreamBridge and it work well. Now i need to integrate with multi google pubsub (different projectId, credentials),i found that

<groupId>com.google.cloud</groupId>
<artifactId>spring-cloud-gcp-pubsub-stream-binder</artifactId>

but it not work with streamBridge cause by

No qualifying bean of type 'org.springframework.cloud.stream.binder.Binder<?, ?, ?>' available

note:

spring boot 2.7.3

spring-cloud-gcp v3.3.0

here is my sample:

#init binder

spring.cloud.stream.binders.pubsub-gcp.type=pubsub
spring.cloud.stream.binders.pubsub-gcp.environment.spring.cloud.stream.gcp.pubsub.project-id=
spring.cloud.stream.binders.pubsub-gcp.environment.spring.cloud.stream.gcp.pubsub.credentials.location=

#define function

spring.cloud.stream.output-bindings=update

spring.cloud.stream.bindings.update-out-0.binder=pubsub-gcp
spring.cloud.stream.bindings.update-out-0.destination=abc

#producer code

streamBridge.send("update-out-0", data)


问:
In flutter I wants to navigate when tapped on Material Button but its not working for below code is there anything wrong with response I am getting?
I am getting this type of response when hit the API:{"token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ2YWlzaG5hdmkuYXRkb2NodWJAZ21haWwuY29tIiwiaXNzIjoidGVjaC10cmFpbCIsImlhdCI6MTY3MjEyMjc2NiwiZXhwIjoxMjYwODgxMjI3NjZ9.a7Lq9v0fzMfwk5xCXuIfY4sh9Dls2Q0WksXtloui3OsoDwZBQX1qR6yJMz8nUS634POFETNxisHXTu6ObosEow"}
Below is my code where I am checking if the response is not null then navigate to another page but its not working is there anything wrong with response type I am getting?</p>
```<code>Center(
                            child: MaterialButton(
                                height:
                                    MediaQuery.of(context).size.height * 0.06,
                                child: AutoSizeText("Login",
                                    textAlign: TextAlign.center,
                                    style: style.copyWith(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      fontSize: multiplier * unitHeightValue,
                                    )),
                                minWidth:
                                    MediaQuery.of(context).size.width * 0.5,
                                elevation: 3.0,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(30.0))),
                                color: Color.fromARGB(255, 253, 153, 33),
                                onPressed: () async {
                                  // _formKey.currentState?.validate();
                                  // final isValidForm =
                                  //     _formKey.currentState!.validate();
                                  // if (isValidForm) {
                                  final String email = emailController.text;

                                  final String pass = pwController.text;
                                  String pid = this.playerid;
                                  print(
                                      'The player id from login............${pid}');
                                  List<UserLogin> res =
                                      await LoginController.login(
                                          email, pass, pid);
                                  SharedPreferences prefs =
                                      await SharedPreferences.getInstance();
                                  prefs.setString(
                                      'email', emailController.text);
                                  prefs.setString('authToken', res[0].token);
                                  // UserLogin resp = UserLogin.fromJson(
                                  //     jsonDecode(res[0].token));
                                  print(
                                      'Auth Token.............${res[0].token}');
                                  // prefs.setString('username', res[0].userName);
                                  // this.uname = res[0].userName;
                                  // final String username = this.uname;

                                  String authToken = jsonEncode(res[0]);

                                  // ignore: unnecessary_null_comparison
                                  if (authToken != null) {
                                    Navigator.of(context)
                                        .push(MaterialPageRoute(
                                            builder: (_) => homePageAdmin(
                                                  this.playerid,
                                                  'Vaishnavi',
                                                )));
                                  }

                                  print(
                                      'Auth Token from login..... ${authToken}');

                                  // role == res[0].role;
                                  // print(res[0].role);

                                  // }
                                }),
                          )
</code>```

Body:
I am getting this type of response when hit the API:{"token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ2YWlzaG5hdmkuYXRkb2NodWJAZ21haWwuY29tIiwiaXNzIjoidGVjaC10cmFpbCIsImlhdCI6MTY3MjEyMjc2NiwiZXhwIjoxMjYwODgxMjI3NjZ9.a7Lq9v0fzMfwk5xCXuIfY4sh9Dls2Q0WksXtloui3OsoDwZBQX1qR6yJMz8nUS634POFETNxisHXTu6ObosEow"}
Below is my code where I am checking if the response is not null then navigate to another page but its not working is there anything wrong with response type I am getting?

Center(
                            child: MaterialButton(
                                height:
                                    MediaQuery.of(context).size.height * 0.06,
                                child: AutoSizeText("Login",
                                    textAlign: TextAlign.center,
                                    style: style.copyWith(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      fontSize: multiplier * unitHeightValue,
                                    )),
                                minWidth:
                                    MediaQuery.of(context).size.width * 0.5,
                                elevation: 3.0,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(30.0))),
                                color: Color.fromARGB(255, 253, 153, 33),
                                onPressed: () async {
                                  // _formKey.currentState?.validate();
                                  // final isValidForm =
                                  //     _formKey.currentState!.validate();
                                  // if (isValidForm) {
                                  final String email = emailController.text;

                                  final String pass = pwController.text;
                                  String pid = this.playerid;
                                  print(
                                      'The player id from login............${pid}');
                                  List<UserLogin> res =
                                      await LoginController.login(
                                          email, pass, pid);
                                  SharedPreferences prefs =
                                      await SharedPreferences.getInstance();
                                  prefs.setString(
                                      'email', emailController.text);
                                  prefs.setString('authToken', res[0].token);
                                  // UserLogin resp = UserLogin.fromJson(
                                  //     jsonDecode(res[0].token));
                                  print(
                                      'Auth Token.............${res[0].token}');
                                  // prefs.setString('username', res[0].userName);
                                  // this.uname = res[0].userName;
                                  // final String username = this.uname;

                                  String authToken = jsonEncode(res[0]);

                                  // ignore: unnecessary_null_comparison
                                  if (authToken != null) {
                                    Navigator.of(context)
                                        .push(MaterialPageRoute(
                                            builder: (_) => homePageAdmin(
                                                  this.playerid,
                                                  'Vaishnavi',
                                                )));
                                  }

                                  print(
                                      'Auth Token from login..... ${authToken}');

                                  // role == res[0].role;
                                  // print(res[0].role);

                                  // }
                                }),
                          )


问:
Altering Android offline battery charging display (playlpm)
I'm using a ViewSonic Viewpad 7 Android tablet for an application where I'd like the tablet to power on whenever it has been turned off and power is then provided. A bit of Googling revealed that I could alter the executable /system/bin/playlpm (apparently the program responsible for showing the battery charging display when the device is off, but plugged in) to contain a simple shell script like so:

```<code>#!/system/bin/sh
/system/bin/reboot
</code>```

In any event, the playlpm executable seems only to be present on Samsung devices, and not on anything else. Does anyone know that the more widely-used executable or other means used to display the battery indicator would be (and how it could be modified)?

ContentLicense: CC BY-SA 3.0

Body:
I'm using a ViewSonic Viewpad 7 Android tablet for an application where I'd like the tablet to power on whenever it has been turned off and power is then provided. A bit of Googling revealed that I could alter the executable /system/bin/playlpm (apparently the program responsible for showing the battery charging display when the device is off, but plugged in) to contain a simple shell script like so:

#!/system/bin/sh
/system/bin/reboot

In any event, the playlpm executable seems only to be present on Samsung devices, and not on anything else. Does anyone know that the more widely-used executable or other means used to display the battery indicator would be (and how it could be modified)?


问:
How to use the artifactory dependency jars in the custom defined gradle tasks in classpath
```<code>plugins {
   }

   apply plugin: 'java'

   task compileJC(type: JavaCompile) {
    source = fileTree(dir: 'JC', include: '**/*.java')
    destinationDir = file('build/JCims/classes/main')
    classpath = files('/opt/mks/om/src/AKH/JC6/JC/run/ak_lib/activation.jar')
   }
</code>```

In the above code, I am using jars in the classpath from the local folder. Now I want to add the classpath from the anyone of the repository and use it as a dependency. I am using gradle version 4.4.

Any help can be appreciated.

Thanks in Advance.

In the above code, I am using jars in the classpath from the local folder. Now I want to add the classpath from the anyone of the repository and use it as a dependency. I am using gradle version 4.4.

Need to add the classpath jars from the repository and not from the local path.

Body:
plugins {
   }

   apply plugin: 'java'

   task compileJC(type: JavaCompile) {
    source = fileTree(dir: 'JC', include: '**/*.java')
    destinationDir = file('build/JCims/classes/main')
    classpath = files('/opt/mks/om/src/AKH/JC6/JC/run/ak_lib/activation.jar')
   }

In the above code, I am using jars in the classpath from the local folder. Now I want to add the classpath from the anyone of the repository and use it as a dependency. I am using gradle version 4.4.

Any help can be appreciated.

Thanks in Advance.

In the above code, I am using jars in the classpath from the local folder. Now I want to add the classpath from the anyone of the repository and use it as a dependency. I am using gradle version 4.4.

Need to add the classpath jars from the repository and not from the local path.


问:
Twilio : Make a call using Connect App | Twilio.Device Error: ConnectionError (53000)
I am trying to make a call using Twilio Connected App. I have

Registered a new connect app

Authorized the connect(step 1) with my account

Bought/provisioned a new incoming phone number using connected app (step 1).

Using python helper library, I am trying to call a number. But i keep getting error [ Twilio.Device Error: ConnectionError (53000) ].

```<code>    # sid issued by Twilio when we authorised the connect app
    account_SID = request.user.organization.twilio_sid

    # env.Twilio_SID is my API key (main) SID and env.TWILIO_SECRET is secret of the same API key
    # identity is phone number that we provisioned using the connected app
    access_token = AccessToken(account_SID,env.TWILIO_SID, env.TWILIO_SECRET, identity="+17208****")
</code>```

If I replace the account_SID with my parent account SID, the access token works. But if I use SID related to connected app, it throws this error.

What can i change to make it work?

Body:
I am trying to make a call using Twilio Connected App. I have

Registered a new connect app

Authorized the connect(step 1) with my account

Bought/provisioned a new incoming phone number using connected app (step 1).

Using python helper library, I am trying to call a number. But i keep getting error [ Twilio.Device Error: ConnectionError (53000) ].

    # sid issued by Twilio when we authorised the connect app
    account_SID = request.user.organization.twilio_sid

    # env.Twilio_SID is my API key (main) SID and env.TWILIO_SECRET is secret of the same API key
    # identity is phone number that we provisioned using the connected app
    access_token = AccessToken(account_SID,env.TWILIO_SID, env.TWILIO_SECRET, identity="+17208****")

If I replace the account_SID with my parent account SID, the access token works. But if I use SID related to connected app, it throws this error.

What can i change to make it work?


问:
How to do Database validation in Async function Nodejs(Express) API
I'm inserting user in SQl SERVER with the following code which is working fine for insertion purpose and I want to validate user that it already exist in database or not before inserting it, my function looks like:</p>
```<code>async function addUser(user) {
    try {
      let pool = await sql.connect(config);
      let addUser = await pool.request()
      .input('userName', sql.NVarChar, user.userName)
      .input('email', sql.NVarChar, user.email)
      .input('password', sql.NVarChar, user.password)

      .query(`insert into testRegistration01 (userName, password, email)
      values(@userName, @password,@email)`);

        UserAdd=addUser.recordsets;
      console.log(UserAdd,{message:"Record inserted"})
    }
    catch (err) {
      console.log(err);
    }
  }
</code>```

Body:
I'm inserting user in SQl SERVER with the following code which is working fine for insertion purpose and I want to validate user that it already exist in database or not before inserting it, my function looks like:

async function addUser(user) {
    try {
      let pool = await sql.connect(config);
      let addUser = await pool.request()
      .input('userName', sql.NVarChar, user.userName)
      .input('email', sql.NVarChar, user.email)
      .input('password', sql.NVarChar, user.password)

      .query(`insert into testRegistration01 (userName, password, email)
      values(@userName, @password,@email)`);

        UserAdd=addUser.recordsets;
      console.log(UserAdd,{message:"Record inserted"})
    }
    catch (err) {
      console.log(err);
    }
  }


问:
Apache Nifi: Monitor Files in Queue for longer duration
I have an ETL pipeline setup on Apache Nifi. It has more than 1300 processors. I need to get into each process group manually to check whether there are any files stuck in a queue. Is there any way that these queues can be monitored and notified automatically?</p>


问:
The package 'analytics-react-native' can't access a custom native module while testing in react native
analytics-react-native giving me this warning when I run test on it.

```<code>    console.warn
      The package 'sovran-react-native' doesn't seem to be linked. Make sure:

      - You have run 'pod install'
      - You rebuilt the app after installing the package
      - You are not using Expo managed workflow

</code>```

and

```<code> The package 'analytics-react-native' can't access a custom native module. Make sure:

      - You have run 'pod install'
      - You rebuilt the app after installing the package
      - You are not using Expo managed workflow
</code>```

I tried to mock it like

```<code>jest.mock('@segment/analytics-react-native', () => ({
  setup: jest.fn(),
  identify: jest.fn(),
  reset: jest.fn(),
}));
</code>```

but it gives error

Super expression must either be null or a function

What is the proper way to test it or create mock of it?

Body:
analytics-react-native giving me this warning when I run test on it.

    console.warn
      The package 'sovran-react-native' doesn't seem to be linked. Make sure:

      - You have run 'pod install'
      - You rebuilt the app after installing the package
      - You are not using Expo managed workflow

and

 The package 'analytics-react-native' can't access a custom native module. Make sure:

      - You have run 'pod install'
      - You rebuilt the app after installing the package
      - You are not using Expo managed workflow

I tried to mock it like

jest.mock('@segment/analytics-react-native', () => ({
  setup: jest.fn(),
  identify: jest.fn(),
  reset: jest.fn(),
}));

but it gives error

Super expression must either be null or a function

What is the proper way to test it or create mock of it?


问:
Publisher confirm in rabbitmq-c?
How to implement publisher confirms in rabbitmq-c? In an example written by alanxz this is the approach:

```<code>amqp_frame_t frame;
amqp_simple_wait_frame(conn, &frame);
if (frame.method == AMQP_BASIC_ACK)
{
  // Message successfully delivered
}
</code>```

https://lists.rabbitmq.com/pipermail/rabbitmq-discuss/2012-July/021338.html

However it appears that amqp_frame_t structure has no member method anymore. This is the error that I am getting:

```<code>error: ‘amqp_frame_t’ {aka ‘struct amqp_frame_t_’} has no member named ‘method’
</code>```

I looked up the documentation for amqp_frame_t, this is how the data structure is:

```<code>typedef struct amqp_frame_t_ {
  uint8_t frame_type; /* 0 means no event */
  amqp_channel_t channel;
  union {
    amqp_method_t method;
    struct {
      uint16_t class_id;
      uint64_t body_size;
      void *decoded;
    } properties;
    amqp_bytes_t body_fragment;
    struct {
      uint8_t transport_high;
      uint8_t transport_low;
      uint8_t protocol_version_major;
      uint8_t protocol_version_minor;
    } protocol_header;
  } payload;
} amqp_frame_t;
</code>```

I am trying to write a function:

```<code>void publisher_confirm(amqp_connection_state_t conn){
    amqp_frame_t frame;
    frame.frame_type == AMQP_FRAME_METHOD;
    amqp_simple_wait_frame(conn, &frame);
    //if (frame.payload.method == AMQP_BASIC_ACK)
    //Suppose we could compare some member of the method structure with some value
    {
      printf("Message successfully delivered to queue.\n");
    }
}
</code>```

However I don't know how to perform the comparison for frame.payload.method.  frame.payload.method is of the type amqp_method_t which is documented here:
http://alanxz.github.io/rabbitmq-c/docs/0.2/structamqp__method__t.html#a83e7496e9cc6d407d5798345a0c07504

Title: Publisher confirm in rabbitmq-c?

Body:
How to implement publisher confirms in rabbitmq-c? In an example written by alanxz this is the approach:

amqp_frame_t frame;
amqp_simple_wait_frame(conn, &frame);
if (frame.method == AMQP_BASIC_ACK)
{
  // Message successfully delivered
}

https://lists.rabbitmq.com/pipermail/rabbitmq-discuss/2012-July/021338.html

However it appears that amqp_frame_t structure has no member method anymore. This is the error that I am getting:

error: ‘amqp_frame_t’ {aka ‘struct amqp_frame_t_’} has no member named ‘method’

I looked up the documentation for amqp_frame_t, this is how the data structure is:

typedef struct amqp_frame_t_ {
  uint8_t frame_type; /* 0 means no event */
  amqp_channel_t channel;
  union {
    amqp_method_t method;
    struct {
      uint16_t class_id;
      uint64_t body_size;
      void *decoded;
    } properties;
    amqp_bytes_t body_fragment;
    struct {
      uint8_t transport_high;
      uint8_t transport_low;
      uint8_t protocol_version_major;
      uint8_t protocol_version_minor;
    } protocol_header;
  } payload;
} amqp_frame_t;

I am trying to write a function:

void publisher_confirm(amqp_connection_state_t conn){
    amqp_frame_t frame;
    frame.frame_type == AMQP_FRAME_METHOD;
    amqp_simple_wait_frame(conn, &frame);
    //if (frame.payload.method == AMQP_BASIC_ACK)
    //Suppose we could compare some member of the method structure with some value
    {
      printf("Message successfully delivered to queue.\n");
    }
}

However I don't know how to perform the comparison for frame.payload.method.  frame.payload.method is of the type amqp_method_t which is documented here:
http://alanxz.github.io/rabbitmq-c/docs/0.2/structamqp__method__t.html#a83e7496e9cc6d407d5798345a0c07504


问:
Exception "Unknown PrimitiveTypeKind DateTimeOffset" when save model in .Net Framework 4.8 in DB2
Came across a problem while working with DB2 from .Net Framework 4.8.

We have a Db2 for z/OS v12 database. Our database has fields with type "TIMESTAMP WITH TIME ZONE". When using ADO.NET, these fields in models are of type DateTimeOffset. When getting data from the database, there are no problems, but when saving, we get the following error:

```<code>2022-12-27 08:16:09.2273 FATAL InputManager.Program System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.EntityCommandCompilationException: An error occurred while preparing the command definition. See the inner exception for details. ---> System.InvalidOperationException: Unknown PrimitiveTypeKind DateTimeOffset
   at IBM.Data.DB2.EntityFramework.MetadataHelpers.GetDbType(PrimitiveTypeKind primitiveType, TypeUsage type)
   at IBM.Data.DB2.EntityFramework.DmlSqlGenerator.ExpressionTranslator.CreateParameter(Object value, TypeUsage type)
   at IBM.Data.DB2.EntityFramework.DmlSqlGenerator.ExpressionTranslator.Visit(DbConstantExpression expression)
   at System.Data.Entity.Core.Common.CommandTrees.DbConstantExpression.Accept(DbExpressionVisitor visitor)
   at IBM.Data.DB2.EntityFramework.DmlSqlGenerator.GenerateUpdateSql(DbUpdateCommandTree tree, SqlGenerator sqlGenerator, List`1& parameters, Boolean createParameters)
   at IBM.Data.DB2.EntityFramework.SqlGenerator.GenerateSql(DbCommandTree tree, DB2ProviderManifest manifest, List`1& parameters, CommandType& commandType, Dictionary`2& overrideColumnReturnTypes, List`1& replaceParametersWithValues, String[]& rowsToSkipAndLimit)
   at IBM.Data.DB2.EntityFramework.DB2ProviderServices.CreateCommand(DbProviderManifest manifest, DbCommandTree commandTree)
   at IBM.Data.DB2.EntityFramework.DB2ProviderServices.CreateDbCommandDefinition(DbProviderManifest manifest, DbCommandTree commandTree)
   at System.Data.Entity.Core.Common.DbProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(Dictionary`2 identifierValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<>c.<Update>b__21_0(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__153_0()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass148_0.<SaveChangesInternal>b__0()
   at IBM.Data.DB2.EntityFramework.DB2DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
</code>```

NuGet Packages installed:
EntityFramework v6.4.4;
EntityFramework.IBM.DB2 6.4.1.
Although the same error occurred on other versions.

Code example:

```<code>//Model from ADO.NET
[Table("MyModel")]
public partial class MyModel
{
    [Key]
    [Column(TypeName = "integer")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int IdMyModel { get; set; }

    [Column(TypeName = "timestz")]
    public DateTimeOffset TmCreate { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyModel>()
        .Property(e => e.TmCreate)
        .HasColumnType("timestz");
}
</code>```
```<code>//How it is used
var myModel = db.MyModel.FirstOrDefault(m => m.IdMyModel == 123); //OK
myModel.TmCreate = DateTimeOffset.Now;
db.SaveChanges(); //Error
</code>```

Sql-injection works OK.

```<code>string dateFormat = DateTimeOffset.Now.ToString("o");
string query = $"UPDATE MyDB.\"MyModel\" set \"TmCreate\" = TIMESTAMP '{dateFormat}' where \"IdMyModel \" = 123;";
db.ExecuteSqlCommand(query);
</code>```

I saw the table, but, as I understand it, it is for the version for windows, not for z/OS. Is it even possible to work with
DateTimeOffset in our situation? What are we doing wrong?

Information that may be useful:
When manually replacing DateTimeOffset with DateTime and timestz with timestmp, an attempt to read information causes an error, but it saves normally using the time zone from the system settings.

```<code>//Model from ADO.NET
[Table("MyModel")]
public partial class MyModel
{
    [Key]
    [Column(TypeName = "integer")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int IdMyModel { get; set; }

    [Column(TypeName = "timestmp")]
    public DateTime TmCreate { get; set; }
}
</code>```
```<code>//How it is used
var myModel = db.MyModel.FirstOrDefault(m => m.IdMyModel == 123);//Erore
myModel.TmCreate = DateTime.Now;
db.SaveChanges(); //OK
</code>```

Body:
Came across a problem while working with DB2 from .Net Framework 4.8.

We have a Db2 for z/OS v12 database. Our database has fields with type "TIMESTAMP WITH TIME ZONE". When using ADO.NET, these fields in models are of type DateTimeOffset. When getting data from the database, there are no problems, but when saving, we get the following error:

2022-12-27 08:16:09.2273 FATAL InputManager.Program System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.EntityCommandCompilationException: An error occurred while preparing the command definition. See the inner exception for details. ---> System.InvalidOperationException: Unknown PrimitiveTypeKind DateTimeOffset
   at IBM.Data.DB2.EntityFramework.MetadataHelpers.GetDbType(PrimitiveTypeKind primitiveType, TypeUsage type)
   at IBM.Data.DB2.EntityFramework.DmlSqlGenerator.ExpressionTranslator.CreateParameter(Object value, TypeUsage type)
   at IBM.Data.DB2.EntityFramework.DmlSqlGenerator.ExpressionTranslator.Visit(DbConstantExpression expression)
   at System.Data.Entity.Core.Common.CommandTrees.DbConstantExpression.Accept(DbExpressionVisitor visitor)
   at IBM.Data.DB2.EntityFramework.DmlSqlGenerator.GenerateUpdateSql(DbUpdateCommandTree tree, SqlGenerator sqlGenerator, List`1& parameters, Boolean createParameters)
   at IBM.Data.DB2.EntityFramework.SqlGenerator.GenerateSql(DbCommandTree tree, DB2ProviderManifest manifest, List`1& parameters, CommandType& commandType, Dictionary`2& overrideColumnReturnTypes, List`1& replaceParametersWithValues, String[]& rowsToSkipAndLimit)
   at IBM.Data.DB2.EntityFramework.DB2ProviderServices.CreateCommand(DbProviderManifest manifest, DbCommandTree commandTree)
   at IBM.Data.DB2.EntityFramework.DB2ProviderServices.CreateDbCommandDefinition(DbProviderManifest manifest, DbCommandTree commandTree)
   at System.Data.Entity.Core.Common.DbProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(Dictionary`2 identifierValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<>c.<Update>b__21_0(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__153_0()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass148_0.<SaveChangesInternal>b__0()
   at IBM.Data.DB2.EntityFramework.DB2DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()

NuGet Packages installed:
EntityFramework v6.4.4;
EntityFramework.IBM.DB2 6.4.1.
Although the same error occurred on other versions.

Code example:

//Model from ADO.NET
[Table("MyModel")]
public partial class MyModel
{
    [Key]
    [Column(TypeName = "integer")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int IdMyModel { get; set; }

    [Column(TypeName = "timestz")]
    public DateTimeOffset TmCreate { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyModel>()
        .Property(e => e.TmCreate)
        .HasColumnType("timestz");
}

//How it is used
var myModel = db.MyModel.FirstOrDefault(m => m.IdMyModel == 123); //OK
myModel.TmCreate = DateTimeOffset.Now;
db.SaveChanges(); //Error

Sql-injection works OK.

string dateFormat = DateTimeOffset.Now.ToString("o");
string query = $"UPDATE MyDB.\"MyModel\" set \"TmCreate\" = TIMESTAMP '{dateFormat}' where \"IdMyModel \" = 123;";
db.ExecuteSqlCommand(query);

I saw the table, but, as I understand it, it is for the version for windows, not for z/OS. Is it even possible to work with
DateTimeOffset in our situation? What are we doing wrong?

Information that may be useful:
When manually replacing DateTimeOffset with DateTime and timestz with timestmp, an attempt to read information causes an error, but it saves normally using the time zone from the system settings.

//Model from ADO.NET
[Table("MyModel")]
public partial class MyModel
{
    [Key]
    [Column(TypeName = "integer")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int IdMyModel { get; set; }

    [Column(TypeName = "timestmp")]
    public DateTime TmCreate { get; set; }
}

//How it is used
var myModel = db.MyModel.FirstOrDefault(m => m.IdMyModel == 123);//Erore
myModel.TmCreate = DateTime.Now;
db.SaveChanges(); //OK


问:
Execution failed for task ':app:minifyReleaseWithR8'
Execution failed for task ':app:minifyReleaseWithR8'.

com.android.tools.r8.CompilationFailedException: Compilation failed to complete, position: Landroidx/core/util/Preconditions;InstructionScreen(Ljava/lang/String;Landroidx/compose/runtime/Composer;I)V, origin: C:\Users\Abhijeet.gradle\caches\transforms-3\62f30f4018c4fadcd072270a2ac9959a\transformed\core-1.9.0-runtime.jar:androidx/core/util/Preconditions.class

not able to build signed apk with r8


问:
Firebase returns "undefined" when data is not actually defined
Having a strange error trying to work with IDs in a react app. I am fetching a user from my database, which works fine. Each user has a list of products, each with their own respective ID. For some reason when I make the request to fetch the data and log it to the console, ONLY the ID (shown below) is undefined whilst the rest of the data is shown properly (everything is supposed to be a blank string). When I look into my firestore collection, there is a value for the ID so I'm not sure why it's coming up as undefined on my end. Images and code:

id showing up undefined in console:

Id in firestore:

Code:

```<code>  useEffect(() => {
    // retrieve product information from database
    let user = JSON.parse(localStorage.getItem("user"));
    if (user) {
      user = getUser(user.uid)
        .then((user) => {
          setUser(user);
          console.log(user);
          const product = user.products.filter((p) => (p.id = id));
          console.log(product);

          setName(product.name);
          setDescription(product.description);
          setPrice(product.price || "0");
          setUrl(product.url);
        })
        .catch((err) => console.error(err));
    } else {
      router.push("/");
    }
  }, []);
</code>```

Body:
Having a strange error trying to work with IDs in a react app. I am fetching a user from my database, which works fine. Each user has a list of products, each with their own respective ID. For some reason when I make the request to fetch the data and log it to the console, ONLY the ID (shown below) is undefined whilst the rest of the data is shown properly (everything is supposed to be a blank string). When I look into my firestore collection, there is a value for the ID so I'm not sure why it's coming up as undefined on my end. Images and code:

id showing up undefined in console:

Id in firestore:

Code:

  useEffect(() => {
    // retrieve product information from database
    let user = JSON.parse(localStorage.getItem("user"));
    if (user) {
      user = getUser(user.uid)
        .then((user) => {
          setUser(user);
          console.log(user);
          const product = user.products.filter((p) => (p.id = id));
          console.log(product);

          setName(product.name);
          setDescription(product.description);
          setPrice(product.price || "0");
          setUrl(product.url);
        })
        .catch((err) => console.error(err));
    } else {
      router.push("/");
    }
  }, []);


问:
Navigate from Java Activity to A composable function
I have a Java class that I want to navigate and pass data to composable function(another page). Can I use Intent and putExtra to do this?</p>


问:
Process time increases with increase in virtual hosts threads in apache server
I’m trying to run an AI yolov5 model on 12 cameras through the flask script. I have made 12 virtual hosts with separate directory containing separate flask script for each camera.

Each virtual host is with different port number, making them port separated virtual hosts

The system specifications includes:
OS: Windows 2019 server
GPU: 12 GB RTX Geforce 2080 Ti
CPU: intel xeon, 8 cores with 3.6 GHz
RAM: 32 GB

When I’m running only one camera through virtual hosts, its performance is really good, processing upto 34 frames per second. But as I add more cameras the processing time increases. With 12 cameras each virtual hosts processes only 4 frames per second, reducing the performance.

Are the worker threads through which the virtual hosts are initialized are interfering with each other?

I have increased the thread limit of apache through winnit mpm module to 12000 threads, to spare extra threads to handle the load.

The cpu usage only goes to 35 %, RAM: 10 GB and GPU: 6 GB


问:
Redirect Wix Domain to GoDaddy Domain having a web site hosted in Hostinger
I will tell you about my situation, I have a website hosted by hostinger, and a domain in godaddy which points to the hostinger's site through hostinger's dns and a domain created in cpanel, all good.
The question is that I have a domain in wix, to which I want to point to goddady's, or simply that when I enter this domain in wix it redirects me to godaddy's to see my website in hostinger.

I tried to do it through the CNAME and the A record that Wix has, placing the domain name in the CNAME and the IP that appears in the cpanel in the A record, the problem is that it does not redirect me correctly, showing me this screen.
It is worth mentioning that in the CNAME place the godaddy domain with the www and in the A without the www.
I attach an image of the result.
Any advice or a solution?Result


问:
java actuator cpu utilization
I want to know the JVM CPU usage rate.
So we used the Java actuator's process.cpu.usage.

However, this value was different from the CPU utilization of the container.
So I wonder if "process.cpu.usage" is the usage rate.

And if it is, what is the limit value based on when calculating the utilization rate?

I can't find the official document or source code related to it.

Title: java actuator cpu utilization


问:
Warning: Each child in a list should have a unique "key" prop
I am getting this error when I upload the files in cloudinary.

```<code>  const [images, setImages] = useState([]);

</code>```
```<code> function showWidget(){
    const widget= window.cloudinary.createUploadWidget(
      {
        cloudName:'djguiefro',
        uploadPreset:'fz1sjhdc',
      },
      (error, result)=>{
        if(!error && result.event ==='success'){
          setImages((prev)=>[...prev,{url:result.info.url, public_id:result.info.public_id}])
        }
        else{
          console.log(error)
        }
      }
    );
    widget.open();
  }`
</code>```
```<code><Form.Group className='mb-3'>
                  <Button type='button' onClick={showWidget}>Upload Images</Button>
                  <div className='images-preview-container'>
                    {/* 2:11:34 */}
                    {images.map((image)=>(
                      <div className='images-preview'>
                        <img src={image.url}/>

                        {/*add items for removing  {(imgToRemove != image.public_id) this will remove the cross icon once clicked }*/}
                        {imgToRemove !== image.public_id && <i className='fa fa-times-circle' onClick={()=>handleRemoveImg(image)}></i>}
                      </div>
                    ))}
                  </div>
                </Form.Group>`
</code>```

I tried to fix the error but stuck

Body:
I am getting this error when I upload the files in cloudinary.

  const [images, setImages] = useState([]);

 function showWidget(){
    const widget= window.cloudinary.createUploadWidget(
      {
        cloudName:'djguiefro',
        uploadPreset:'fz1sjhdc',
      },
      (error, result)=>{
        if(!error && result.event ==='success'){
          setImages((prev)=>[...prev,{url:result.info.url, public_id:result.info.public_id}])
        }
        else{
          console.log(error)
        }
      }
    );
    widget.open();
  }`

<Form.Group className='mb-3'>
                  <Button type='button' onClick={showWidget}>Upload Images</Button>

                    {/* 2:11:34 */}
                    {images.map((image)=>(

                        {/*add items for removing  {(imgToRemove != image.public_id) this will remove the cross icon once clicked }*/}
                        {imgToRemove !== image.public_id && handleRemoveImg(image)}>}

                    ))}

                </Form.Group>`

I tried to fix the error but stuck


问:
How to display a confirmation dialog when user click button in Isolated components in react app (Next Js)
I'm maintaining global flag when there is a form has some and preventing route changes but i have some isolated components which has certain button clicks (6 buttons) that i need to prevent when form has changes.

At the moment i'm checking formHasChange on every button click methods and getting confirmation and executing event. For that i have implemented wrapper button component to check the condition and get user confirmation. I would like to know is the any other best way to achieve this ?

Below is wrapper component

import React, { Children, isValidElement, cloneElement, SyntheticEvent } from 'react';

const EventWrapper = ({ children, onClick, hasChange }) => {
  function areYouSure(event) {
    if (hasChange) {
      return confirm('Are you sure want to discard changes ?') ? onClick(event) : event.preventDefault();
    } else {
      onClick(event);
    }
  }

  const childrenWithProps = Children.map(children, (child) => {
    if (isValidElement(child)) {
      return cloneElement(child, { onClick: (event: SyntheticEvent) => areYouSure(event) });
    }
    return child;
  });

  return <>{childrenWithProps}</>;
};

export default EventWrapper;```
</div>
</div>
</p>
<p>Below hook used for the prevent rout changes</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import Router from 'next/router';
import { useEffect } from 'react';
import { useBeforeUnload } from 'react-use';
import { useSettings } from './useSettings';
import themeConfig from 'src/config/themeConfig';
import nProgress from 'nprogress';

const useUnsaveChangeConfirm = (isConfirm = true, message = 'Are you sure want to leave this page?') => {
  const { settings, saveSettings } = useSettings();

  useBeforeUnload(isConfirm, message);

  useEffect(() => {
    const handler = () => {
      if (isConfirm && !window.confirm(message)) {
        if (settings.routingLoader) {
          nProgress.done();
        }
        throw 'Route Canceled due to unsaved changes';
      }
    };

    Router.events.on('routeChangeStart', handler);

    return () => {
      Router.events.off('routeChangeStart', handler);
      saveSettings({ ...settings, routingLoader: themeConfig.routingLoader });
    };
  }, [isConfirm, message]);
};

export default useUnsaveChangeConfirm;</code>```

Body:
I'm maintaining global flag when there is a form has some and preventing route changes but i have some isolated components which has certain button clicks (6 buttons) that i need to prevent when form has changes.

At the moment i'm checking formHasChange on every button click methods and getting confirmation and executing event. For that i have implemented wrapper button component to check the condition and get user confirmation. I would like to know is the any other best way to achieve this ?

Below is wrapper component

import React, { Children, isValidElement, cloneElement, SyntheticEvent } from 'react';

const EventWrapper = ({ children, onClick, hasChange }) => {
  function areYouSure(event) {
    if (hasChange) {
      return confirm('Are you sure want to discard changes ?') ? onClick(event) : event.preventDefault();
    } else {
      onClick(event);
    }
  }

  const childrenWithProps = Children.map(children, (child) => {
    if (isValidElement(child)) {
      return cloneElement(child, { onClick: (event: SyntheticEvent) => areYouSure(event) });
    }
    return child;
  });

  return <>{childrenWithProps}</>;
};

export default EventWrapper;

Below hook used for the prevent rout changes

import Router from 'next/router';
import { useEffect } from 'react';
import { useBeforeUnload } from 'react-use';
import { useSettings } from './useSettings';
import themeConfig from 'src/config/themeConfig';
import nProgress from 'nprogress';

const useUnsaveChangeConfirm = (isConfirm = true, message = 'Are you sure want to leave this page?') => {
  const { settings, saveSettings } = useSettings();

  useBeforeUnload(isConfirm, message);

  useEffect(() => {
    const handler = () => {
      if (isConfirm && !window.confirm(message)) {
        if (settings.routingLoader) {
          nProgress.done();
        }
        throw 'Route Canceled due to unsaved changes';
      }
    };

    Router.events.on('routeChangeStart', handler);

    return () => {
      Router.events.off('routeChangeStart', handler);
      saveSettings({ ...settings, routingLoader: themeConfig.routingLoader });
    };
  }, [isConfirm, message]);
};

export default useUnsaveChangeConfirm;


问:
what does count[s2.charAt(i) - 'a']--; do?
```<code>int[] count = new int[26];
for (int i = 0; i < len1; i++) {
            count[s1.charAt(i) - 'a']++;
            count[s2.charAt(i) - 'a']--;
        }
</code>```

what is
count[s1.charAt(i) - 'a']++; and count[s2.charAt(i) - 'a']--;
exactly doing?.count is an int array

Body:
int[] count = new int[26];
for (int i = 0; i < len1; i++) {
            count[s1.charAt(i) - 'a']++;
            count[s2.charAt(i) - 'a']--;
        }

what is
count[s1.charAt(i) - 'a']++; and count[s2.charAt(i) - 'a']--;
exactly doing?.count is an int array


问:
How to show count of unread messages for a particular user with firebase flutter as shown in image

I have searched a lot but only getting unread message badges for app icon

Please help me get this


问:
Can we say everything is "Data" in Functional Programming?
I'm trying to learn and understand thinking Functionally. What I learned so far gives me the idea below:

There are 2 sides to Any application, Algorithm and Data, and functional programming lets us beautifully separate them when designing our solution. But on the other hand Algorithms are being written by Functions, and Functions are values in Functional Programming.

Based on this, Functional Programming is about Composing Data and not only Functions! Functions are only a specific kind of data.

How much I'm correct? and where do I need to work on my reasoning?


问:
How to refresh contextmenustrip items or refreshing form's items
Basically, i am creating a raw-based web browser application. Bookmarks are added in contextmenu toolstripitem either from using "star" button or via another form. When added using another form, it is not refreshing the contextmenu items which are added from another form in the main form.

MainForm View:

mainform

Favourites/Bookmarks View:
bookmarks
updatebookmarks

This is how it is added via another form:
addbookmark
addbookmark2

Code Preview:

Star Button:

private void favButton_Click(object sender, EventArgs e)
        {
            if(inputUrlBox.Text != "")
            {
                var item = inputUrlBox.Text.ToString();

                if(!favouritesToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>().Any(x => x.Text == item))
                {
                    try {
                        Properties.Settings.Default.BookmarksList.Add(item + ",null");
                        Properties.Settings.Default.Save();
                        foreach (var bookmark in Properties.Settings.Default.BookmarksList) {
                            var link = bookmark.Split(',')[0].ToString();
                            favouritesToolStripMenuItem.DropDownItems.Add(link);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("Bookmark already exists!");
                }
            }
        }
```
<p>Moving directly to "Add" in another form's button (this is written in BookmarkWindow Form):</p>
<pre class="lang-cs prettyprint-override"><code>        private void addButton_Click(object sender, EventArgs e)
        {
            AddBookmarkWindow form = new AddBookmarkWindow();
            form.ShowDialog(this);

        }
</code>```

In AddBookMark's Form (AddBookmkarkWindow.cs):

if ((isUri) && (linkinput != null && linkinput.Length > 0) && (nameinput != null && nameinput.Length > 0))
            {
                Properties.Settings.Default.BookmarksList.Add(linkinput + "," + nameinput);
                Properties.Settings.Default.Save();

                MainWindow mw = new MainWindow();
                mw.updatebookmarkstab(linkinput);
                this.Close();
                MessageBox.Show("Added!");
            }
```
<p>This "updatebookmarkstab" function is in mainwindow/mainform:</p>
<pre class="lang-cs prettyprint-override"><code> public void updatebookmarkstab(string item)
        {
            menuStrip1.Refresh();
            contextMenuStrip1.Refresh();
            favouritesToolStripMenuItem.DropDownItems.Add(item);

        }
</code>```

What I expect is, once i add bookmark(s) from another form, I want it to be showed in main form's contextmenustrip item just like how "star" works.

Anyone has any idea on how to refresh menuitems from another form or has a better solution to provide this view.

Body:
Basically, i am creating a raw-based web browser application. Bookmarks are added in contextmenu toolstripitem either from using "star" button or via another form. When added using another form, it is not refreshing the contextmenu items which are added from another form in the main form.

MainForm View:

mainform

Favourites/Bookmarks View:
bookmarks
updatebookmarks

This is how it is added via another form:
addbookmark
addbookmark2

Code Preview:

Star Button:

private void favButton_Click(object sender, EventArgs e)
        {
            if(inputUrlBox.Text != "")
            {
                var item = inputUrlBox.Text.ToString();

                if(!favouritesToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>().Any(x => x.Text == item))
                {
                    try {
                        Properties.Settings.Default.BookmarksList.Add(item + ",null");
                        Properties.Settings.Default.Save();
                        foreach (var bookmark in Properties.Settings.Default.BookmarksList) {
                            var link = bookmark.Split(',')[0].ToString();
                            favouritesToolStripMenuItem.DropDownItems.Add(link);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("Bookmark already exists!");
                }
            }
        }

Moving directly to "Add" in another form's button (this is written in BookmarkWindow Form):

        private void addButton_Click(object sender, EventArgs e)
        {
            AddBookmarkWindow form = new AddBookmarkWindow();
            form.ShowDialog(this);

        }

In AddBookMark's Form (AddBookmkarkWindow.cs):

if ((isUri) && (linkinput != null && linkinput.Length > 0) && (nameinput != null && nameinput.Length > 0))
            {
                Properties.Settings.Default.BookmarksList.Add(linkinput + "," + nameinput);
                Properties.Settings.Default.Save();

                MainWindow mw = new MainWindow();
                mw.updatebookmarkstab(linkinput);
                this.Close();
                MessageBox.Show("Added!");
            }

This "updatebookmarkstab" function is in mainwindow/mainform:

 public void updatebookmarkstab(string item)
        {
            menuStrip1.Refresh();
            contextMenuStrip1.Refresh();
            favouritesToolStripMenuItem.DropDownItems.Add(item);

        }

What I expect is, once i add bookmark(s) from another form, I want it to be showed in main form's contextmenustrip item just like how "star" works.

Anyone has any idea on how to refresh menuitems from another form or has a better solution to provide this view.


问:
I enable multi_worker by using the respective keyword in keras,model.fit(), not working since, even after reverting, restart
Great thanks to anyone looking to help.
I added the complete error log,

Running inside run_distribute_coordinator already.

this seems to be the most important part for TL: DR

Restarted notebook,
Restarted system,

Current fit arguments

model.fit(
    x = train[:model_test_data_size],
    y = label[:model_test_data_size],
    batch_size = batch_size,
    epochs = epochs,
    verbose = 1,
    #callbacks = [early_stopping, lr_scheduler],
    validation_split = 0.5,
    shuffle = False)
```
```---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_3888\1502392415.py in <module>
      7     #callbacks = [early_stopping, lr_scheduler],
      8     validation_split = 0.5,
----> 9     shuffle = False)

c:\Users\Perosnal\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in _method_wrapper(self, *args, **kwargs)
    106   def _method_wrapper(self, *args, **kwargs):
    107     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
--> 108       return method(self, *args, **kwargs)
    109
    110     # Running inside `run_distribute_coordinator` already.

c:\Users\Perosnal\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1096                 batch_size=batch_size):
   1097               callbacks.on_train_batch_begin(step)

-> 1098               tmp_logs = train_function(iterator)
   1099               if data_handler.should_sync:
   1100                 context.async_wait()

c:\Users\Perosnal\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in __call__(self, *args, **kwds)
    778       else:
    779         compiler = "nonXla"
--> 780         result = self._call(*args, **kwds)
     [[node gradient_tape/mean_squared_error/BroadcastGradientArgs (defined at C:\Users\Perosnal\AppData\Local\Temp\ipykernel_3888\3286626927.py:9) ]] [Op:__inference_train_function_1206]

Function call stack:
train_function
```
```

Reverted back to code state when it executed successfully....!!!!
No avail
```

Body:
Great thanks to anyone looking to help.
I added the complete error log,

Running inside run_distribute_coordinator already.

this seems to be the most important part for TL: DR

Restarted notebook,
Restarted system,

Current fit arguments

model.fit(
    x = train[:model_test_data_size],
    y = label[:model_test_data_size],
    batch_size = batch_size,
    epochs = epochs,
    verbose = 1,
    #callbacks = [early_stopping, lr_scheduler],
    validation_split = 0.5,
    shuffle = False)

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_3888\1502392415.py in <module>
      7     #callbacks = [early_stopping, lr_scheduler],
      8     validation_split = 0.5,
----> 9     shuffle = False)

c:\Users\Perosnal\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in _method_wrapper(self, *args, **kwargs)
    106   def _method_wrapper(self, *args, **kwargs):
    107     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
--> 108       return method(self, *args, **kwargs)
    109
    110     # Running inside `run_distribute_coordinator` already.

c:\Users\Perosnal\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1096                 batch_size=batch_size):
   1097               callbacks.on_train_batch_begin(step)

-> 1098               tmp_logs = train_function(iterator)
   1099               if data_handler.should_sync:
   1100                 context.async_wait()

c:\Users\Perosnal\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in __call__(self, *args, **kwds)
    778       else:
    779         compiler = "nonXla"
--> 780         result = self._call(*args, **kwds)
     [[node gradient_tape/mean_squared_error/BroadcastGradientArgs (defined at C:\Users\Perosnal\AppData\Local\Temp\ipykernel_3888\3286626927.py:9) ]] [Op:__inference_train_function_1206]

Function call stack:
train_function

Reverted back to code state when it executed successfully....!!!!
No avail


问:
Issue when using embedded YouTube API for app
I made an app that can watch videos uploaded on YouTube through YouTube API.

I saved the URL, channel name, and thumbnail of the videos in my database and it's being called up from the app and played back.

Due to YouTube's policy, I know that it is possible to provide videos that the original author did not reject through embedding, so please let me know if it is possible to save URLs, channel names, and thumbnails in my database.