问:
Problems in second blocks message digest in self-learning SHA-1 algorithm
Output

I am new in learning C programming. Now, I am trying to do SHA-1 for university project. I think this coding by myself. I am trying to do the message digest from the file above 55characters, which means 2 blocks is needed. The first block message digest is correct, but the second block is wrong. I have checked it very many times, but I still not able to find the mistake. Can anyone with experiences able to help me find it out? Thank you.

patients information.txt
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  int length,number_of_block,str_length;
  unsigned int i = 0,j = 0,l = 0,e = 0,n = 0, t=0, k=0,f=0;
  float x=0;
  char c;
  int H[5]={0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0};
  unsigned int temp = 0;

  FILE *file;
  file = fopen("patients information.txt", "r");//Choose the file that want to access
  if (file == NULL)//detect the file is empty or not
  {
      printf("The file is empty");
  }

  fseek(file, 0, SEEK_END);// move the file pointer to the end of the file
  length = ftell(file);//calculate the length of sting in file
  fseek(file, 0, SEEK_SET);// move file pointer back to start of file so we can read each character

  printf("The length of string is %d\n",length);//check the number of character in string

  char *string = malloc(sizeof(char) * (length+1));

  while ( (c = fgetc(file)) != EOF)//pass the every character in the file to the string array
  {
    string[i] = c;
    i++;
  }

  string[i] = '\0';//terminate the string storing

  unsigned char long_msg[length+1];

  for (i=0;i<length;i++)//pass the pointer array to the unsigned character array
  {
      long_msg[i]=string[i];
  }

  printf("The character store in th array is ");

  long_msg[length]=128;

  for (i=0;i<=length;i++)//check the message in msg array
  {
      printf("%X ",long_msg[i]);
  }

  if (length<=55)
  {
      number_of_block = 1;
  }
  else if (length>55 && length<120)
  {
      number_of_block = 2;
  }
  else
  {
      x = ((length - 55)/64);//calculate the number of block needed
      number_of_block = x+2;
  }

  printf("\nNumber of block needed is %d\n",number_of_block);

  unsigned char blocks[number_of_block][64];

  for (i=0;i<number_of_block;i++)//Split the long string into n number of blocks
  {
      for(j=0;j<64;j++)
      {
          blocks[i][j]=long_msg[l];
          if(l>length)//padding 0
          {
              blocks[i][j]=0;
          }
          l++;
      }
  }
  for (i=0;i<number_of_block;i++)//check the blocks content

  {
      for(j=0;j<64;j++)
      {
          printf("%X ",blocks[i][j]);
      }
  }
  printf("\nCheck length padding:\n");
  str_length = 8*length;//sting length in bits

  if (length<32)//if length of string is 1 bytes in hexadecimal
  {
      blocks[number_of_block-1][63]=str_length;
  }
  else
  {
      blocks[number_of_block-1][62]=(str_length>>8);//second last block
      blocks[number_of_block-1][63]=((str_length<<8)>>8);//last block
  }

   for (i=0;i<number_of_block;i++)//check length padding
  {
      for(j=0;j<64;j++)
      {
          printf("%02X ",blocks[i][j]);
      }
  }

  unsigned int w[number_of_block][16][4];
  unsigned int W[number_of_block][80];
  unsigned int A[number_of_block],B[number_of_block],C[number_of_block],D[number_of_block],E[number_of_block];

  for (e=0;e<number_of_block;e++)
  {
      /*The problem is here*/
      n=0;
      for (i=0;i<16;i++)//split the padding message into w0 to w15 ,exp. w0 = (w[0][1]),....,(w[0][3])
        {
            for(j=0;j<4;j++)
            {
                w[e][i][j] = blocks[e][n];
                n++;
            }
        }

      for (i=0;i<16;i++)//combine the hex --> 16 block of hexadecimal(W0 to W15)
        {
            W[e][i] = ((w[e][i][0])<<24 | (w[e][i][1])<<16 | (w[e][i][2])<<8 | (w[e][i][3]));
        }

    /*Compute message digest*/
        A[e] = 0x67452301;
        B[e] = 0xEFCDAB89;
        C[e] = 0x98BADCFE;
        D[e] = 0x10325476;
        E[e] = 0xC3D2E1F0;

      for (t=0;t<=79;t++)
    {
        //for t = 16 -> 79
        if (t>=16 && t<=79)//prepare W16 to W79
        {
            W[e][t]= ( (W[e][t-3]) ^ (W[e][t-8]) ^ (W[e][t-14]) ^ (W[e][t-16]) );
            W[e][t]= ( ((W[e][t])<<1) | ((W[e][t]) >> (32-1)));//perform circular left shift
        }

        if (t>=0 && t<=19)
        {
            f = (B[e]&C[e]) | ((~B[e])&D[e]);
            k = 0x5A827999;
        }
        else if (t>=20 && t<=39)
        {
            f = (B[e]^C[e]^D[e]);
            k = 0x6ED9EBA1;
        }
        else if (t>=40 && t<=59)
        {
            f = (B[e]&C[e]) | (B[e]&D[e]) | (C[e]&D[e]);
            k = 0x8F1BBCDC;
        }
        else if(t>=60 && t<=79)
        {
            f = (B[e]^C[e]^D[e]);
            k = 0xCA62C1D6;
        }

        temp = ((A[e]<<5) | (A[e] >> (32-5))) + f + E[e] + W[e][t] + k;

        E[e] = D[e];
        D[e] = C[e];
        C[e] = ( (B[e]<<30) | (B[e]>> (32-30)));
        B[e] = A[e];
        A[e] = temp;
    }
    printf("\n\n");

    printf("%08X %08X %08X %08X %08X",A[e],B[e],C[e],D[e],E[e]);//check the value before adding up

    H[0] = ( H[0] + A[e]);
    H[1] = ( H[1] + B[e]);
    H[2] = ( H[2] + C[e]);
    H[3] = ( H[3] + D[e]);
    H[4] = ( H[4] + E[e]);
  }
  printf("\n\n");

  printf("Message digest:");
  for (i=0;i<5;i++)
    {
       printf("%X ",H[i]);
    }

    printf("\n\n");

  return 0;
}

</code>```

The wrong output of second block    : CE3A1FD0 01464A63 F6766B50 AF97AC62 8D5DBBDD
The output of second block should be: 906FD62C 58C0AAC0 B6A55520 74E9B89D 9AF00B7F

Body:
Output

I am new in learning C programming. Now, I am trying to do SHA-1 for university project. I think this coding by myself. I am trying to do the message digest from the file above 55characters, which means 2 blocks is needed. The first block message digest is correct, but the second block is wrong. I have checked it very many times, but I still not able to find the mistake. Can anyone with experiences able to help me find it out? Thank you.

patients information.txt
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  int length,number_of_block,str_length;
  unsigned int i = 0,j = 0,l = 0,e = 0,n = 0, t=0, k=0,f=0;
  float x=0;
  char c;
  int H[5]={0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0};
  unsigned int temp = 0;

  FILE *file;
  file = fopen("patients information.txt", "r");//Choose the file that want to access
  if (file == NULL)//detect the file is empty or not
  {
      printf("The file is empty");
  }

  fseek(file, 0, SEEK_END);// move the file pointer to the end of the file
  length = ftell(file);//calculate the length of sting in file
  fseek(file, 0, SEEK_SET);// move file pointer back to start of file so we can read each character

  printf("The length of string is %d\n",length);//check the number of character in string

  char *string = malloc(sizeof(char) * (length+1));

  while ( (c = fgetc(file)) != EOF)//pass the every character in the file to the string array
  {
    string[i] = c;
    i++;
  }

  string[i] = '\0';//terminate the string storing

  unsigned char long_msg[length+1];

  for (i=0;i<length;i++)//pass the pointer array to the unsigned character array
  {
      long_msg[i]=string[i];
  }

  printf("The character store in th array is ");

  long_msg[length]=128;

  for (i=0;i<=length;i++)//check the message in msg array
  {
      printf("%X ",long_msg[i]);
  }

  if (length<=55)
  {
      number_of_block = 1;
  }
  else if (length>55 && length<120)
  {
      number_of_block = 2;
  }
  else
  {
      x = ((length - 55)/64);//calculate the number of block needed
      number_of_block = x+2;
  }

  printf("\nNumber of block needed is %d\n",number_of_block);

  unsigned char blocks[number_of_block][64];

  for (i=0;i<number_of_block;i++)//Split the long string into n number of blocks
  {
      for(j=0;j<64;j++)
      {
          blocks[i][j]=long_msg[l];
          if(l>length)//padding 0
          {
              blocks[i][j]=0;
          }
          l++;
      }
  }
  for (i=0;i<number_of_block;i++)//check the blocks content

  {
      for(j=0;j<64;j++)
      {
          printf("%X ",blocks[i][j]);
      }
  }
  printf("\nCheck length padding:\n");
  str_length = 8*length;//sting length in bits

  if (length<32)//if length of string is 1 bytes in hexadecimal
  {
      blocks[number_of_block-1][63]=str_length;
  }
  else
  {
      blocks[number_of_block-1][62]=(str_length>>8);//second last block
      blocks[number_of_block-1][63]=((str_length<<8)>>8);//last block
  }

   for (i=0;i<number_of_block;i++)//check length padding
  {
      for(j=0;j<64;j++)
      {
          printf("%02X ",blocks[i][j]);
      }
  }

  unsigned int w[number_of_block][16][4];
  unsigned int W[number_of_block][80];
  unsigned int A[number_of_block],B[number_of_block],C[number_of_block],D[number_of_block],E[number_of_block];

  for (e=0;e<number_of_block;e++)
  {
      /*The problem is here*/
      n=0;
      for (i=0;i<16;i++)//split the padding message into w0 to w15 ,exp. w0 = (w[0][1]),....,(w[0][3])
        {
            for(j=0;j<4;j++)
            {
                w[e][i][j] = blocks[e][n];
                n++;
            }
        }

      for (i=0;i<16;i++)//combine the hex --> 16 block of hexadecimal(W0 to W15)
        {
            W[e][i] = ((w[e][i][0])<<24 | (w[e][i][1])<<16 | (w[e][i][2])<<8 | (w[e][i][3]));
        }

    /*Compute message digest*/
        A[e] = 0x67452301;
        B[e] = 0xEFCDAB89;
        C[e] = 0x98BADCFE;
        D[e] = 0x10325476;
        E[e] = 0xC3D2E1F0;

      for (t=0;t<=79;t++)
    {
        //for t = 16 -> 79
        if (t>=16 && t<=79)//prepare W16 to W79
        {
            W[e][t]= ( (W[e][t-3]) ^ (W[e][t-8]) ^ (W[e][t-14]) ^ (W[e][t-16]) );
            W[e][t]= ( ((W[e][t])<<1) | ((W[e][t]) >> (32-1)));//perform circular left shift
        }

        if (t>=0 && t<=19)
        {
            f = (B[e]&C[e]) | ((~B[e])&D[e]);
            k = 0x5A827999;
        }
        else if (t>=20 && t<=39)
        {
            f = (B[e]^C[e]^D[e]);
            k = 0x6ED9EBA1;
        }
        else if (t>=40 && t<=59)
        {
            f = (B[e]&C[e]) | (B[e]&D[e]) | (C[e]&D[e]);
            k = 0x8F1BBCDC;
        }
        else if(t>=60 && t<=79)
        {
            f = (B[e]^C[e]^D[e]);
            k = 0xCA62C1D6;
        }

        temp = ((A[e]<<5) | (A[e] >> (32-5))) + f + E[e] + W[e][t] + k;

        E[e] = D[e];
        D[e] = C[e];
        C[e] = ( (B[e]<<30) | (B[e]>> (32-30)));
        B[e] = A[e];
        A[e] = temp;
    }
    printf("\n\n");

    printf("%08X %08X %08X %08X %08X",A[e],B[e],C[e],D[e],E[e]);//check the value before adding up

    H[0] = ( H[0] + A[e]);
    H[1] = ( H[1] + B[e]);
    H[2] = ( H[2] + C[e]);
    H[3] = ( H[3] + D[e]);
    H[4] = ( H[4] + E[e]);
  }
  printf("\n\n");

  printf("Message digest:");
  for (i=0;i<5;i++)
    {
       printf("%X ",H[i]);
    }

    printf("\n\n");

  return 0;
}

The wrong output of second block    : CE3A1FD0 01464A63 F6766B50 AF97AC62 8D5DBBDD
The output of second block should be: 906FD62C 58C0AAC0 B6A55520 74E9B89D 9AF00B7F


来源: stackexchange

问:
Switching from Docker Desktop to Colima - no localhost access
Trying to switch to colima from Docker Desktop on mac but having issues reaching my containers on localhost.

Removed Docker Desktop and installed colimna/docker w homebrew. Colima starts fine.

I have a command that I use to run Dynamo:

```<code>docker run --name dynamodb -d -p 8000:8000 amazon/dynamodb-local"
</code>```

When I was using Docker Desktop I could reach the database on localhost:8000. Now it's only accessible on 127.0.0.1:8000

My /etc/hosts correctly maps localhost - this is an issue with the switch. Not finding much online regarding this - any ideas? It seems that docker no longer recognizes localhost as an alias for 127.0.0.1 after the switch. Not using Kubernetes or docker compose.

ContentLicense: CC BY-SA 4.0

Body:
Trying to switch to colima from Docker Desktop on mac but having issues reaching my containers on localhost.

Removed Docker Desktop and installed colimna/docker w homebrew. Colima starts fine.

I have a command that I use to run Dynamo:

docker run --name dynamodb -d -p 8000:8000 amazon/dynamodb-local"

When I was using Docker Desktop I could reach the database on localhost:8000. Now it's only accessible on 127.0.0.1:8000

My /etc/hosts correctly maps localhost - this is an issue with the switch. Not finding much online regarding this - any ideas? It seems that docker no longer recognizes localhost as an alias for 127.0.0.1 after the switch. Not using Kubernetes or docker compose.


问:
How can I use API Arcgis in linux
I'm trying to install arcgis library on my Linux machine. My idea is to use this library in Google cloud functions but I've had some errors. I want to know if Someone knows how can I use this library in Linux or google cloud functions.

Thanks

I tried to install the library but I've had errors

Title: How can I use API Arcgis in linux


问:
Authentication with Spring Security and JWT token
I'm new to java, I have a project to practice/train and when trying to make an authentication method with SpringBoot and JWT I'm not succeeding, currently it doesn't even let the project go up, it gives the error below:

```<code>APPLICATION FAILED TO START
***************************

Description:

Field authenticationManager in com.luan.config.SecurityConfig required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
</code>```

I'm using version 6.0.1 of Spring Security and version 0.9.1 of JWT according to the pom.xml below:

```<code>    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</code>```

The class that I suspect to be in error is the one below:

```<code>@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

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

        http.addFilter(new JWTAuthenticationFilter(authenticationManager, jwtUtil));

        http.httpBasic().and().authorizeHttpRequests()

        .requestMatchers(HttpMethod.POST, "/postsblog/**").permitAll()
        .requestMatchers(HttpMethod.GET).permitAll()
        .requestMatchers(HttpMethod.DELETE).hasRole("ADMIN")
        .requestMatchers(HttpMethod.PUT).permitAll()
        .anyRequest().authenticated()
        .and().csrf().disable()
        .cors().disable();
        return http.build();
    }

    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("*").exposedHeaders("*");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
        }

    @Bean(name = "authenticationManager")
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

}
</code>```

More specifically, I believe it's a problem with the last method, the AuthenticationManagerBuilder, I've tried to solve it in some ways and I couldn't, searching the internet I only found content with old Spring Security extending the WebSecurityConfigAdapter.

If anyone can help, thanks in advance.

Body:
I'm new to java, I have a project to practice/train and when trying to make an authentication method with SpringBoot and JWT I'm not succeeding, currently it doesn't even let the project go up, it gives the error below:

APPLICATION FAILED TO START
***************************

Description:

Field authenticationManager in com.luan.config.SecurityConfig required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.

I'm using version 6.0.1 of Spring Security and version 0.9.1 of JWT according to the pom.xml below:

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

The class that I suspect to be in error is the one below:

@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

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

        http.addFilter(new JWTAuthenticationFilter(authenticationManager, jwtUtil));

        http.httpBasic().and().authorizeHttpRequests()

        .requestMatchers(HttpMethod.POST, "/postsblog/**").permitAll()
        .requestMatchers(HttpMethod.GET).permitAll()
        .requestMatchers(HttpMethod.DELETE).hasRole("ADMIN")
        .requestMatchers(HttpMethod.PUT).permitAll()
        .anyRequest().authenticated()
        .and().csrf().disable()
        .cors().disable();
        return http.build();
    }

    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("*").exposedHeaders("*");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
        }

    @Bean(name = "authenticationManager")
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

}

More specifically, I believe it's a problem with the last method, the AuthenticationManagerBuilder, I've tried to solve it in some ways and I couldn't, searching the internet I only found content with old Spring Security extending the WebSecurityConfigAdapter.

If anyone can help, thanks in advance.


问:
repeated data in json response spring boot
I have this SQL query

@Query( value = "select tc_users.id as userid,tc_devices.id as deviceid, tc_devices.name, tc_devices.lastupdate as hora_fecha,\n" +
            "tc_positions.speed as velocidad, tc_positions.latitude, tc_positions.longitude, tc_positions.devicetime\n" +
            "from tc_devices\n" +
            "join tc_users on tc_users.id = tc_devices.userid \n" +
            "join tc_positions on tc_devices.id= tc_positions.deviceid and \n" +
            "tc_positions.devicetime=(select max(devicetime) from tc_positions where tc_positions.deviceid= tc_devices.id)    and tc_users.id= ?1 ;", nativeQuery = true)
List<resumen_entity> resu(Integer userid);
```
<p>This SQL query return this data
result of query in SQL workbench
but when using it with my spring project it returns this json
result of query by springboot
a really need help with this problem</p>
<p>I try with another type of SQL query but spring returns the same result</p>
<pre class="lang-java prettyprint-override"><code>@Query( value = "select distinct tc_users.id as userid,tc_devices.id as deviceid, " +
            "tc_devices.name, tc_devices.lastupdate as hora_fecha, " +
            "tc_positions.speed as velocidad, tc_positions.latitude, " +
            "tc_positions.longitude, tc_positions.devicetime " +
            "from tc_users, tc_devices,tc_positions where tc_users.id =tc_devices.userid " +
            "and tc_devices.id= tc_positions.deviceid " +
            "and tc_positions.devicetime=(select max(devicetime) " +
            "from tc_positions where tc_positions.deviceid = tc_devices.id) and tc_users.id= ?1 ",
            nativeQuery = true)
List<resumen_entity> resu(Integer userid);
</code>```

Body:
I have this SQL query

@Query( value = "select tc_users.id as userid,tc_devices.id as deviceid, tc_devices.name, tc_devices.lastupdate as hora_fecha,\n" +
            "tc_positions.speed as velocidad, tc_positions.latitude, tc_positions.longitude, tc_positions.devicetime\n" +
            "from tc_devices\n" +
            "join tc_users on tc_users.id = tc_devices.userid \n" +
            "join tc_positions on tc_devices.id= tc_positions.deviceid and \n" +
            "tc_positions.devicetime=(select max(devicetime) from tc_positions where tc_positions.deviceid= tc_devices.id)    and tc_users.id= ?1 ;", nativeQuery = true)
List<resumen_entity> resu(Integer userid);

This SQL query return this data
result of query in SQL workbench
but when using it with my spring project it returns this json
result of query by springboot
a really need help with this problem

I try with another type of SQL query but spring returns the same result

@Query( value = "select distinct tc_users.id as userid,tc_devices.id as deviceid, " +
            "tc_devices.name, tc_devices.lastupdate as hora_fecha, " +
            "tc_positions.speed as velocidad, tc_positions.latitude, " +
            "tc_positions.longitude, tc_positions.devicetime " +
            "from tc_users, tc_devices,tc_positions where tc_users.id =tc_devices.userid " +
            "and tc_devices.id= tc_positions.deviceid " +
            "and tc_positions.devicetime=(select max(devicetime) " +
            "from tc_positions where tc_positions.deviceid = tc_devices.id) and tc_users.id= ?1 ",
            nativeQuery = true)
List<resumen_entity> resu(Integer userid);


问:
Cannot paste text content in textarea or textbox
For some reason I cannot paste this block of text in any textarea in the browser. It's not even a large content but pasting does not work.

You can try copy/paste the text here:

```<code>[https://jsfiddle.net/bn9hx3vt/]
</code>```

Copy all text and paste it, it will not paste. but if you copy partially and paste. It works.

Body:
For some reason I cannot paste this block of text in any textarea in the browser. It's not even a large content but pasting does not work.

You can try copy/paste the text here:

[https://jsfiddle.net/bn9hx3vt/]

Copy all text and paste it, it will not paste. but if you copy partially and paste. It works.


问:
Visual Studio 2022 Git Merge tool not starting
The merge tool is failing in my visual studio 2022 and I am not able to resolve merge conflict.

The side checkboxes to select lines are not visible and its not letting me choose the current or incoming versions as well.

I have restarted Visual Studio 2022. I have restarted my laptop but still the same result.

Any pointers or ideas how to resolve this issue ?


问:
rename dataframe column values based on dict and groupby
For a mock df:

```<code>tempdf = pd.DataFrame({
    'class': ['a', 'a', 'a','a','a','a', 'b','b','b','b', 'b', 'b'],
    'type': ['train', 'train', 'train','train', 'test','test', 'train','train','train','train','test','test'],
    'mag': [15,15,8,8,15,8, 2,2,6,6,6,6]
})
print(tempdf)
   class   type    mag
0      a  train     15
1      a  train     15
2      a  train      8
3      a  train      8
4      a   test     15
5      a   test      8
6      b  train      2
7      b  train      2
8      b  train      6
9      b  train      6
10     b   test      6
11     b   test      6
</code>```

I want to rename the mag column values according to a new mag-level name, so that the different classes can be sorted according to a relative magnification level.

I want to end up with:

```<code>   class   type    mag
0      a  train   mag-level2
1      a  train   mag-level2
2      a  train   mag-level1
3      a  train   mag-level1
4      a   test   mag-level2
5      a   test   mag-level1
6      b  train   mag-level1
7      b  train   mag-level1
8      b  train   mag-level2
9      b  train   mag-level2
10     b   test   mag-level2
11     b   test   mag-level2
</code>```

I defined a function to create the new names depending on how many magnification levels are present in the original data

```<code>def make_magnif_groups(class):
    # create magnification label based on number of magnifications for dataset
    labels = ['mag-level{}'.format(x) for x in range(1, len(np.unique(class))+1)]
    # assign value with mag-level
    paired = dict(zip(np.unique(sorted(class)), labels))
    return paired
</code>```

Printing the mags for each class looks like:

```<code>tempmag = tempdf.groupby('class')['mag'].unique()
print(tempmag)
class
a    [15, 8]
b     [2, 6]
</code>```

My goal is to rename the mag col values according to their respective magnification level, which i specify via:

```<code>for i in range(len(tempmag)):
    pairs = make_magnif_groups(tempmag[i])
</code>```

which looks like:

```<code>print(pairs)
{8: 'mag-level1', 15: 'mag-level2'}
{2: 'mag-level1', 6: 'mag-level2'}
</code>```

I was thinking that using the tempdf.replace({'mag': pairs}) is needed. However, I can't apply the function directly because my actual df may have, for example mag of 8 = mag-level1 for one class but is a mag-level2 for another class...

I was trying various things with df.groupby(['species', 'type']) (Note, while theory the mag should be the same in the train/test for a specific class, it isn't always the case. Hence needing to group by that as well)

tempdf.groupby(['class', 'type']).agg({'mag': lambda x: make_magnif_groups(x)}).unstack() returns the dict that should be used to replace all the values by for each class-type subgroup... but i'm missing the last step (or may not be approaching this in the right way at all...)

Thanks for any suggestions!

Body:
For a mock df:

tempdf = pd.DataFrame({
    'class': ['a', 'a', 'a','a','a','a', 'b','b','b','b', 'b', 'b'],
    'type': ['train', 'train', 'train','train', 'test','test', 'train','train','train','train','test','test'],
    'mag': [15,15,8,8,15,8, 2,2,6,6,6,6]
})
print(tempdf)
   class   type    mag
0      a  train     15
1      a  train     15
2      a  train      8
3      a  train      8
4      a   test     15
5      a   test      8
6      b  train      2
7      b  train      2
8      b  train      6
9      b  train      6
10     b   test      6
11     b   test      6

I want to rename the mag column values according to a new mag-level name, so that the different classes can be sorted according to a relative magnification level.

I want to end up with:

   class   type    mag
0      a  train   mag-level2
1      a  train   mag-level2
2      a  train   mag-level1
3      a  train   mag-level1
4      a   test   mag-level2
5      a   test   mag-level1
6      b  train   mag-level1
7      b  train   mag-level1
8      b  train   mag-level2
9      b  train   mag-level2
10     b   test   mag-level2
11     b   test   mag-level2

I defined a function to create the new names depending on how many magnification levels are present in the original data

def make_magnif_groups(class):
    # create magnification label based on number of magnifications for dataset
    labels = ['mag-level{}'.format(x) for x in range(1, len(np.unique(class))+1)]
    # assign value with mag-level
    paired = dict(zip(np.unique(sorted(class)), labels))
    return paired

Printing the mags for each class looks like:

tempmag = tempdf.groupby('class')['mag'].unique()
print(tempmag)
class
a    [15, 8]
b     [2, 6]

My goal is to rename the mag col values according to their respective magnification level, which i specify via:

for i in range(len(tempmag)):
    pairs = make_magnif_groups(tempmag[i])

which looks like:

print(pairs)
{8: 'mag-level1', 15: 'mag-level2'}
{2: 'mag-level1', 6: 'mag-level2'}

I was thinking that using the tempdf.replace({'mag': pairs}) is needed. However, I can't apply the function directly because my actual df may have, for example mag of 8 = mag-level1 for one class but is a mag-level2 for another class...

I was trying various things with df.groupby(['species', 'type']) (Note, while theory the mag should be the same in the train/test for a specific class, it isn't always the case. Hence needing to group by that as well)

tempdf.groupby(['class', 'type']).agg({'mag': lambda x: make_magnif_groups(x)}).unstack() returns the dict that should be used to replace all the values by for each class-type subgroup... but i'm missing the last step (or may not be approaching this in the right way at all...)

Thanks for any suggestions!


问:
Replicate "ng serve --host NAME --publicHost NAME:PORT" with webpack/react/nginx
I am now working on an application where the login page is served by docker under http://DOMAIN_NAME/folder/.

I am trying to replicate the setup that was used with an Angular app and port it to a React App, this is the command used in package.json:

```<code>...
"start": "ng serve --host DOMAIN_NAME --publicHost DOMAIN_NAME:PORT"
...
</code>```

I did not touch NGINX reverse proxy a lot in the past hence my confusion with this setup.

I am wondering what --host and --publicHost do behind the scenes and how I can configure webpack-dev-server accordingly.

Body:
I am now working on an application where the login page is served by docker under http://DOMAIN_NAME/folder/.

I am trying to replicate the setup that was used with an Angular app and port it to a React App, this is the command used in package.json:

...
"start": "ng serve --host DOMAIN_NAME --publicHost DOMAIN_NAME:PORT"
...

I did not touch NGINX reverse proxy a lot in the past hence my confusion with this setup.

I am wondering what --host and --publicHost do behind the scenes and how I can configure webpack-dev-server accordingly.


问:
Qt icon theme switch
I am currently following a tutorial on how to achieve icon theme switching with QtWidgets.

Here is the article I am following:
https://openapplibrary.org/dev-tutorials/qt-icon-themes

I have a simple program setup where my MainWindow object creates a QPushButton and displays it with the dark icon.

mainwindow.h:

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>

class MainWindow : public QMainWindow
{
// Macros
    Q_OBJECT

// Constructors
public:
    MainWindow(QWidget *parent = nullptr);

// Destructors
public:
    ~MainWindow();

// Widgets
private:

    QPushButton *button;

#endif
</code>```

mainwindow.cpp:

```<code>#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    button = new QPushButton(

        QIcon(":/resources/icons/Qogir-dark/16/actions/format-text-italic.svg"),
        this
        );
}

MainWindow::~MainWindow()
{

}
</code>```

Here is my main file.

main.cpp:

```<code>#include "mainwindow.h"
#include <QApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);

    MainWindow mainWindow;
    mainWindow.show();

    // Making sure that Qt is looking in the correct path
    QStringList list;
    list<<"://resources/icons";
    QIcon::setThemeSearchPaths(list);

    QIcon::setThemeName("Qogir");

    return application.exec();
}
</code>```

I found a very nice icon theme called Qogir from the Gnome website.

Link to icon theme:
(https://www.gnome-look.org/p/1296407)

resource file:

```<code><RCC>
    <qresource prefix="/">
        <file>resources/icons/Qogir/24/actions/accept_signal.svg</file>
        <file>resources/icons/Qogir/index.theme</file>
        <file>resources/icons/Qogir-dark/16/actions/accept_signal.svg</file>
        <file>resources/icons/Qogir-dark/index.theme</file>
    </qresource>
</RCC>
</code>```

The application runs and the button displays an icon (the dark icon). However, in my main I specified that as soon as the MainWindow is displayed, I want it to display the light theme icon. But it doesn't work.

Any ideas what I am doing wrong?

Title: Qt icon theme switch

Body:
I am currently following a tutorial on how to achieve icon theme switching with QtWidgets.

Here is the article I am following:
https://openapplibrary.org/dev-tutorials/qt-icon-themes

I have a simple program setup where my MainWindow object creates a QPushButton and displays it with the dark icon.

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>

class MainWindow : public QMainWindow
{
// Macros
    Q_OBJECT

// Constructors
public:
    MainWindow(QWidget *parent = nullptr);

// Destructors
public:
    ~MainWindow();

// Widgets
private:

    QPushButton *button;

#endif

mainwindow.cpp:

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    button = new QPushButton(

        QIcon(":/resources/icons/Qogir-dark/16/actions/format-text-italic.svg"),
        this
        );
}

MainWindow::~MainWindow()
{

}

Here is my main file.

main.cpp:

#include "mainwindow.h"
#include <QApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);

    MainWindow mainWindow;
    mainWindow.show();

    // Making sure that Qt is looking in the correct path
    QStringList list;
    list<<"://resources/icons";
    QIcon::setThemeSearchPaths(list);

    QIcon::setThemeName("Qogir");

    return application.exec();
}

I found a very nice icon theme called Qogir from the Gnome website.

Link to icon theme:
(https://www.gnome-look.org/p/1296407)

resource file:

<RCC>
    <qresource prefix="/">
        <file>resources/icons/Qogir/24/actions/accept_signal.svg</file>
        <file>resources/icons/Qogir/index.theme</file>
        <file>resources/icons/Qogir-dark/16/actions/accept_signal.svg</file>
        <file>resources/icons/Qogir-dark/index.theme</file>
    </qresource>
</RCC>

The application runs and the button displays an icon (the dark icon). However, in my main I specified that as soon as the MainWindow is displayed, I want it to display the light theme icon. But it doesn't work.

Any ideas what I am doing wrong?


问:
Only when a post request fails should the Link stop
Lobbies.json
{"Lobbies":[]}

jsonWorker.js

```<code>const fs = require('fs');

function lobbyUpdater(name, password) {
    let rawdata = fs.readFileSync('Lobbies.json');
    let data = JSON.parse(rawdata);
    // data.Lobbies.length = 0; // Remove this for production
    let newLobby = {"Name":name, "Password":password, "Players":1, "Mode":"", "Word":""}
    data.Lobbies.push(newLobby)
    fs.writeFile('Lobbies.json', JSON.stringify(data), 'utf8', function(err) {
        if (err) throw err;
    });
}

function lobbyAvailable(name) {
    let rawdata = fs.readFileSync('Lobbies.json');
    let data = JSON.parse(rawdata);
    for (let i = 0; i < data.Lobbies.length; i++) {
        if (data.Lobbies[i].Name.toUpperCase() === name.toUpperCase()) {
            return false;
        }
    }
    return true;
}

module.exports = {
    lobbyUpdater,
    lobbyAvailable
};
</code>```

post Request on index.js

```<code>app.post('/newLobby', (req, res) => {
  console.log("Lobby Name:", req.body.lobbyName);
  console.log("Lobby Password:", req.body.lobbyPassword);
  const jsonWorker = require('./jsonWorker');
  if (jsonWorker.lobbyAvailable(req.body.lobbyName)) {
    jsonWorker.lobbyUpdater(req.body.lobbyName, req.body.lobbyPassword);
  }
  else {
    res.sendStatus(403);
    console.log("Stopped A Lobby From Being Created");
  }
});
</code>```

Code from react that is being followed
<Link id="testLink" to="/Waiting-For-Players"><button id="submit" onClick={sendingRequest} className="WaitingForPlayers">Create Lobby</button></Link>

sendingRequest function

```<code>function sendingRequest(event) {
  event.preventDefault();
  $.post("http://localhost:4000/newLobby",
    {
        lobbyName: document.getElementById('lobbyName').value,
        lobbyPassword: document.getElementById('lobbyPassword').value
    },
    function (data, status) {
      console.log("Data", data);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      console.log("Error received:", errorThrown);
      console.log("Stopping the post request.");
      return;
    })
    .then(function() {
      // Follow the Link component
      let linkToUse = document.getElementById("testLink");
      window.location.assign(linkToUse.to);
      console.log("Testing")
    });
}
</code>```

My goal is to only have the Link be stopped if the post request throws a 403 forbidden since the lobby name would have already been in the json. The link should go through otherwise. I believe that the issue is that the .then function isn't going through as the console.log isn't showing up but I am really not sure why it isn't working. Any help would be appreciated thanks!

Body:
Lobbies.json
{"Lobbies":[]}

jsonWorker.js

const fs = require('fs');

function lobbyUpdater(name, password) {
    let rawdata = fs.readFileSync('Lobbies.json');
    let data = JSON.parse(rawdata);
    // data.Lobbies.length = 0; // Remove this for production
    let newLobby = {"Name":name, "Password":password, "Players":1, "Mode":"", "Word":""}
    data.Lobbies.push(newLobby)
    fs.writeFile('Lobbies.json', JSON.stringify(data), 'utf8', function(err) {
        if (err) throw err;
    });
}

function lobbyAvailable(name) {
    let rawdata = fs.readFileSync('Lobbies.json');
    let data = JSON.parse(rawdata);
    for (let i = 0; i < data.Lobbies.length; i++) {
        if (data.Lobbies[i].Name.toUpperCase() === name.toUpperCase()) {
            return false;
        }
    }
    return true;
}

module.exports = {
    lobbyUpdater,
    lobbyAvailable
};

post Request on index.js

app.post('/newLobby', (req, res) => {
  console.log("Lobby Name:", req.body.lobbyName);
  console.log("Lobby Password:", req.body.lobbyPassword);
  const jsonWorker = require('./jsonWorker');
  if (jsonWorker.lobbyAvailable(req.body.lobbyName)) {
    jsonWorker.lobbyUpdater(req.body.lobbyName, req.body.lobbyPassword);
  }
  else {
    res.sendStatus(403);
    console.log("Stopped A Lobby From Being Created");
  }
});

Code from react that is being followed
<Link id="testLink" to="/Waiting-For-Players"><button id="submit" onClick={sendingRequest} className="WaitingForPlayers">Create Lobby</button></Link>

sendingRequest function

function sendingRequest(event) {
  event.preventDefault();
  $.post("http://localhost:4000/newLobby",
    {
        lobbyName: document.getElementById('lobbyName').value,
        lobbyPassword: document.getElementById('lobbyPassword').value
    },
    function (data, status) {
      console.log("Data", data);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      console.log("Error received:", errorThrown);
      console.log("Stopping the post request.");
      return;
    })
    .then(function() {
      // Follow the Link component
      let linkToUse = document.getElementById("testLink");
      window.location.assign(linkToUse.to);
      console.log("Testing")
    });
}

My goal is to only have the Link be stopped if the post request throws a 403 forbidden since the lobby name would have already been in the json. The link should go through otherwise. I believe that the issue is that the .then function isn't going through as the console.log isn't showing up but I am really not sure why it isn't working. Any help would be appreciated thanks!


问:
How can I set height automatically when using swiper in flutter?
I am using the swiper with the height of the container fixed as follows, but I want to make the height value automatically adjust according to the contents inside the swiper.</p>
```<code>Container(
    height: 220,
    child: Swiper(
        itemBuilder: (BuildContext context, int index) {
            return Container() //content
        }
    )
)
</code>```

Body:
I am using the swiper with the height of the container fixed as follows, but I want to make the height value automatically adjust according to the contents inside the swiper.

Container(
    height: 220,
    child: Swiper(
        itemBuilder: (BuildContext context, int index) {
            return Container() //content
        }
    )
)


问:
Invalid scheme, expected connection string to start with "mongodb:" or "mongodb+srv://
Deploying my API then attempting to send a GET request to the DB results in Runtime.UnhandledPromiseRejection Invalid scheme, expected connection string to start with "mongodb:" or "mongodb+srv://

My db.js

```<code>import mongoose from "mongoose";
mongoose.Promise = global.Promise;
mongoose.set("strictQuery", false);

let connection_uri = process.env.MONGODB_URI;
let cachedMongoConn = null;

export const connectToDatabase = () => {
  return new Promise((resolve, reject) => {
    // mongoose.Promise = global.Promise;
    mongoose.connection
      .on("error", (error) => {
        console.log("Error: connection to DB failed");
        reject(error);
      })
      .on("close", () => {
        console.log("Error: Connection to DB lost");
        process.exit(1);
      })
      // Connected to DB
      .once("open", () => {
        // Display connection information
        const infos = mongoose.connections;

        infos.map((info) =>
          console.log(`Connected to ${info.host}:${info.port}/${info.name}`)
        );
        // Return successful promise
        resolve(cachedMongoConn);
      });
    if (!cachedMongoConn) {
      cachedMongoConn = mongoose.connect(connection_uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        connectTimeoutMS: 60000,
        bufferCommands: false,
      });
    } else {
      console.log("MongoDB: using cached database instance");
      resolve(cachedMongoConn);
    }
  });
};
</code>```

.env

```<code>MONGODB_URI=mongodb+srv://Username:Password:...
</code>```

Everything "looks" correct and the connection string in the .env file is in the right format. So I'm not sure what the issue is.

Any help you can provide would be greatly appreciated.

Body:
Deploying my API then attempting to send a GET request to the DB results in Runtime.UnhandledPromiseRejection Invalid scheme, expected connection string to start with "mongodb:" or "mongodb+srv://

My db.js

import mongoose from "mongoose";
mongoose.Promise = global.Promise;
mongoose.set("strictQuery", false);

let connection_uri = process.env.MONGODB_URI;
let cachedMongoConn = null;

export const connectToDatabase = () => {
  return new Promise((resolve, reject) => {
    // mongoose.Promise = global.Promise;
    mongoose.connection
      .on("error", (error) => {
        console.log("Error: connection to DB failed");
        reject(error);
      })
      .on("close", () => {
        console.log("Error: Connection to DB lost");
        process.exit(1);
      })
      // Connected to DB
      .once("open", () => {
        // Display connection information
        const infos = mongoose.connections;

        infos.map((info) =>
          console.log(`Connected to ${info.host}:${info.port}/${info.name}`)
        );
        // Return successful promise
        resolve(cachedMongoConn);
      });
    if (!cachedMongoConn) {
      cachedMongoConn = mongoose.connect(connection_uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        connectTimeoutMS: 60000,
        bufferCommands: false,
      });
    } else {
      console.log("MongoDB: using cached database instance");
      resolve(cachedMongoConn);
    }
  });
};

.env

MONGODB_URI=mongodb+srv://Username:Password:...

Everything "looks" correct and the connection string in the .env file is in the right format. So I'm not sure what the issue is.

Any help you can provide would be greatly appreciated.


问:
spawn UNKNOWN at ChildProcess.spawn
I got this error, now I don't know how to fix it.
enter image description here

I want to find a way to fix it

Title: spawn UNKNOWN at ChildProcess.spawn


问:
Why does cv2.SimpleBlobDetector outline extra whitespace only on one side of a blob?
I'm using OpenCV's cv2 module in Python 3, using SimpleBlobDetector to detect a single blob in an image snippet, but sometimes it incorrectly outlines extra whitespace only on one side, and therefore gives an incorrect centre point for the blob.

Here's an example image:

Example blob with extra whitespace on top and left sides

Here's a code snippet to show what I'm doing:

```<code>import numpy
import cv2
import matplotlib.pyplot as plt

# img is a 2D numpy array containing an 8-bit grayscale image

img_area = img.shape[0] * img.shape[1]

detector = cv2.SimpleBlobDetector_create()
params = cv2.SimpleBlobDetector_Params()
params.minArea = round(img_area / 4)
keypoints = detector.detect(img)

img_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

keypoint_coords = keypoints[0].pt
blob_center_coords = (round(keypoint_coords[1]), round(keypoint_coords[0]))
img_keypoints[blob_center_coords[0],blob_center_coords[1]] = (255,0,0) #places a red dot at the keypoint coordinates

imshow(image_keypoints)
plt.show()`
</code>```

I'm guessing part of the problem is that the blob is against the edge of the image, but unfortunately, this is unavoidable in my analytical pipeline, so I need to be able to work around it. I've also tried playing with the SimpleBlobDetector params to no avail.

How do I make it shrink onto only the blob and ignore all that whitespace?

Body:
I'm using OpenCV's cv2 module in Python 3, using SimpleBlobDetector to detect a single blob in an image snippet, but sometimes it incorrectly outlines extra whitespace only on one side, and therefore gives an incorrect centre point for the blob.

Here's an example image:

Example blob with extra whitespace on top and left sides

Here's a code snippet to show what I'm doing:

import numpy
import cv2
import matplotlib.pyplot as plt

# img is a 2D numpy array containing an 8-bit grayscale image

img_area = img.shape[0] * img.shape[1]

detector = cv2.SimpleBlobDetector_create()
params = cv2.SimpleBlobDetector_Params()
params.minArea = round(img_area / 4)
keypoints = detector.detect(img)

img_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

keypoint_coords = keypoints[0].pt
blob_center_coords = (round(keypoint_coords[1]), round(keypoint_coords[0]))
img_keypoints[blob_center_coords[0],blob_center_coords[1]] = (255,0,0) #places a red dot at the keypoint coordinates

imshow(image_keypoints)
plt.show()`

I'm guessing part of the problem is that the blob is against the edge of the image, but unfortunately, this is unavoidable in my analytical pipeline, so I need to be able to work around it. I've also tried playing with the SimpleBlobDetector params to no avail.

How do I make it shrink onto only the blob and ignore all that whitespace?


问:
Google earth engine App: Change the chart based on the user's input
I would like to generate a chart time series of a region based on the user's drawing and the y-axis of a chart based on the user's selection. For example, when I clicked and drawed a polygon (step 1 on the image attached), then select the vege index such as EVI (step 2), then the app will generate an EVI chart. If I change the vege index into NDVI, then the app will generate a NDVI chart. However, my script automatically drawed a chart after step 1 without using step 2 or when I changed the select from NDVI to EVI, the chart did not update. How to fix this? Below are my script

```<code>var drawingTools = Map.drawingTools();
drawingTools.setShown(false);
while (drawingTools.layers().length() > 0) {
  var layer = drawingTools.layers().get(0);
  drawingTools.layers().remove(layer);
}
var dummyGeometry =
    ui.Map.GeometryLayer({geometries: null, name: 'geometry', color: 'red'});

drawingTools.layers().add(dummyGeometry);

function clearMap() {
  var mapLayers = Map.layers();
  if (mapLayers.length() > 0) {
    mapLayers.reset();
  }
}

function clearGeometry() {
  var layers = drawingTools.layers();
  layers.get(0).geometries().remove(layers.get(0).geometries().get(0));
}
function drawRectangle() {
  clearMap();
  clearGeometry();
  drawingTools.setShape('rectangle');
  drawingTools.draw();
}

function drawPolygon() {
  clearMap();
  clearGeometry();
  drawingTools.setShape('polygon');
  drawingTools.draw();
}

function drawPoint() {
  clearMap();
  clearGeometry();
  drawingTools.setShape('point');
  drawingTools.draw();
}

var symbol = {
  rectangle: '⬛',
  polygon: '',
  point: '',
};
var controlPanel = ui.Panel({
  widgets: [
    ui.Label('1. Select a drawing mode.'),
    ui.Button({
      label: symbol.rectangle + ' Rectangle',
      onClick: drawRectangle,
      style: {stretch: 'horizontal'}
    }),
    ui.Button({
      label: symbol.polygon + ' Polygon',
      onClick: drawPolygon,
      style: {stretch: 'horizontal'}
    }),
    ui.Button({
      label: symbol.point + ' Point',
      onClick: drawPoint,
      style: {stretch: 'horizontal'}
    }),
    ui.Label('2. Draw a geometry.'),
    ui.Label('3. Wait for chart to render.'),
    ui.Label(
        '4. Repeat 1-3 or edit/move\ngeometry for a new chart.',
        {whiteSpace: 'pre'})
  ],
  style: {position: 'bottom-left'},
  layout: null,
});
Map.add(controlPanel);

var chartPanel = ui.Panel({
  style:
      {height: '235px', width: '600px', position: 'bottom-right', shown: false}
});
Map.add(chartPanel);

function chartNdviTimeSeries() {
  // Make the chart panel visible the first time a geometry is drawn.
  if (!chartPanel.style().get('shown')) {
    chartPanel.style().set('shown', true);
  }

  var aoi = drawingTools.layers().get(0).getEeObject();

  var aoiFc = ee.FeatureCollection(aoi);

  var empty = ee.Image().byte();

  var outline = empty.paint({
    featureCollection: aoiFc,
    color: 1,
    width: 3
  });

  Map.addLayer(outline, {palette: 'red'}, 'AOI');
  clearGeometry();

  // Set the drawing mode back to null; turns drawing off.
  drawingTools.setShape(null);

  // Reduction scale is based on map scale to avoid memory/timeout errors.
  var mapScale = Map.getScale();
  var scale = mapScale > 5000 ? mapScale * 2 : 5000;

  // Chart NDVI time series for the selected area of interest.
  var chart = ui.Chart.image
                  .seriesByRegion({
                    imageCollection: ee.ImageCollection('MODIS/006/MOD13A2'),
                    regions: aoi,
                    reducer: ee.Reducer.mean(),
                    band:select_index.getValue(),
                    scale: scale,
                    xProperty: 'system:time_start'
                  })
                  .setOptions({
                    titlePostion: 'none',
                    legend: {position: 'none'},
                    hAxis: {title: 'Date'},
                    vAxis: {title: select_index.getValue()},
                    series: {0: {color: '23cba7'}}
                  });

  // Replace the existing chart in the chart panel with the new chart.
  chartPanel.widgets().reset([chart]);
}

// Index set-up
var label_index= ui.Label('Select vege index');
var index=['NDVI','EVI'];
var select_index=ui.Select({
  items:Object.values(index),
  onChange: chartNdviTimeSeries
});

Map.add(ui.Panel([label_index,select_index], ui.Panel.Layout.flow('horizontal')));
drawingTools.onDraw(ui.util.debounce(chartNdviTimeSeries, 500));
drawingTools.onEdit(ui.util.debounce(chartNdviTimeSeries, 500));
</code>```

My script code is in the link:

https://code.earthengine.google.com/fcc81cfebae226157ba7dc4e67db4851

Body:
I would like to generate a chart time series of a region based on the user's drawing and the y-axis of a chart based on the user's selection. For example, when I clicked and drawed a polygon (step 1 on the image attached), then select the vege index such as EVI (step 2), then the app will generate an EVI chart. If I change the vege index into NDVI, then the app will generate a NDVI chart. However, my script automatically drawed a chart after step 1 without using step 2 or when I changed the select from NDVI to EVI, the chart did not update. How to fix this? Below are my script

var drawingTools = Map.drawingTools();
drawingTools.setShown(false);
while (drawingTools.layers().length() > 0) {
  var layer = drawingTools.layers().get(0);
  drawingTools.layers().remove(layer);
}
var dummyGeometry =
    ui.Map.GeometryLayer({geometries: null, name: 'geometry', color: 'red'});

drawingTools.layers().add(dummyGeometry);

function clearMap() {
  var mapLayers = Map.layers();
  if (mapLayers.length() > 0) {
    mapLayers.reset();
  }
}

function clearGeometry() {
  var layers = drawingTools.layers();
  layers.get(0).geometries().remove(layers.get(0).geometries().get(0));
}
function drawRectangle() {
  clearMap();
  clearGeometry();
  drawingTools.setShape('rectangle');
  drawingTools.draw();
}

function drawPolygon() {
  clearMap();
  clearGeometry();
  drawingTools.setShape('polygon');
  drawingTools.draw();
}

function drawPoint() {
  clearMap();
  clearGeometry();
  drawingTools.setShape('point');
  drawingTools.draw();
}

var symbol = {
  rectangle: '⬛',
  polygon: '',
  point: '',
};
var controlPanel = ui.Panel({
  widgets: [
    ui.Label('1. Select a drawing mode.'),
    ui.Button({
      label: symbol.rectangle + ' Rectangle',
      onClick: drawRectangle,
      style: {stretch: 'horizontal'}
    }),
    ui.Button({
      label: symbol.polygon + ' Polygon',
      onClick: drawPolygon,
      style: {stretch: 'horizontal'}
    }),
    ui.Button({
      label: symbol.point + ' Point',
      onClick: drawPoint,
      style: {stretch: 'horizontal'}
    }),
    ui.Label('2. Draw a geometry.'),
    ui.Label('3. Wait for chart to render.'),
    ui.Label(
        '4. Repeat 1-3 or edit/move\ngeometry for a new chart.',
        {whiteSpace: 'pre'})
  ],
  style: {position: 'bottom-left'},
  layout: null,
});
Map.add(controlPanel);

var chartPanel = ui.Panel({
  style:
      {height: '235px', width: '600px', position: 'bottom-right', shown: false}
});
Map.add(chartPanel);

function chartNdviTimeSeries() {
  // Make the chart panel visible the first time a geometry is drawn.
  if (!chartPanel.style().get('shown')) {
    chartPanel.style().set('shown', true);
  }

  var aoi = drawingTools.layers().get(0).getEeObject();

  var aoiFc = ee.FeatureCollection(aoi);

  var empty = ee.Image().byte();

  var outline = empty.paint({
    featureCollection: aoiFc,
    color: 1,
    width: 3
  });

  Map.addLayer(outline, {palette: 'red'}, 'AOI');
  clearGeometry();

  // Set the drawing mode back to null; turns drawing off.
  drawingTools.setShape(null);

  // Reduction scale is based on map scale to avoid memory/timeout errors.
  var mapScale = Map.getScale();
  var scale = mapScale > 5000 ? mapScale * 2 : 5000;

  // Chart NDVI time series for the selected area of interest.
  var chart = ui.Chart.image
                  .seriesByRegion({
                    imageCollection: ee.ImageCollection('MODIS/006/MOD13A2'),
                    regions: aoi,
                    reducer: ee.Reducer.mean(),
                    band:select_index.getValue(),
                    scale: scale,
                    xProperty: 'system:time_start'
                  })
                  .setOptions({
                    titlePostion: 'none',
                    legend: {position: 'none'},
                    hAxis: {title: 'Date'},
                    vAxis: {title: select_index.getValue()},
                    series: {0: {color: '23cba7'}}
                  });

  // Replace the existing chart in the chart panel with the new chart.
  chartPanel.widgets().reset([chart]);
}

// Index set-up
var label_index= ui.Label('Select vege index');
var index=['NDVI','EVI'];
var select_index=ui.Select({
  items:Object.values(index),
  onChange: chartNdviTimeSeries
});

Map.add(ui.Panel([label_index,select_index], ui.Panel.Layout.flow('horizontal')));
drawingTools.onDraw(ui.util.debounce(chartNdviTimeSeries, 500));
drawingTools.onEdit(ui.util.debounce(chartNdviTimeSeries, 500));

My script code is in the link:

https://code.earthengine.google.com/fcc81cfebae226157ba7dc4e67db4851


问:
Why is the text overlapping in an infinite scroll animation on the X axis?
I'm trying to set up an infinite animation effect but the seems to overlap every time I add another row (green banner) and if the div is rotated at an angle. It looks fine if there is only one green banner and if it's straight but I'm not sure why it overlaps when there are multiple. Any help would be appreciated. Image is attached for reference.

section {
  position: relative;
  width: 100%;
  height: 42%;
  overflow: hidden;
}

section .scroll {
  display: flex;
  background-color: #99e836;
  transform: rotate(-5deg);
  margin: 8rem 0;
  width: 100vw;
  border: 2px solid white;
}

section .scroll div {
  color: white;
  font-size: 4em;
  white-space: nowrap;
  font-weight: 800;
  animation: animate 40s linear infinite;
}

section .scroll div:nth-child(2) {
  animation: animate2 40s linear infinite;
  animation-delay: -20s;
}

section .scroll div span {
  margin: 0 2rem;
}

.transparent {
  color: transparent;
  -webkit-text-stroke-width: 1.3px;
  -webkit-text-stroke-color: blue;
  font-weight: 600;
  &-no {
    color: black;
    font-weight: 500;
  }
}

@keyframes animate {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

@keyframes animate2 {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-200%);
  }
}

section .scroll2 {
  display: flex;
  background-color: #99e836;
  transform: rotate(8deg);
  width: 100vw;
  border: 2px solid white;
  position: absolute;
  top: 7.5rem;
}

section .scroll2 div {
  color: $primary-light;
  font-size: 4em;
  white-space: nowrap;
  font-weight: 800;
  animation: animate 40s linear infinite;
}

section .scroll2 div:nth-child(2) {
  animation: animate2 40s linear infinite;
  animation-delay: -20s;
}

section .scroll2 div span {
  margin: 0 2rem;
}

section .scroll.text1 {
  box-shadow: 0 5px 15px rgba(255, 255, 255, 0.3);
}

section .scroll2.text2 {
  box-shadow: 0 5px 15px rgba(255, 255, 255, 0.3);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div class="scroll text1">
    <div>
      <span class="transparent-no"> Available for Hire</span>
      <span class="transparent"> Available for Hire</span>
      <span class="transparent-no"> Available for Hire</span>
      <span class="transparent"> Available for Hire</span>
    </div>
    <div>
      <span class="transparent-no"> Available for Hire</span>
      <span class="transparent"> Available for Hire</span>
      <span class="transparent-no"> Available for Hire</span>
      <span class="transparent"> Available for Hire</span>
    </div>
  </div>
  <div class="scroll2 text2">
    <div>
      <span class="transparent-no"> Available for Hire</span>
      <span class="transparent"> Available for Hire</span>
      <span class="transparent-no"> Available for Hire</span>
      <span class="transparent"> Available for Hire</span>
    </div>
    <div>
      <span class="transparent-no"> Available for Hire</span>
      <span class="transparent"> Available for Hire</span>
      <span class="transparent-no"> Available for Hire</span>
      <span class="transparent"> Available for Hire</span>
    </div>
  </div>
</section></code>```

overlapping image

Body:
I'm trying to set up an infinite animation effect but the seems to overlap every time I add another row (green banner) and if the div is rotated at an angle. It looks fine if there is only one green banner and if it's straight but I'm not sure why it overlaps when there are multiple. Any help would be appreciated. Image is attached for reference.

section {
  position: relative;
  width: 100%;
  height: 42%;
  overflow: hidden;
}

section .scroll {
  display: flex;
  background-color: #99e836;
  transform: rotate(-5deg);
  margin: 8rem 0;
  width: 100vw;
  border: 2px solid white;
}

section .scroll div {
  color: white;
  font-size: 4em;
  white-space: nowrap;
  font-weight: 800;
  animation: animate 40s linear infinite;
}

section .scroll div:nth-child(2) {
  animation: animate2 40s linear infinite;
  animation-delay: -20s;
}

section .scroll div span {
  margin: 0 2rem;
}

.transparent {
  color: transparent;
  -webkit-text-stroke-width: 1.3px;
  -webkit-text-stroke-color: blue;
  font-weight: 600;
  &-no {
    color: black;
    font-weight: 500;
  }
}

@keyframes animate {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

@keyframes animate2 {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-200%);
  }
}

section .scroll2 {
  display: flex;
  background-color: #99e836;
  transform: rotate(8deg);
  width: 100vw;
  border: 2px solid white;
  position: absolute;
  top: 7.5rem;
}

section .scroll2 div {
  color: $primary-light;
  font-size: 4em;
  white-space: nowrap;
  font-weight: 800;
  animation: animate 40s linear infinite;
}

section .scroll2 div:nth-child(2) {
  animation: animate2 40s linear infinite;
  animation-delay: -20s;
}

section .scroll2 div span {
  margin: 0 2rem;
}

section .scroll.text1 {
  box-shadow: 0 5px 15px rgba(255, 255, 255, 0.3);
}

section .scroll2.text2 {
  box-shadow: 0 5px 15px rgba(255, 255, 255, 0.3);
}

       Available for Hire
       Available for Hire
       Available for Hire
       Available for Hire

       Available for Hire
       Available for Hire
       Available for Hire
       Available for Hire

       Available for Hire
       Available for Hire
       Available for Hire
       Available for Hire

       Available for Hire
       Available for Hire
       Available for Hire
       Available for Hire

overlapping image


问:
How can I replicate Ecplise's live-reloading of Java web apps resources on Tomcat
I'm trying to replicate the behavior of Eclipse live-reloading of the web resources of the web app deployed on Tomcat, when changes are made locally to the project files, but I'm not able to understand how it works.

I have a Java project that I deploy on Tomcat using Ecplise, simply running the Server in Eclipse.

If I make any changes to the Handlebars templates under [antProjectName]/WebContent/view as soon as Ecplise "notices" that the file have changed (eg. navigating in the Project explorer), it replicates the changes to the deployed web app under /eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/[antProjectName]/view, where Tomcat is running.

Refreshing the page in the browsers shows immediately the change.

I was thinking it might be triggered by the built, but not, since disabling the "Build project automatically" option does not inhibit this behavior.

The only thing particular I notices is that in the server.xml in /eclipse-workspace/Servers/Tomcat v7.0 Server at localhost-config/server.xml this line is present

```<code><Context docBase="[antProjectName]" path="/" reloadable="true" source="org.eclipse.jst.jee.server:[antProjectName]"/></Host>
</code>```

For what I found online:

Eclipse WTP adds a custom attribute source to the project related
 element in the server.xml of Tomcat which identifies the
source of the context (the actual project in the workspace which is
deployed to the particular server). This way Eclipse can correlate the
deployed webapplication with an project in the workspace.

I don't know if this is related.

Replicating the behavior by copying "manually" the files at every change is not an option for my set-up.

Body:
I'm trying to replicate the behavior of Eclipse live-reloading of the web resources of the web app deployed on Tomcat, when changes are made locally to the project files, but I'm not able to understand how it works.

I have a Java project that I deploy on Tomcat using Ecplise, simply running the Server in Eclipse.

If I make any changes to the Handlebars templates under [antProjectName]/WebContent/view as soon as Ecplise "notices" that the file have changed (eg. navigating in the Project explorer), it replicates the changes to the deployed web app under /eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/[antProjectName]/view, where Tomcat is running.

Refreshing the page in the browsers shows immediately the change.

I was thinking it might be triggered by the built, but not, since disabling the "Build project automatically" option does not inhibit this behavior.

The only thing particular I notices is that in the server.xml in /eclipse-workspace/Servers/Tomcat v7.0 Server at localhost-config/server.xml this line is present

<Context docBase="[antProjectName]" path="/" reloadable="true" source="org.eclipse.jst.jee.server:[antProjectName]"/></Host>

For what I found online:

Eclipse WTP adds a custom attribute source to the project related
 element in the server.xml of Tomcat which identifies the
source of the context (the actual project in the workspace which is
deployed to the particular server). This way Eclipse can correlate the
deployed webapplication with an project in the workspace.

I don't know if this is related.

Replicating the behavior by copying "manually" the files at every change is not an option for my set-up.


问:
Create pagination using vuejs
I want like to build a pagination as the picture shows

However, I had looked through the internet but there is no other examples that can give me some idea on building it. The pagination is almost same like Google's one. But  i cant find any related to the vuetify.

```<code><v-pagination
      v-model="page"
      :length="24"
      :withNextPrev="true"
      nextText="Next"
      prevText="Previous"
></v-pagination>

data() {
      return {
        page: 1,
      };
},
</code>```

Title: Create pagination using vuejs

Body:
I want like to build a pagination as the picture shows

However, I had looked through the internet but there is no other examples that can give me some idea on building it. The pagination is almost same like Google's one. But  i cant find any related to the vuetify.

<v-pagination
      v-model="page"
      :length="24"
      :withNextPrev="true"
      nextText="Next"
      prevText="Previous"
></v-pagination>

data() {
      return {
        page: 1,
      };
},


问:
Route 53 website endpoint adds trailing slash at the end of a URL; the new redirect url adds an unnecessary https prefix
I have three pages I'm trying to shorten the url for one of the pages. The person in my position before me successfully did one of the pages, I was able to do another one of the pages, but for some reason, the last page doesn't work. When I type in page.domain.org, it properly redirects to the domain.org/page for two of the pages, but not for one of them. I know this is not a problem with the content management system we use either.

I started off with creating the bucket in S3 and under Static Website Hosting, I made the hosting type as bucket hosting and added a redirecting rule. Under index document, I simply wrote index.html. I used the same code for the redirecting rules for all three pages when hosting a website, except just changing the ReplaceKeyWith part. I clicked on the website endpoint to see what comes up and instead of the url saying domain.org/example (the way it does for the other two pages) it comes up with domain.org/example/ and that gives a 404 error.

I also tried the Route 53 redirect as well and when I type in example.domain.org, what comes up in the url bar is https//domain.org/example/

I did the same steps for all of the pages, following what the person in my position before me did, but for whatever reason it doesn't work. Any suggestions that I should try?

```<code># Redirection rules
[
    {
        "Condition": {
            "KeyPrefixEquals": ""
        },
        "Redirect": {
            "HostName": "www.domain.org",
            "Protocol": "https",
            "ReplaceKeyWith": "example"
        }
    }
]
</code>```

Body:
I have three pages I'm trying to shorten the url for one of the pages. The person in my position before me successfully did one of the pages, I was able to do another one of the pages, but for some reason, the last page doesn't work. When I type in page.domain.org, it properly redirects to the domain.org/page for two of the pages, but not for one of them. I know this is not a problem with the content management system we use either.

I started off with creating the bucket in S3 and under Static Website Hosting, I made the hosting type as bucket hosting and added a redirecting rule. Under index document, I simply wrote index.html. I used the same code for the redirecting rules for all three pages when hosting a website, except just changing the ReplaceKeyWith part. I clicked on the website endpoint to see what comes up and instead of the url saying domain.org/example (the way it does for the other two pages) it comes up with domain.org/example/ and that gives a 404 error.

I also tried the Route 53 redirect as well and when I type in example.domain.org, what comes up in the url bar is https//domain.org/example/

I did the same steps for all of the pages, following what the person in my position before me did, but for whatever reason it doesn't work. Any suggestions that I should try?

# Redirection rules
[
    {
        "Condition": {
            "KeyPrefixEquals": ""
        },
        "Redirect": {
            "HostName": "www.domain.org",
            "Protocol": "https",
            "ReplaceKeyWith": "example"
        }
    }
]


问:
AWS DMS replication instance and target endpoint test connection failed
I am trying to start a replication task but for that I need the test connection to work between the target endpoint (S3) and the replication instance. Here's the error:

Test Endpoint failed: Application-Status: 1020912, Application-Message: N/A, Application-Detailed-Message: N/A

They're both on the same VPC

I tried granting permission to the role but it already had.


问:
C++: entering a float or char with std::cin for a int value causes undefined loop
Putting letters or decimal numbers in std::cin for int values causes infinite looping or code interruption

I'm writing a code but I'm having problems with user input options. Snippets like the following give me trouble.

```<code>int x;
do{
   std::cin >> x;
   // random code here
} while(x != y);
</code>```

I have no issues with the code, and it works perfectly. But a typo in input time (as in code) causes the program to crash, like inputting a float or a char (where an integer should be). Entering a letter (and sometimes, maybe a decimal number) causes the code to stay in the while loop indefinitely, ignoring the input and often terminating the code after a few seconds.

I have no idea how to introduce a solution to this kind of problem, as there are a few dozen entries with this problem, and maybe this solution would take up a few dozen lines, which means I would need at least a hundred lines to solve just a user typo.

How does the std::cin function work during this user input issue, and how can I solve this problem in a simple way that doesn't turn my code into 10 functional lines and 20 lines of typo test?

Thanks in advance!

Body:
Putting letters or decimal numbers in std::cin for int values causes infinite looping or code interruption

I'm writing a code but I'm having problems with user input options. Snippets like the following give me trouble.

int x;
do{
   std::cin >> x;
   // random code here
} while(x != y);

I have no issues with the code, and it works perfectly. But a typo in input time (as in code) causes the program to crash, like inputting a float or a char (where an integer should be). Entering a letter (and sometimes, maybe a decimal number) causes the code to stay in the while loop indefinitely, ignoring the input and often terminating the code after a few seconds.

I have no idea how to introduce a solution to this kind of problem, as there are a few dozen entries with this problem, and maybe this solution would take up a few dozen lines, which means I would need at least a hundred lines to solve just a user typo.

How does the std::cin function work during this user input issue, and how can I solve this problem in a simple way that doesn't turn my code into 10 functional lines and 20 lines of typo test?

Thanks in advance!


问:
detect change of status in textbox web.whatssap
I am trying through javascript code to activate the send button in the web.whatsapp chat
1.- when the text is empty, a microphone icon simply appears
2.- when you enter a text, change the icon to a send button
This happens when you write something and some event is fired that detects the change and activates the submit button I just want to replicate this

my code example :

window.InputEvent = window.Event || window.InputEvent;
var event = new InputEvent('input', {bubbles: true});
document.querySelector('#main > footer > div._2BU3P.tm2tP.copyable-area > div > span:nth-child(2) > div > div._2lMWa > div.p3_M1 > div > div.fd365im1.to2l77zo.bbv8nyr4.mwp4sxku.gfz4du6o.ag5g9lrv > p').textContent = "prueba";
document.querySelector('#main > footer > div._2BU3P.tm2tP.copyable-area > div > span:nth-child(2) > div > div._2lMWa > div.p3_M1 > div > div.fd365im1.to2l77zo.bbv8nyr4.mwp4sxku.gfz4du6o.ag5g9lrv > p')
textbox.dispatchEvent(event);

window.InputEvent = window.Event || window.InputEvent;
var event = new InputEvent('input', {bubbles: true});
document.querySelector('#main > footer > div._2BU3P.tm2tP.copyable-area > div > span:nth-child(2) > div > div._2lMWa > div.p3_M1 > div > div.fd365im1.to2l77zo.bbv8nyr4.mwp4sxku.gfz4du6o.ag5g9lrv > p').textContent = "prueba";
document.querySelector('#main > footer > div._2BU3P.tm2tP.copyable-area > div > span:nth-child(2) > div > div._2lMWa > div.p3_M1 > div > div.fd365im1.to2l77zo.bbv8nyr4.mwp4sxku.gfz4du6o.ag5g9lrv > p')
textbox.dispatchEvent(event);
```


问:
Looking for ways to extract useful data from whitespots list
Whitespots are products that customers are looking for but cannot yet find on bol.com.

The dataset is publicly available on: https://www.kaggle.com/datasets/elias070/bolcom-whitespots-20221018

130+K rows
Source:  partnerplatform bol com/nl/samendoorgroeien/ervaringen-uit-de-praktijk/verkoopkansen/
Last updated: 18 oktober 2022

8 columns:

```<code>Winkel => Head-category
Productgroep => Sub-category
Type => Whether its a specific product or a brand name
Merknaam => Brand name
Artikel => Product name
Verkooppotentie => Selling potential (defined by bol.com)
Publicatie whitespot => Recent toegevoegd means Recently added
</code>```

What are ways I can extract useful data with given columns? Because there no selling numbers or any other KPI defined in the data I am not sure how anyone could extract useful data. Thanks!

Body:
Whitespots are products that customers are looking for but cannot yet find on bol.com.

The dataset is publicly available on: https://www.kaggle.com/datasets/elias070/bolcom-whitespots-20221018

130+K rows
Source:  partnerplatform bol com/nl/samendoorgroeien/ervaringen-uit-de-praktijk/verkoopkansen/
Last updated: 18 oktober 2022

8 columns:

Winkel => Head-category
Productgroep => Sub-category
Type => Whether its a specific product or a brand name
Merknaam => Brand name
Artikel => Product name
Verkooppotentie => Selling potential (defined by bol.com)
Publicatie whitespot => Recent toegevoegd means Recently added

What are ways I can extract useful data with given columns? Because there no selling numbers or any other KPI defined in the data I am not sure how anyone could extract useful data. Thanks!


问:
How to set CMAKE_OSX_ARCHITECTURES in CMakeLists depending on debug or release configuration?
I want to set CMAKE_OSX_ARCHITECTURES to "arm64;x86_64" only if in release configuration, and I want to do that in CMakeLists (not on the command line), but I can't figure it out.

I tried:

```<code>set (CMAKE_OSX_ARCHITECTURES $<IF:$<CONFIG:Debug>, "", arm64;x86_64)
</code>```

but that fails.

The documentation says that it needs to be set before the project() call, which I'm doing.

Body:
I want to set CMAKE_OSX_ARCHITECTURES to "arm64;x86_64" only if in release configuration, and I want to do that in CMakeLists (not on the command line), but I can't figure it out.

I tried:

set (CMAKE_OSX_ARCHITECTURES $<IF:$<CONFIG:Debug>, "", arm64;x86_64)

but that fails.

The documentation says that it needs to be set before the project() call, which I'm doing.


问:
Does subscription of Azure Service Bus work like a single thread?
So, assume I have one topic and one subscription, and I might send several duplicate messages to the topic. Do I need to concern that multiple subscription threads might be running at the same time? It's ok if the subscription for the same message runs multiple times one by one.</p>


问:
C vprintf Modify va_list Argument
I'm trying to write a function that intermixes calls to vprintf with usages of the variadic arguments.  However, the behavior I am observing does not match my expectation.  The following is code that illustrates the problem:

```<code>static void variadicFunc(int a, ...)
{
    va_list funArgs;
    va_start(funArgs, a);

    printf("a: %d, ", a);
    vprintf("b: %d, ", funArgs);
    int c = va_arg(funArgs, int);
    printf("c: %d\n", c);

    va_end(funArgs);
}

void main()
{
    variadicFunc(1, 2, 3);
}
</code>```

I expected the above code to produce the string 1, 2, 3, but instead it produces 1, 2, 2 when executing on an ARM64 processor.  Is there some way to get the call to vprintf to modify the funArgs?

More Information:

The goal is to add support for custom format specifiers to a printf-like function.  Essentially, I am testing whether the format specifier is one of my custom types, and want to handle that logic myself.  All other format specifiers should go through the default logic.  E.g., if my custom format specifier is %M, then my expectation is that the following should be OK:

```<code>printfWrapper("%0*d%M", 5, 1, /* Args required by the %M specifier */);
</code>```

My expectation was that I could just let the OS format the "%0*d" specifier, which would consume two arguments from the variadic list.  I don't want to have to write code that needs to know how many arguments and of what type I need to advance the list; doing so basically requires me to rewrite the entire functionality of the printf function.  There must be some way to accomplish this without needing to rewrite existing functionality, but I can't figure out what that is.  Any help is greatly appreciated.

Title: C vprintf Modify va_list Argument

Body:
I'm trying to write a function that intermixes calls to vprintf with usages of the variadic arguments.  However, the behavior I am observing does not match my expectation.  The following is code that illustrates the problem:

static void variadicFunc(int a, ...)
{
    va_list funArgs;
    va_start(funArgs, a);

    printf("a: %d, ", a);
    vprintf("b: %d, ", funArgs);
    int c = va_arg(funArgs, int);
    printf("c: %d\n", c);

    va_end(funArgs);
}

void main()
{
    variadicFunc(1, 2, 3);
}

I expected the above code to produce the string 1, 2, 3, but instead it produces 1, 2, 2 when executing on an ARM64 processor.  Is there some way to get the call to vprintf to modify the funArgs?

More Information:

The goal is to add support for custom format specifiers to a printf-like function.  Essentially, I am testing whether the format specifier is one of my custom types, and want to handle that logic myself.  All other format specifiers should go through the default logic.  E.g., if my custom format specifier is %M, then my expectation is that the following should be OK:

printfWrapper("%0*d%M", 5, 1, /* Args required by the %M specifier */);

My expectation was that I could just let the OS format the "%0*d" specifier, which would consume two arguments from the variadic list.  I don't want to have to write code that needs to know how many arguments and of what type I need to advance the list; doing so basically requires me to rewrite the entire functionality of the printf function.  There must be some way to accomplish this without needing to rewrite existing functionality, but I can't figure out what that is.  Any help is greatly appreciated.


问:
Printing PDF from .repx file so slowly
I'm using DevExpress XtraReports on .NET to print a pdf file with flow: Take data from database -> Fill data to .repx file (a printing file model) -> export to pdf. I felt it so slowly while just printing only one page pdf file.

If i print a one page pdf file, it took 2-3 seconds to print. So if I print a multipage pdf file, the printing time increase with number of page and too slow with large pdf.

So please anyone here have a solution for this problem.
Thanks so much!

Title: Printing PDF from .repx file so slowly


问:
Webpack fails to build stoplight prism client
I know this is not related to stoplight or webpack directly but something to do with a package called json-schema-faker which fails to build. Here's how to reproduce. A basic js script to initialise the stoplight client and make a request.

import { getHttpOperationsFromSpec } from '@stoplight/prism-cli/dist/operations'
import { createClientFromOperations } from '@stoplight/prism-http/dist/client'

export const main = async () => {
  const operations = await getHttpOperationsFromSpec('./spec.yaml')
  const client = createClientFromOperations(operations, {
    mock: true
  })

  const result = await client.request('/documents', { method: 'get' })
  console.log(result)
}

main()
  .then(() => console.log('done'))
  .catch(console.error)

```
<p>Save it as <code>prism.js</code> and create a <code>webpack.config.js</code> file with the following content:</p>
<pre class="lang-js prettyprint-override"><code>const path = require('path')

module.exports = {
  mode: 'development',
  entry: './src/prism.js',
  output: {
    path: path.resolve(__dirname, 'dist')
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.jsx', '.js', '...']
  },
  target: 'node'
}
</code>```

Build the bundle by running npx webpack build and after build executing the program fails with the following error

$ node dist/main.js
webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/generator/JSONSchema.js?:12
jsf.extend('faker', () => faker_1.default);
    ^

TypeError: jsf.extend is not a function
    at eval (webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/generator/JSONSchema.js?:12:5)
    at ./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/generator/JSONSchema.js (/Users/dina//webpack-issue/dist/main.js:21321:1)
    at __webpack_require__ (/Users/dina//webpack-issue/dist/main.js:29241:42)
    at eval (webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/index.js?:19:22)
    at ./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/index.js (/Users/dina//webpack-issue/dist/main.js:21332:1)
    at __webpack_require__ (/Users/dina//webpack-issue/dist/main.js:29241:42)
    at eval (webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/forwarder/index.js?:14:18)
    at ./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/forwarder/index.js (/Users/dina//webpack-issue/dist/main.js:21255:1)
    at __webpack_require__ (/Users/dina//webpack-issue/dist/main.js:29241:42)
    at eval (webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/index.js?:7:21)

```

Can anyone suggest a way forward?

Body:
I know this is not related to stoplight or webpack directly but something to do with a package called json-schema-faker which fails to build. Here's how to reproduce. A basic js script to initialise the stoplight client and make a request.

import { getHttpOperationsFromSpec } from '@stoplight/prism-cli/dist/operations'
import { createClientFromOperations } from '@stoplight/prism-http/dist/client'

export const main = async () => {
  const operations = await getHttpOperationsFromSpec('./spec.yaml')
  const client = createClientFromOperations(operations, {
    mock: true
  })

  const result = await client.request('/documents', { method: 'get' })
  console.log(result)
}

main()
  .then(() => console.log('done'))
  .catch(console.error)

Save it as prism.js and create a webpack.config.js file with the following content:

const path = require('path')

module.exports = {
  mode: 'development',
  entry: './src/prism.js',
  output: {
    path: path.resolve(__dirname, 'dist')
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.jsx', '.js', '...']
  },
  target: 'node'
}

Build the bundle by running npx webpack build and after build executing the program fails with the following error

$ node dist/main.js
webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/generator/JSONSchema.js?:12
jsf.extend('faker', () => faker_1.default);
    ^

TypeError: jsf.extend is not a function
    at eval (webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/generator/JSONSchema.js?:12:5)
    at ./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/generator/JSONSchema.js (/Users/dina//webpack-issue/dist/main.js:21321:1)
    at __webpack_require__ (/Users/dina//webpack-issue/dist/main.js:29241:42)
    at eval (webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/index.js?:19:22)
    at ./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/mocker/index.js (/Users/dina//webpack-issue/dist/main.js:21332:1)
    at __webpack_require__ (/Users/dina//webpack-issue/dist/main.js:29241:42)
    at eval (webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/forwarder/index.js?:14:18)
    at ./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/forwarder/index.js (/Users/dina//webpack-issue/dist/main.js:21255:1)
    at __webpack_require__ (/Users/dina//webpack-issue/dist/main.js:29241:42)
    at eval (webpack://my-webpack-project/./node_modules/.pnpm/@stoplight+prism-http@4.10.5/node_modules/@stoplight/prism-http/dist/index.js?:7:21)

Can anyone suggest a way forward?


问:
How to change column header in Elementor export leads to CSV?
I need a way to modify the exported csv/excel headers to other values.

The following code should do the trick, but its not working.

Seems not to get triggered at all - any idea why?

Using WP 6.1.1. Elementor+Pro latest, Hello Child theme. No other plugins.

```<code>function custom_form_field_headers( $headers, $form_id ) {
  // Replace the form field labels with the form field IDs
  foreach ( $headers as $key => $header ) {
    $field_id = 'testing_' . $key; // get_form_field_id_by_label( $header, $form_id );
    if ( $field_id ) {
      $headers[ $key ] = $field_id;
    }
  }
  error_log('elementor_pro/forms/csv_export_headers form id='. $form_id . '   headers='. print_r($headers,true)); // for debug purposes
  return $headers;
}
add_filter( 'elementor_pro/forms/csv_export_headers', 'custom_form_field_headers', 10, 2 );
</code>```

Body:
I need a way to modify the exported csv/excel headers to other values.

The following code should do the trick, but its not working.

Seems not to get triggered at all - any idea why?

Using WP 6.1.1. Elementor+Pro latest, Hello Child theme. No other plugins.

function custom_form_field_headers( $headers, $form_id ) {
  // Replace the form field labels with the form field IDs
  foreach ( $headers as $key => $header ) {
    $field_id = 'testing_' . $key; // get_form_field_id_by_label( $header, $form_id );
    if ( $field_id ) {
      $headers[ $key ] = $field_id;
    }
  }
  error_log('elementor_pro/forms/csv_export_headers form id='. $form_id . '   headers='. print_r($headers,true)); // for debug purposes
  return $headers;
}
add_filter( 'elementor_pro/forms/csv_export_headers', 'custom_form_field_headers', 10, 2 );


问:
Py-installer-windows github action giving me /entrypoint.sh: line 42: cd: src: No such file or directory error
Here is the link: https://github.com/veryredpp/csquiz/actions/runs/3843300200/jobs/6545428953

if you know what is going on help would be appreciated.

Thanks in advance!


问:
What's the benefits of using sub-section in Assembly code?
As noted in Using as, there are two main benefits of using the subsection:

Group the objects together even though they are not contiguous in the assembler source code. such as .text 0 ...OTHERCODE... .text 0

Separate objects even though they are in the same section. such as .text 0 .text 1

Let's imagine there is no the concept of subsection:

For 1, I think just put them in the same section would be OK, like .text ...OTHERCODE... .text, the code would be grouped together even there are OTHERCODE.

For 2, I think just using a new section would be ok, like .text .newtext.

So what's the true benefits of designing a subsection concept in the Assembly code?


问:
Running Print To PDF in ASP.NET Core MVC hosted on IIS
We receive a lot of PDFs and some are protected and others are not. When a PDF file is protected we cannot even select words to comment. One known way around this is to print to pdf from the browser to create a new pdf file which is unprotected. This manual work is quite cumbersome for my users as they upload the pdfs to our ASP.NET Core MVC application. So I am trying to automate this process. I found this question and answers below:

How to programmatically print to PDF file without prompting for filename in C# using the Microsoft Print To PDF printer that comes with Windows 10

The first answer allows silent printing to pdf using a windows service(which our IIS server has windows print to pdf as an available printer). I have modified the code to run inside a test controller and it seems to draw an error. I am using a mac so I am unable to test this locally however when I push this to IIS the controller errors out. In IIS print spooling is disabled and I am guessing that is for security reasons? So could this be what is stopping my code or is there an issue with my code? If it is because print spooling is disabled is there anyway to use this functionality with print spooling disabled?

```<code>        public IActionResult RemovePDFPassword()
    {
        StreamReader streamToPrint;

        var RootPath = _env.ContentRootPath;
        var fileDirectory = Path.Combine(Directory.GetParent(RootPath).Parent.ToString(), "files");
        var filePathSource = Path.Combine(fileDirectory, "testDocToPrint.pdf");
        var filePathDestination = Path.Combine(fileDirectory, "test.pdf");

        streamToPrint = new StreamReader(filePathSource);

        System.Drawing.Printing.PrintDocument printDoc = new System.Drawing.Printing.PrintDocument
        {
            PrinterSettings = new PrinterSettings
            {
                PrinterName = "Microsoft Print to PDF",
                PrintToFile = true,
                PrintFileName = filePathDestination
            }
        };

        printDoc.Print();
        streamToPrint.Close();

        Console.ReadKey(true);

        return Ok("Success");
    }
</code>```

Body:
We receive a lot of PDFs and some are protected and others are not. When a PDF file is protected we cannot even select words to comment. One known way around this is to print to pdf from the browser to create a new pdf file which is unprotected. This manual work is quite cumbersome for my users as they upload the pdfs to our ASP.NET Core MVC application. So I am trying to automate this process. I found this question and answers below:

How to programmatically print to PDF file without prompting for filename in C# using the Microsoft Print To PDF printer that comes with Windows 10

The first answer allows silent printing to pdf using a windows service(which our IIS server has windows print to pdf as an available printer). I have modified the code to run inside a test controller and it seems to draw an error. I am using a mac so I am unable to test this locally however when I push this to IIS the controller errors out. In IIS print spooling is disabled and I am guessing that is for security reasons? So could this be what is stopping my code or is there an issue with my code? If it is because print spooling is disabled is there anyway to use this functionality with print spooling disabled?

        public IActionResult RemovePDFPassword()
    {
        StreamReader streamToPrint;

        var RootPath = _env.ContentRootPath;
        var fileDirectory = Path.Combine(Directory.GetParent(RootPath).Parent.ToString(), "files");
        var filePathSource = Path.Combine(fileDirectory, "testDocToPrint.pdf");
        var filePathDestination = Path.Combine(fileDirectory, "test.pdf");

        streamToPrint = new StreamReader(filePathSource);

        System.Drawing.Printing.PrintDocument printDoc = new System.Drawing.Printing.PrintDocument
        {
            PrinterSettings = new PrinterSettings
            {
                PrinterName = "Microsoft Print to PDF",
                PrintToFile = true,
                PrintFileName = filePathDestination
            }
        };

        printDoc.Print();
        streamToPrint.Close();

        Console.ReadKey(true);

        return Ok("Success");
    }


问:
How to use Windows binaries in MinGW shell
I recently installed SBCL 2.2.8 on my Windows, and also installed MSYS.
In Command Prompt(cmd) calling SBCL works well:

```<code>sbcl
This is SBCL 2.2.8, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
</code>```

But when I run the same command "sbcl" on MinGW64 shell, it can't find tha binary:

```<code>MINGW64 ~
$ sbcl
bash: sbcl: command not found
</code>```

Is there a way to, sort of, "import" the binaries installed on Windows into MSYS or MinGW system? How do I configure MinGW so that I can call Windows binaries in the MinGW shell?

Expected result:
calling a binary installed on Windows from MinGW:

```<code>MINGW64 ~
$ sbcl
This is SBCL 2.2.8, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
</code>```

Body:
I recently installed SBCL 2.2.8 on my Windows, and also installed MSYS.
In Command Prompt(cmd) calling SBCL works well:

sbcl
This is SBCL 2.2.8, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.

But when I run the same command "sbcl" on MinGW64 shell, it can't find tha binary:

MINGW64 ~
$ sbcl
bash: sbcl: command not found

Is there a way to, sort of, "import" the binaries installed on Windows into MSYS or MinGW system? How do I configure MinGW so that I can call Windows binaries in the MinGW shell?

Expected result:
calling a binary installed on Windows from MinGW:

MINGW64 ~
$ sbcl
This is SBCL 2.2.8, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.


问:
NoSuchElementError: no such element: Unable to locate element: Nodejs
I am running with a problem with this error "NoSuchElementError: no such element: Unable to locate element:", I have this test case which I am on,

`await driver.wait(until.elementIsVisible(driver.findElement(By.xpath('//*[@id="check_btn"]'))), 10000).click();

var testBtn = driver.wait(until.elementIsVisible(driver.findElement(By.xpath('//[@name="test_btn_1"]')))
var LocateBtn = driver.findElement(By.xpath('//[@name="communication_consent"]'))

```<code>if (LocatecBtn != undefined) {
  await testBtn.click();
} else {
  console.log("btn null");
}
</code>```

`

I am trying to get this to skip the second script and just continue onto the next one, I have tried if (LocatecBtn != null), and (LocatecBtn.isDisplayed != 0).

Expecting it to skip this execution and just go onto the next one.

Body:
I am running with a problem with this error "NoSuchElementError: no such element: Unable to locate element:", I have this test case which I am on,

`await driver.wait(until.elementIsVisible(driver.findElement(By.xpath('//*[@id="check_btn"]'))), 10000).click();

var testBtn = driver.wait(until.elementIsVisible(driver.findElement(By.xpath('//[@name="test_btn_1"]')))
var LocateBtn = driver.findElement(By.xpath('//[@name="communication_consent"]'))

if (LocatecBtn != undefined) {
  await testBtn.click();
} else {
  console.log("btn null");
}

`

I am trying to get this to skip the second script and just continue onto the next one, I have tried if (LocatecBtn != null), and (LocatecBtn.isDisplayed != 0).

Expecting it to skip this execution and just go onto the next one.


问:
MacOS: zsh: command not found: sdk after adding android sdk to path
I'm following some tutorials of setting up android sdk in MacOS command line, and no matter what I tried it doesn't seems to add the commands android or sdk to the path

I already have the following in my ~/.zshrc

```<code>export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools
</code>```

I also tried export ANDROID_HOME="~/Library/Android/sdk as the first line or export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools, but nothing seems to work.

Any help would be appreciated

I've tried editing the ~/.zshrc file in various way, yet the command sdk or android still isn't in the PATH as the tutorials suggested

Body:
I'm following some tutorials of setting up android sdk in MacOS command line, and no matter what I tried it doesn't seems to add the commands android or sdk to the path

I already have the following in my ~/.zshrc

export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools

I also tried export ANDROID_HOME="~/Library/Android/sdk as the first line or export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools, but nothing seems to work.

Any help would be appreciated

I've tried editing the ~/.zshrc file in various way, yet the command sdk or android still isn't in the PATH as the tutorials suggested