问:
Apache Flink issue when defining a StreamTableEnvironment object
I'm coding a Java project to create a table within a Dockerized MySQL database using the Apache Flink API. As provided by the doc, I coded the following lines of code in order to define a streaming environment:

```<code>StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env); //<== runtime error
</code>```

After typed docker-compose build and docker-compose up, the script hangs in a couple of seconds for this reason:

Exception in thread "main" org.apache.flink.table.api.TableException: Could not instantiate the executor. Make sure a planner module is on the classpath

and after tens of rows, the runtime error is primarly driven by:

app_1 | Caused by: org.apache.flink.table.api.ValidationException: Could not find any factories that implement 'org.apache.flink.table.delegation.ExecutorFactory' in the classpath.

as if the program was unable to link the proper dependency or something like that. The pom.xml file I've used is provided below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>first-stream</artifactId>
    <version>maven-project</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

  <dependencies>

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-java_2.12</artifactId>
            <version>1.14.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-java</artifactId>
            <version>1.14.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-api</artifactId>
           <version>1.7.25</version>
       </dependency>

       <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-jdbc_2.12</artifactId>
            <version>1.14.2</version>
        </dependency>

       <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
       </dependency>

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-clients_2.12</artifactId>
            <version>1.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.13.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.13.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-jdbc</artifactId>
            <version>1.0.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>

        <dependency>
          <groupId>org.apache.flink</groupId>
          <artifactId>flink-table-api-java-bridge_2.11</artifactId>
          <version>1.14.2</version>
        </dependency>

        <dependency>
          <groupId>org.apache.flink</groupId>
          <artifactId>flink-table-planner_2.11</artifactId>
          <version>1.14.2</version>
        </dependency>

        <dependency>
          <groupId>org.apache.flink</groupId>
          <artifactId>flink-streaming-scala_2.11</artifactId>
          <version>1.14.2</version>
        </dependency>

        <dependency>
          <groupId>org.apache.flink</groupId>
          <artifactId>flink-table-common</artifactId>
          <version>1.14.2</version>
        </dependency>

  </dependencies>

    <build>
      <plugins>
            <plugin>
                 <artifactId>maven-assembly-plugin</artifactId>
                 <executions>
                     <execution>
                          <phase>package</phase>
                          <goals>
                              <goal>single</goal>
                          </goals>
                      </execution>
                  </executions>
                  <configuration>

                       <archive>
                           <manifest>
                                 <mainClass>com.example.first_stream.WindowWordCount</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                           <descriptorRef>jar-with-dependencies</descriptorRef>
                      </descriptorRefs>
                 </configuration>

         </plugin>
   </plugins>

    </build>

</project>

```
<p>while Java code is the following:</p>
<pre class="lang-java prettyprint-override"><code>package com.example.first_stream;

import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.api.java.typeutils.TypeExtractor;

public class WindowWordCount {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        env.execute();
    }
}
</code>```

After many attempts I haven't identified the reason why it crashes, neither from the doc nor double-checking the Maven pom.xml. Any idea on how to deal with this situation? Thanks.

答: You need to add flink-table-planner library in your classpath.</p>

Body:
I'm coding a Java project to create a table within a Dockerized MySQL database using the Apache Flink API. As provided by the doc, I coded the following lines of code in order to define a streaming environment:

StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env); //<== runtime error

After typed docker-compose build and docker-compose up, the script hangs in a couple of seconds for this reason:

Exception in thread "main" org.apache.flink.table.api.TableException: Could not instantiate the executor. Make sure a planner module is on the classpath

and after tens of rows, the runtime error is primarly driven by:

app_1 | Caused by: org.apache.flink.table.api.ValidationException: Could not find any factories that implement 'org.apache.flink.table.delegation.ExecutorFactory' in the classpath.

as if the program was unable to link the proper dependency or something like that. The pom.xml file I've used is provided below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>first-stream</artifactId>
    <version>maven-project</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

  <dependencies>

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-java_2.12</artifactId>
            <version>1.14.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-java</artifactId>
            <version>1.14.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-api</artifactId>
           <version>1.7.25</version>
       </dependency>

       <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-jdbc_2.12</artifactId>
            <version>1.14.2</version>
        </dependency>

       <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
       </dependency>

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-clients_2.12</artifactId>
            <version>1.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.13.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.13.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-jdbc</artifactId>
            <version>1.0.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>

        <dependency>
          <groupId>org.apache.flink</groupId>
          <artifactId>flink-table-api-java-bridge_2.11</artifactId>
          <version>1.14.2</version>
        </dependency>

        <dependency>
          <groupId>org.apache.flink</groupId>
          <artifactId>flink-table-planner_2.11</artifactId>
          <version>1.14.2</version>
        </dependency>

        <dependency>
          <groupId>org.apache.flink</groupId>
          <artifactId>flink-streaming-scala_2.11</artifactId>
          <version>1.14.2</version>
        </dependency>

        <dependency>
          <groupId>org.apache.flink</groupId>
          <artifactId>flink-table-common</artifactId>
          <version>1.14.2</version>
        </dependency>

  </dependencies>

    <build>
      <plugins>
            <plugin>
                 <artifactId>maven-assembly-plugin</artifactId>
                 <executions>
                     <execution>
                          <phase>package</phase>
                          <goals>
                              <goal>single</goal>
                          </goals>
                      </execution>
                  </executions>
                  <configuration>

                       <archive>
                           <manifest>
                                 <mainClass>com.example.first_stream.WindowWordCount</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                           <descriptorRef>jar-with-dependencies</descriptorRef>
                      </descriptorRefs>
                 </configuration>

         </plugin>
   </plugins>

    </build>

</project>

while Java code is the following:

package com.example.first_stream;

import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.api.java.typeutils.TypeExtractor;

public class WindowWordCount {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        env.execute();
    }
}

After many attempts I haven't identified the reason why it crashes, neither from the doc nor double-checking the Maven pom.xml. Any idea on how to deal with this situation? Thanks.


来源: stackexchange

问:
validate special characters by negating unicode letters with regex pattern?
This regex: \p{L}+ matches these characters "ASKJKSDJKDSJÄÖÅüé" of the example string "ASKJKSDJK_-.;,DSJÄÖÅ!”#€%&/()=?`¨’<>üé" which is great but is the exact opposite of what I want. Which leads me to negating regexes.

Goal:

I want to match any and all characters that are not a letter nor a number in multiple languages.

Could a negative regex be a natural direction for this?

I should mention one intended use for the regex I'd like to find is to validate passwords for the rule:

that it needs to contain at least one special character, which I
define as not being a number nor a letter.

It would seem defining ranges of special characters should be avoided if possible, because why limit the possibilities? Thus my definition. I assume there could be some problems with such a wide definition, but it is a first step.

If you have some suggestions for a better solution I'm giving below or just have some thoughts on the subject, I'm sure I'm not the only one that would like to learn about it. Thanks.

Note I'm using double \\ in the Java code. Platform is Java 11.

答:
So after having read similar, though not identical questions and some equally great answers, I came up with this solution: (?=\P{L})(?=\P{N}) meaning match both not letters and not numbers. Even if I'm asserting numbers separately I need to negate both to meet the specification of special characters (See question).

This is making use of a non-consuming regular expression with the parentheses and the?=, first matching the expression in the first parenthesis and after that continue to match the whole in the second. Thanks to @Jason Cohen for this detail in the Regular Expressions: Is there an AND operator? discussion.

The upper case P in \P{L} and \P{N} expresses the "not belonging to a category" in Unicode Categories, where the uppercase P means "not", i e the opposite of a lowercase p.

It's not perfect for a real world solution, but works as a starting point at least. Note I'm using double \\ in the Java code. Platform is Java 11.

ContentLicense: CC BY-SA 4.0


问:
Android Manifest permissions issue
I have an app where im using uses-permission tags in the AndroidManifest.xml to give some permissions to my app, eg CAMERA. But when i check the permissions through my phone's settings all the given permissions are denied and i have to manually change it to allow. What could be wrong? Thanks!

答:
Since android 12 granting permissions in manifest isn't enough imo. Check out:

https://developer.android.com/training/permissions/requesting

Title: Android Manifest permissions issue


问:
Get data from file using ajax
I'm trying to do this scenario .
If folder is empty then return false else return true .
To do that i tried this

```<code>function downloadExcel() {
// Mu folder path
var folder="D:/output";
if (result.isConfirmed) {
                    $.ajax({
                    type: 'POST',
                    url: 'check_file.php',
                    data: {
                        folder: folder
                    },
                    cache: false,
                    success: function(result){
                        if(result==false)
                        {
                            Swal.fire(
                                    'execution success '
                            );
                        }
                        else
                        {
                            Swal.fire(
                                'extraction failed '
                            );
                        }

                },
                error: function(result){

                   console.log("Error request Ajax");
                }
                });

                refresh();

            } else if (
                result.dismiss === Swal.DismissReason.cancel

</code>```

my php file to render the data :: check_file.php

```<code><?php
if (!empty($_POST["folder"])) {
$dir = $_POST['folder'];
}

if (is_dir_empty($dir)) {
echo "the folder is empty";
$result=false;

}else{
 echo "the folder is NOT empty";
 $result=true;
}

return $result;

function is_dir_empty($dir) {
if (!is_readable($dir)) return null;
return (count(scandir($dir)) == 2);
}

?>
</code>```

When i run my check_file.php the check if directory is empty or not works fine .

But when i try the the $result variable there something gone wrong about my code

The $result variable is always empty

答:
You're never echoing $result - and even if you did, echoing a boolean false doesn't actually produce any visible output. Using return to end the main part of a script isn't necessary, doesn't really make much sense and certainly doesn't produce any output.

The things you are echoing consist of neither true nor false, so obviously the JS code won't match those either.

To allow the JS to detect a truth-y or false-y value accurately, it's better to output numeric 0 or 1 than strings.

As an additional point, it would make sense not to try and use $dir unless it's been populated.

This version should help you (note that if there's no value in $_POST["folder"] it won't output anything - you might want to add something extra to deal with that, but I'll leave it up to you):

```<code><?php
if (!empty($_POST["folder"]))
{
  $dir = $_POST['folder'];
  $result;

  if (is_dir_empty($dir)) $result = 0;
  else $result = 1;

  echo $result;
}

function is_dir_empty($dir) {
  if (!is_readable($dir)) return null;
  return (count(scandir($dir)) == 2);
}
?>
</code>```

Title: Get data from file using ajax

Body:
I'm trying to do this scenario .
If folder is empty then return false else return true .
To do that i tried this

function downloadExcel() {
// Mu folder path
var folder="D:/output";
if (result.isConfirmed) {
                    $.ajax({
                    type: 'POST',
                    url: 'check_file.php',
                    data: {
                        folder: folder
                    },
                    cache: false,
                    success: function(result){
                        if(result==false)
                        {
                            Swal.fire(
                                    'execution success '
                            );
                        }
                        else
                        {
                            Swal.fire(
                                'extraction failed '
                            );
                        }

                },
                error: function(result){

                   console.log("Error request Ajax");
                }
                });

                refresh();

            } else if (
                result.dismiss === Swal.DismissReason.cancel

my php file to render the data :: check_file.php

<?php
if (!empty($_POST["folder"])) {
$dir = $_POST['folder'];
}

if (is_dir_empty($dir)) {
echo "the folder is empty";
$result=false;

}else{
 echo "the folder is NOT empty";
 $result=true;
}

return $result;

function is_dir_empty($dir) {
if (!is_readable($dir)) return null;
return (count(scandir($dir)) == 2);
}

?>

When i run my check_file.php the check if directory is empty or not works fine .

But when i try the the $result variable there something gone wrong about my code

The $result variable is always empty

Body:
You're never echoing $result - and even if you did, echoing a boolean false doesn't actually produce any visible output. Using return to end the main part of a script isn't necessary, doesn't really make much sense and certainly doesn't produce any output.

The things you are echoing consist of neither true nor false, so obviously the JS code won't match those either.

To allow the JS to detect a truth-y or false-y value accurately, it's better to output numeric 0 or 1 than strings.

As an additional point, it would make sense not to try and use $dir unless it's been populated.

This version should help you (note that if there's no value in $_POST["folder"] it won't output anything - you might want to add something extra to deal with that, but I'll leave it up to you):

<?php
if (!empty($_POST["folder"]))
{
  $dir = $_POST['folder'];
  $result;

  if (is_dir_empty($dir)) $result = 0;
  else $result = 1;

  echo $result;
}

function is_dir_empty($dir) {
  if (!is_readable($dir)) return null;
  return (count(scandir($dir)) == 2);
}
?>


问:
PL/SQL counting by looping?
I have an assignment asking me to rewrite this PL/SQL code I wrote for a previous assignment:

```<code>DECLARE
    -- Variables used to count a, b, c, d, and f grades:
    na integer := 0;
    nb integer := 0;
    nc integer := 0;
    nd integer := 0;
    nf integer := 0;
BEGIN
    select count(*) into na
    from   gradeReport1
    where  grade = 'A';

    select count(*) into nb
    from   gradeReport1
    where  grade = 'B';

    select count(*) into nc
    from   gradeReport1
    where  grade = 'C';

    select count(*) into nd
    from   gradeReport1
    where  grade = 'D';

    select count(*) into nf
    from   gradeReport1
    where  grade = 'F';

    if na > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || na || ' A''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no As');
    end if;

    if nb > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || nb || ' B''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no Bs');
    end if;

    if nc > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || nc || ' C''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no Cs');
    end if;

    if nd > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || nd || ' D''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no Ds');
    end if;

    if nf > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || nf || ' F''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no Fs');
    end if;
END;
</code>```

All it does is search a table I made called gradeReport that stores studentID's and associates them with a grade. The PL/SQL counts all instances of a grade A through F. The question wants me to rewrite this solution using looping and VARRAYS. Could anyone give me a hint to help get the ball rolling for me? I've only been using PL/SQL for a few weeks and don't have much more than a basic understanding of the syntax so I'm completely lost and have no idea where to start.

Not looking for any answers here, just some ideas.

Thank You

答:
```<code>set SERVEROUTPUT ON
declare
type number_array is VARRAY(5) OF integer;
total integer :=0;
i number :=1;
begin
    numbers :=number_array(14,45,67,89,21);
    arr_size := numbers.count;

    FOR i in 1..arr_size loop
    total :=total+numbers(i);
 end loop;
 dbms_output.put_line('total-' || total);
end;
</code>```

here I want to count the number_array elements, but I can't get the correct answers. what is the problem with this?

ContentLicense: CC BY-SA 3.0

Title: PL/SQL counting by looping?

Body:
I have an assignment asking me to rewrite this PL/SQL code I wrote for a previous assignment:

DECLARE
    -- Variables used to count a, b, c, d, and f grades:
    na integer := 0;
    nb integer := 0;
    nc integer := 0;
    nd integer := 0;
    nf integer := 0;
BEGIN
    select count(*) into na
    from   gradeReport1
    where  grade = 'A';

    select count(*) into nb
    from   gradeReport1
    where  grade = 'B';

    select count(*) into nc
    from   gradeReport1
    where  grade = 'C';

    select count(*) into nd
    from   gradeReport1
    where  grade = 'D';

    select count(*) into nf
    from   gradeReport1
    where  grade = 'F';

    if na > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || na || ' A''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no As');
    end if;

    if nb > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || nb || ' B''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no Bs');
    end if;

    if nc > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || nc || ' C''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no Cs');
    end if;

    if nd > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || nd || ' D''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no Ds');
    end if;

    if nf > 0 then
        DBMS_OUTPUT.PUT_LINE('There are total ' || nf || ' F''s');
    else
        DBMS_OUTPUT.PUT_LINE('There are no Fs');
    end if;
END;

All it does is search a table I made called gradeReport that stores studentID's and associates them with a grade. The PL/SQL counts all instances of a grade A through F. The question wants me to rewrite this solution using looping and VARRAYS. Could anyone give me a hint to help get the ball rolling for me? I've only been using PL/SQL for a few weeks and don't have much more than a basic understanding of the syntax so I'm completely lost and have no idea where to start.

Not looking for any answers here, just some ideas.

Thank You

Body:
set SERVEROUTPUT ON
declare
type number_array is VARRAY(5) OF integer;
total integer :=0;
i number :=1;
begin
    numbers :=number_array(14,45,67,89,21);
    arr_size := numbers.count;

    FOR i in 1..arr_size loop
    total :=total+numbers(i);
 end loop;
 dbms_output.put_line('total-' || total);
end;

here I want to count the number_array elements, but I can't get the correct answers. what is the problem with this?


问:
I am very new to MySQL and don't know why there are dupliacte items being added to each row?
This is currently all that I have simply because I wanted to test adding items to a table, and making sure that said item wasn't a duplicate. I saw that if you add INSERT IGNORE that it supposedly stops the creation of duplicated items but in my case, that didn't work.</p>
```<code>CREATE TABLE IF NOT EXISTS testing (test0 TEXT, test10 TEXT);

INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
</code>```

答: INSERT IGNORE  just works in case of avoiding errors when you do the insert statement, it simply gonna let you insert the values because as I see there is not an identifier or   PRIMARY KEY  or   UNIQUE CONSTRAINT   to identify each element as unique that key is the one who cannot be duplicate, the "test01" and "test10" are just normal data types.

Body:
This is currently all that I have simply because I wanted to test adding items to a table, and making sure that said item wasn't a duplicate. I saw that if you add INSERT IGNORE that it supposedly stops the creation of duplicated items but in my case, that didn't work.

CREATE TABLE IF NOT EXISTS testing (test0 TEXT, test10 TEXT);

INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");
INSERT IGNORE INTO testing VALUES ("TEST1","TEST2");


问:
HTTP client not working for retrieving content from e-commerce website
I am trying to implement a web page watcher in Rust. Basic idea is that when certain string is not found in the page content, I would get a notification.

The basic logic is working for most situations but for certain e-commerce site (argos.co.uk in this case), it always return a page with "You don't have permission to access" in it.

The same page, of course, works fine with Safari. So I did Copy as cURL which gave me the following:

```<code>-X 'GET' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15'
</code>```

Running the copied cURL command works fine as expected. So I added those 2 headers in to my Rust code:

```<code>let cli = reqwest::Client::new();
let resp = cli
    .get(url)
    .header(USER_AGENT, r#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15"#)
    .header(ACCEPT, r#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"#)
    .send().await?;
</code>```

And I still got the same "you don't have permission..." page as above.

Using the above code with httpbin.org/get shows that Rust reqwest is indeed sending the right header. So I am at lost where to look for next. What could have gone wrong in my situation?

EDIT

I tried using the cURL command with httpbin as suggested below and got the following back.

```<code>   "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Host": "httpbin.org",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15",
    "X-Amzn-Trace-Id": "Root=1-62011d4b-5ea67cec2c79826d5d00e959"
</code>```

I don't believe X-Amzn-Trace-Id was sent by cURL but am more than willing to be proven wrong.

答:
As already suggested, this is most likely a basic header validation to prevent scraping. The following works for me:

```<code>use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let cli = reqwest::Client::new();
    let resp = cli
        .get("https://www.argos.co.uk/product/<YOUR_ID>")
        .header(reqwest::header::ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
        .header(reqwest::header::ACCEPT_ENCODING, "identity")
        .header(reqwest::header::ACCEPT_LANGUAGE, "en-US,en;q=0.5")
        .header(reqwest::header::USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0")
        .send().await?;

    println!("{:?}", resp.status());
    println!("{}", resp.text().await?);

    Ok(())
}
</code>```

Note that I've switched Accept-Encoding from gzip to identity. You can (and most likely should) use the gzip feature.

And of course make sure to respect the robots.txt and usage terms in regards to scraping.

Body:
I am trying to implement a web page watcher in Rust. Basic idea is that when certain string is not found in the page content, I would get a notification.

The basic logic is working for most situations but for certain e-commerce site (argos.co.uk in this case), it always return a page with "You don't have permission to access" in it.

The same page, of course, works fine with Safari. So I did Copy as cURL which gave me the following:

-X 'GET' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15'

Running the copied cURL command works fine as expected. So I added those 2 headers in to my Rust code:

let cli = reqwest::Client::new();
let resp = cli
    .get(url)
    .header(USER_AGENT, r#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15"#)
    .header(ACCEPT, r#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"#)
    .send().await?;

And I still got the same "you don't have permission..." page as above.

Using the above code with httpbin.org/get shows that Rust reqwest is indeed sending the right header. So I am at lost where to look for next. What could have gone wrong in my situation?

EDIT

I tried using the cURL command with httpbin as suggested below and got the following back.

   "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Host": "httpbin.org",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15",
    "X-Amzn-Trace-Id": "Root=1-62011d4b-5ea67cec2c79826d5d00e959"

I don't believe X-Amzn-Trace-Id was sent by cURL but am more than willing to be proven wrong.

Body:
As already suggested, this is most likely a basic header validation to prevent scraping. The following works for me:

use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let cli = reqwest::Client::new();
    let resp = cli
        .get("https://www.argos.co.uk/product/<YOUR_ID>")
        .header(reqwest::header::ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
        .header(reqwest::header::ACCEPT_ENCODING, "identity")
        .header(reqwest::header::ACCEPT_LANGUAGE, "en-US,en;q=0.5")
        .header(reqwest::header::USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0")
        .send().await?;

    println!("{:?}", resp.status());
    println!("{}", resp.text().await?);

    Ok(())
}

Note that I've switched Accept-Encoding from gzip to identity. You can (and most likely should) use the gzip feature.

And of course make sure to respect the robots.txt and usage terms in regards to scraping.


问:
YUI Tutorial not working
Why does this code from this YUI3 example not work for me?

HTML:

```<code><!-- The original body content is above -->
<div id="form_container">
    <form class="yui3-widget-bd" id="theme_form" action="#" method="get">
        <fieldset>
            <h3>Update Theme</h3>
            <label for="font_size">Font size:</label>
            <input type="text" size="3" id="font_size" value="16px">

            <label for="heading_color">Heading color:</label>
            <input type="text" size="12" id="heading_color" value="#005A9C">

            <label for="link_hover">Link hover backgound:</label>
            <input type="text" size="12" id="link_hover" value="#ffa">
        </fieldset>
        <input type="submit">
    </form>
</div>
</code>```

Javascript:

```<code>// Create a new YUI instance, requiring stylesheet, overlay, slider, and the
// dd-plugin to make the overlay draggable
YUI({
    filter: 'raw'
}).use("stylesheet", "overlay", "slider", "dd-plugin", function(Y) {

    var myStyleSheet = new Y.StyleSheet(),
        overlayContent = Y.one('#form_container'),
        overlay, slider, slider_container, fontSizeInput;

        // Create the Overlay, using the form container as the contentBox.
        // The form is assigned a class yui-widget-bd that will be automatically
        // discovered by Overlay to populate the Overlay's body section.
        // The overlay is positioned in the top right corner, but made draggable
        // using Y.Plugin.Drag, provided by the dd-plugin module.
        overlay = new Y.Overlay({
            srcNode: overlayContent,
            width: '225px',
            align: {
                points: [Y.WidgetPositionAlign.TR, Y.WidgetPositionAlign.TR]
            },
            plugins: [Y.Plugin.Drag]
        }).render();

    // Slider needs a parent element to have the sam skin class for UI skinning
    overlayContent.addClass('yui3-skin-sam');

    // Progressively enhance the font-size input with a Slider
    fontSizeInput = Y.one('#font_size');
    fontSizeInput.set('type', 'hidden');
    fontSizeInput.get('parentNode').insertBefore(
    Y.Node.create('6 <span></span> 36'), fontSizeInput);

    slider_container = fontSizeInput.previous("span");

    // Create a Slider to contain font size between 6px and 36px, using the
    // page's current font size as the initial value.
    // Set up an event subscriber during construction to update the replaced
    // input field's value and apply the change to the StyleSheet
    slider = new Y.Slider({
        length: '100px',
        min: 6,
        max: 36,
        value: parseInt(Y.one('body').getStyle('fontSize')) || 13,
        after: {
            valueChange: function(e) {
                var size = e.newVal + 'px';

                this.thumb.set('title', size);
                fontSizeInput.set('value', size);

                myStyleSheet.set('body', {
                    fontSize: size
                });
            }
        }
    }).render(slider_container);

    // The color inputs are assigned keyup listeners that will update the
    // StyleSheet if the current input value is a valid CSS color value
    // The heading input affects all h1s, h2, and h3s
    Y.on('keyup', function(e) {
        var color = this.get('value');

        console.log(color);

        if (isValidColor(color)) {
            console.log("Valid color", myStyleSheet);

            myStyleSheet.set('h1, h2, h3', {
                color: color
            });
        }
    }, '#heading_color');

    // The link hover affects the background color of links when they are
    // hovered. There is no way other than via stylesheet modification to
    // change pseudo-class styles.
    Y.on('keyup', function(e) {
        var color = this.get('value');

        if (isValidColor(color)) {
            myStyleSheet.set('a:hover', {
                backgroundColor: color
            });
        }
    }, '#link_hover');

    // Progressive form enhancement complete, now prevent the form from
    // submitting normally.
    Y.on('submit', function(e) {
        e.halt();
    }, '#theme_form');

    // A rudimentary validator to make sure we're not trying to set
    // invalid color values in StyleSheet.

    function isValidColor(v) {
        return /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(v) || /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/.test(v) || /^[a-z]{3,}$/i.test(v);
    }

});
</code>```

CSS:

```<code>/* For supporting browsers, the overlay is rendered semi-transparent with
* fancy rounded corners */
.yui3-overlay {
    background: rgba(128,128,128,0.3);
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    padding: 7px;
    cursor: move;
}

.yui3-overlay-content {
    background: rgba(205,205,205,0.3);
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    padding: 1px;
}

.yui3-overlay form {
    background: #f2fbff;
    border: 2px solid #fff;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    margin: 0;
    padding: 0;
    font-size: 13px;
}

.yui3-overlay fieldset {
    border: 1px solid #bcd;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    margin: 0;
    padding: 20px;
}

.yui3-overlay h3 {
    border-bottom: 2px solid #fff;
    color: #479;
    background: transparent;
    margin: 0;
    font-size: 175%;
}

.yui3-overlay label {
    display: block;
    margin: 1.3em 0 0.5ex;
    font-weight: bold;
    color: #003;
}

.yui3-overlay p {
    margin: 2em 0 0;
}

/* override the move cursor for the Slider */
.yui3-overlay .yui3-slider:hover {
    cursor: default;
}
</code>```

I just copied and pasted the code, can anyone help?

答:
This is not the best forum to do support debugging.

You're welcome to ask in the #yui channel on freenode rather than go through slow, back and forth debugging here.

Title: YUI Tutorial not working

Body:
Why does this code from this YUI3 example not work for me?

HTML:

    <form class="yui3-widget-bd" id="theme_form" action="#" method="get">
        <fieldset>

Update Theme

            Font size:
            <input type="text" size="3" id="font_size" value="16px">

            Heading color:
            <input type="text" size="12" id="heading_color" value="#005A9C">

            Link hover backgound:
            <input type="text" size="12" id="link_hover" value="#ffa">
        </fieldset>
        <input type="submit">
    </form>

Javascript:

// Create a new YUI instance, requiring stylesheet, overlay, slider, and the
// dd-plugin to make the overlay draggable
YUI({
    filter: 'raw'
}).use("stylesheet", "overlay", "slider", "dd-plugin", function(Y) {

    var myStyleSheet = new Y.StyleSheet(),
        overlayContent = Y.one('#form_container'),
        overlay, slider, slider_container, fontSizeInput;

        // Create the Overlay, using the form container as the contentBox.
        // The form is assigned a class yui-widget-bd that will be automatically
        // discovered by Overlay to populate the Overlay's body section.
        // The overlay is positioned in the top right corner, but made draggable
        // using Y.Plugin.Drag, provided by the dd-plugin module.
        overlay = new Y.Overlay({
            srcNode: overlayContent,
            width: '225px',
            align: {
                points: [Y.WidgetPositionAlign.TR, Y.WidgetPositionAlign.TR]
            },
            plugins: [Y.Plugin.Drag]
        }).render();

    // Slider needs a parent element to have the sam skin class for UI skinning
    overlayContent.addClass('yui3-skin-sam');

    // Progressively enhance the font-size input with a Slider
    fontSizeInput = Y.one('#font_size');
    fontSizeInput.set('type', 'hidden');
    fontSizeInput.get('parentNode').insertBefore(
    Y.Node.create('6  36'), fontSizeInput);

    slider_container = fontSizeInput.previous("span");

    // Create a Slider to contain font size between 6px and 36px, using the
    // page's current font size as the initial value.
    // Set up an event subscriber during construction to update the replaced
    // input field's value and apply the change to the StyleSheet
    slider = new Y.Slider({
        length: '100px',
        min: 6,
        max: 36,
        value: parseInt(Y.one('body').getStyle('fontSize')) || 13,
        after: {
            valueChange: function(e) {
                var size = e.newVal + 'px';

                this.thumb.set('title', size);
                fontSizeInput.set('value', size);

                myStyleSheet.set('body', {
                    fontSize: size
                });
            }
        }
    }).render(slider_container);

    // The color inputs are assigned keyup listeners that will update the
    // StyleSheet if the current input value is a valid CSS color value
    // The heading input affects all h1s, h2, and h3s
    Y.on('keyup', function(e) {
        var color = this.get('value');

        console.log(color);

        if (isValidColor(color)) {
            console.log("Valid color", myStyleSheet);

            myStyleSheet.set('h1, h2, h3', {
                color: color
            });
        }
    }, '#heading_color');

    // The link hover affects the background color of links when they are
    // hovered. There is no way other than via stylesheet modification to
    // change pseudo-class styles.
    Y.on('keyup', function(e) {
        var color = this.get('value');

        if (isValidColor(color)) {
            myStyleSheet.set('a:hover', {
                backgroundColor: color
            });
        }
    }, '#link_hover');

    // Progressive form enhancement complete, now prevent the form from
    // submitting normally.
    Y.on('submit', function(e) {
        e.halt();
    }, '#theme_form');

    // A rudimentary validator to make sure we're not trying to set
    // invalid color values in StyleSheet.

    function isValidColor(v) {
        return /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(v) || /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/.test(v) || /^[a-z]{3,}$/i.test(v);
    }

});

CSS:

/* For supporting browsers, the overlay is rendered semi-transparent with
* fancy rounded corners */
.yui3-overlay {
    background: rgba(128,128,128,0.3);
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    padding: 7px;
    cursor: move;
}

.yui3-overlay-content {
    background: rgba(205,205,205,0.3);
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    padding: 1px;
}

.yui3-overlay form {
    background: #f2fbff;
    border: 2px solid #fff;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    margin: 0;
    padding: 0;
    font-size: 13px;
}

.yui3-overlay fieldset {
    border: 1px solid #bcd;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    margin: 0;
    padding: 20px;
}

.yui3-overlay h3 {
    border-bottom: 2px solid #fff;
    color: #479;
    background: transparent;
    margin: 0;
    font-size: 175%;
}

.yui3-overlay label {
    display: block;
    margin: 1.3em 0 0.5ex;
    font-weight: bold;
    color: #003;
}

.yui3-overlay p {
    margin: 2em 0 0;
}

/* override the move cursor for the Slider */
.yui3-overlay .yui3-slider:hover {
    cursor: default;
}

I just copied and pasted the code, can anyone help?


问:
how to get an HTML element who called a function?
I have HTML elements with 'onclick' attribute like this one:

```<code>  <div class="item add pt-3" data-toggle="modal" data-target="#uploadModal"
   onclick="myFunction();"><i class="ni ni-fat-add"></i></div>
</code>```

Later in a script I want to have this element to manipulate it.

```<code>myFunction(){
  $(theElement).data('target'); //example
}
</code>```

答:
function myFunction(myEvent){
 console.log( myEvent.getAttribute('data-toggle'))
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="item add pt-3" data-toggle="modal" data-target="#uploadModal"
   onclick="myFunction(this);"><i class="ni ni-fat-add"></i>click me</div></code>```

Body:
I have HTML elements with 'onclick' attribute like this one:

Later in a script I want to have this element to manipulate it.

myFunction(){
  $(theElement).data('target'); //example
}

Body:
function myFunction(myEvent){
 console.log( myEvent.getAttribute('data-toggle'))
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="item add pt-3" data-toggle="modal" data-target="#uploadModal"
   onclick="myFunction(this);"><i class="ni ni-fat-add"></i>click me</div>


问:
Filling a dataframe column after checking multiple conditions based on other columns from the same dataframe
I need to fill up a column with some values based on multiple conditions from multiple other columns

This is my current DataFrame, and these are the conditions I will need to check for each row. Conditions

I need to create a new column that will be filled with either of the values from this - list based on the conditions mentioned above for each row one by one.

I am currently exploring the idea of using np.where but how do I use it for each row and check all 6 conditions together?

答:
To check all conditions together you can use this:</p>
```<code>df_filterd = df.loc[ (df['column1'] < condition1) & (df['column2'] < condition2 &...]
</code>```

Body:
To check all conditions together you can use this:

df_filterd = df.loc[ (df['column1'] < condition1) & (df['column2'] < condition2 &...]


问:
How to add user-picker field for Jira custom plugin
I'm creating a custom plugin for Jira.
I now have start date and end date fields.
How can I add a field to select the user for which the report will be generated?</p>
```<code><atlassian-plugin key="${atlassian.plugin.key}" name="${project.name}" plugins-version="2">
  <plugin-info>
    ...
  </plugin-info>

  <report name="Creation Report" ...>
    <description ...>
    <resource ...>

    <property>
            <key>startDate</key>
            <name>report.issuecreation.startdate</name>
            <description>report.issuecreation.startdate.description</description>
            <type>date</type>
        </property>
        <property>
            <key>endDate</key>
            <name>report.issuecreation.enddate</name>
            <description>report.issuecreation.enddate.description</description>
            <type>date</type>
        </property>
        <property>
            <key>users</key>
            <name>report.issuecreation.users</name>
            <description>report.issuecreation.users.description</description>
            <type>select</type> # i don't know
            ???
        </property>
  </report>
</atlassian-plugin>
</code>```

答:
Read this documentation: https://developer.atlassian.com/server/jira/platform/object-configurable-parameters/

Then you can see some examples like this:

```<code><properties>
    <property>
        <key>versionId</key>
        <name>common.concepts.version</name>
        <description>report.timetracking.version.description</description>
        <type>select</type>
        <values class="com.atlassian.jira.portal.VersionOptionalValuesGenerator"/>
    </property>
    <property>
        <key>sortingOrder</key>
        <name>report.timetracking.sortingorder</name>
        <description>report.timetracking.sortingorder.description</description>
        <type>select</type>
        <values class="com.atlassian.jira.portal.SortingValuesGenerator"/>
    </property>
    <property>
        <key>completedFilter</key>
        <name>report.timetracking.filter</name>
        <description>report.timetracking.filter.description</description>
        <type>select</type>
        <values class="com.atlassian.jira.portal.FilterValuesGenerator"/>
    </property>
</properties>
</code>```

The type select is correct, but I believe you will need something called UserValuesGenerator, these generators basically extend com.atlassian.com.configurable.ValuesGenerator

So you can write your own UserValuesGenerator and use it.

Body:
I'm creating a custom plugin for Jira.
I now have start date and end date fields.
How can I add a field to select the user for which the report will be generated?

<atlassian-plugin key="${atlassian.plugin.key}" name="${project.name}" plugins-version="2">
  <plugin-info>
    ...
  </plugin-info>

  <report name="Creation Report" ...>
    <description ...>
    <resource ...>

    <property>
            <key>startDate</key>
            <name>report.issuecreation.startdate</name>
            <description>report.issuecreation.startdate.description</description>
            <type>date</type>
        </property>
        <property>
            <key>endDate</key>
            <name>report.issuecreation.enddate</name>
            <description>report.issuecreation.enddate.description</description>
            <type>date</type>
        </property>
        <property>
            <key>users</key>
            <name>report.issuecreation.users</name>
            <description>report.issuecreation.users.description</description>
            <type>select</type> # i don't know
            ???
        </property>
  </report>
</atlassian-plugin>

Body:
Read this documentation: https://developer.atlassian.com/server/jira/platform/object-configurable-parameters/

Then you can see some examples like this:

<properties>
    <property>
        <key>versionId</key>
        <name>common.concepts.version</name>
        <description>report.timetracking.version.description</description>
        <type>select</type>
        <values class="com.atlassian.jira.portal.VersionOptionalValuesGenerator"/>
    </property>
    <property>
        <key>sortingOrder</key>
        <name>report.timetracking.sortingorder</name>
        <description>report.timetracking.sortingorder.description</description>
        <type>select</type>
        <values class="com.atlassian.jira.portal.SortingValuesGenerator"/>
    </property>
    <property>
        <key>completedFilter</key>
        <name>report.timetracking.filter</name>
        <description>report.timetracking.filter.description</description>
        <type>select</type>
        <values class="com.atlassian.jira.portal.FilterValuesGenerator"/>
    </property>
</properties>

The type select is correct, but I believe you will need something called UserValuesGenerator, these generators basically extend com.atlassian.com.configurable.ValuesGenerator

So you can write your own UserValuesGenerator and use it.


问:
I'm not getting the expected outputs in this powershell script
i made this script in powershell, but i'm not doing something correctly (I'm trying to learn self-taught uwu)

This is the script in question.

```<code>function Get-DesiredProcess {
    $DesiredProcess=Read-Host "Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification)"
    Switch ($DesiredProcess)
    {
        WUP {$ChosenProcess=Install-WUpdate}
        MDP {$ChosenProcess=Set-Proxy}
        }
    If ($DesiredProcess -eq $null) {
    Write-Error "You must specify an action!"
    return Get-DesiredProcess
    }
    Else {
    Set-Variable -Name "DesiredProcess" -Value "ChosenProcess"
    }
}

Get-DesiredProcess
Write-Output $DesiredProcess
Write-Output $ChosenProcess
</code>```

The 2 last "Write-Output" are just for testing if it did registry the variables correctly or not (spoiler, it didn't)

When the Read-Host have not been answered, it should output "You specify an action!" but does nothing:

```<code>Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification):

PS C:\Users\user1\Documents\scriptsfiles>
</code>```

And when a choice is made, it should keep the variable with this part:

```<code>Set-Variable -Name "DesiredProcess" -Value "ChosenProcess"
</code>```

Instead of that it executes directly the choosen process...

Thanks in advance!

答:
If you want your function to set a new value to a variable defined outside the function, use scoping inside the function, so
$ChosenProcess = 'Install-WUpdate' --> $script:ChosenProcess = 'Install-WUpdate'.

However, easier to understand is to have your function output something the rest of the code can deal with. In this case, since you want both what the user typed in, AND what the chosen process for that input would be, I would suggest having the function output an object that has both properties like:

```<code>function Get-DesiredProcess {
    # inside the function both variables have LOCAL scope
    $ChosenProcess  = $null  # initialize to nothing, or an empty string
    $DesiredProcess = Read-Host "Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification)"
    switch ($DesiredProcess) {
        'WUP' {$ChosenProcess = 'Install-WUpdate'}
        'MDP' {$ChosenProcess = 'Set-Proxy'}
        default {
            Write-Warning "You did not specify an accepted action. Type 'WUP' or 'MDP'"
            Get-DesiredProcess
        }
    }
    # only output if there is a matching chosen process
    if (![string]::IsNullOrWhiteSpace($ChosenProcess)) {
        # now have the function return both what the user typed and what the chosen action should be
        [PsCustomObject]@{
            DesiredProcess = $DesiredProcess
            ChosenProcess  = $ChosenProcess
        }
    }
}

$result = Get-DesiredProcess
</code>```

Using this would output something like

```<code>Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification): 7
WARNING: You did not specify an accepted action. Type 'WUP' or 'MDP'
Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification): wup

DesiredProcess ChosenProcess
-------------- -------------
wup            Install-WUpdate
</code>```

Now, the following code can simply act on what is in variable $result.ChosenProcess

Body:
i made this script in powershell, but i'm not doing something correctly (I'm trying to learn self-taught uwu)

This is the script in question.

function Get-DesiredProcess {
    $DesiredProcess=Read-Host "Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification)"
    Switch ($DesiredProcess)
    {
        WUP {$ChosenProcess=Install-WUpdate}
        MDP {$ChosenProcess=Set-Proxy}
        }
    If ($DesiredProcess -eq $null) {
    Write-Error "You must specify an action!"
    return Get-DesiredProcess
    }
    Else {
    Set-Variable -Name "DesiredProcess" -Value "ChosenProcess"
    }
}

Get-DesiredProcess
Write-Output $DesiredProcess
Write-Output $ChosenProcess

The 2 last "Write-Output" are just for testing if it did registry the variables correctly or not (spoiler, it didn't)

When the Read-Host have not been answered, it should output "You specify an action!" but does nothing:

Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification):

PS C:\Users\user1\Documents\scriptsfiles>

And when a choice is made, it should keep the variable with this part:

Set-Variable -Name "DesiredProcess" -Value "ChosenProcess"

Instead of that it executes directly the choosen process...

Thanks in advance!

Body:
If you want your function to set a new value to a variable defined outside the function, use scoping inside the function, so
$ChosenProcess = 'Install-WUpdate' --> $script:ChosenProcess = 'Install-WUpdate'.

However, easier to understand is to have your function output something the rest of the code can deal with. In this case, since you want both what the user typed in, AND what the chosen process for that input would be, I would suggest having the function output an object that has both properties like:

function Get-DesiredProcess {
    # inside the function both variables have LOCAL scope
    $ChosenProcess  = $null  # initialize to nothing, or an empty string
    $DesiredProcess = Read-Host "Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification)"
    switch ($DesiredProcess) {
        'WUP' {$ChosenProcess = 'Install-WUpdate'}
        'MDP' {$ChosenProcess = 'Set-Proxy'}
        default {
            Write-Warning "You did not specify an accepted action. Type 'WUP' or 'MDP'"
            Get-DesiredProcess
        }
    }
    # only output if there is a matching chosen process
    if (![string]::IsNullOrWhiteSpace($ChosenProcess)) {
        # now have the function return both what the user typed and what the chosen action should be
        [PsCustomObject]@{
            DesiredProcess = $DesiredProcess
            ChosenProcess  = $ChosenProcess
        }
    }
}

$result = Get-DesiredProcess

Using this would output something like

Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification): 7
WARNING: You did not specify an accepted action. Type 'WUP' or 'MDP'
Welcome to de advanced task manager! Choose an action to do: 1. WUP (WindowsUpdate) 2. MDP (ProxyModification): wup

DesiredProcess ChosenProcess
-------------- -------------
wup            Install-WUpdate

Now, the following code can simply act on what is in variable $result.ChosenProcess


问:
React Native Maps UrlTile
I am trying to use openstreetmap tile in UrlTile but I am getting duplicate layers, openstreetmap and default google map, how can I remove google map layer?

This is my component:

```<code>import { StyleSheet, Text, View, Button } from "react-native";
import MapView, {
  PROVIDER_GOOGLE,
  MAP_TYPES,
  PROVIDER_DEFAULT,
  UrlTile,
  Marker,
} from "react-native-maps";
import React, { useEffect } from "react";

export default function Home({ navigation }) {
  let location = {
    latitude: 23.259933,
    longitude: 77.412613,
    latitudeDelta: 0.009,
    longitudeDelta: 0.009,
  };

  return (
    <View style={styles.container}>
      <View style={styles.myMap}>
        <MapView
          region={location}
          rotateEnabled={false}
          style={{ flex: 1 }}
          style={styles.map}
          showsUserLocation
        >
          <UrlTile
            urlTemplate="https://a.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png"
            maximumZ={19}
          />
          <Marker
            title="Home"
            coordinate={{
              latitude: location.latitude,
              longitude: location.longitude,
            }}
          />
        </MapView>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#ffd",
    alignItems: "center",
    justifyContent: "center",
  },
  btn1: {
    margin: 20,
  },
  btn2: {
    margin: 20,
  },
  btns: {
    flex: 1,
    flexDirection: "row",
    backgroundColor: "grey",
  },
  myMap: {
    flex: 2,
    backgroundColor: "white",
    width: "100%",
    marginTop: 30,
    marginBottom: 30,
  },
  map: {
    width: "100%",
    height: "100%",
  },
});
</code>```

Also, when I switch openstreetmap tile with my own MapTiler server tiles it doesn't show anything, just google map

```<code>'http://localhost:3650/api/maps/satellite-hybrid/{z}/{x}/{y}.png'
</code>```

One last thing, I need to know if this going to cost me, I am required to use Google API key to run react-native-maps library, I need some explanation.

Thank you in advance.

答:
have you tried to consult the MapTiler Documentation yet?
There might be some tips to help you:
https://docs.maptiler.com/maplibre-gl-native-android/?_ga=2.172534305.364226297.1644212649-2087445124.1628005081&_gl=1*1hky133*_ga*MjA4NzQ0NTEyNC4xNjI4MDA1MDgx*_ga_K4SXYBF4HT*MTY0NDI0NDA5My4yLjEuMTY0NDI0NTAxMC41Ng..

May I ask if the Google Map is essential? Since you use MapTiler Server, it could be also replaced with a MapTiler Data Layer.

If you are interested in getting to know more, feel free to contact us at support@maptiler.com

Title: React Native Maps UrlTile

Body:
I am trying to use openstreetmap tile in UrlTile but I am getting duplicate layers, openstreetmap and default google map, how can I remove google map layer?

This is my component:

import { StyleSheet, Text, View, Button } from "react-native";
import MapView, {
  PROVIDER_GOOGLE,
  MAP_TYPES,
  PROVIDER_DEFAULT,
  UrlTile,
  Marker,
} from "react-native-maps";
import React, { useEffect } from "react";

export default function Home({ navigation }) {
  let location = {
    latitude: 23.259933,
    longitude: 77.412613,
    latitudeDelta: 0.009,
    longitudeDelta: 0.009,
  };

  return (
    <View style={styles.container}>
      <View style={styles.myMap}>
        <MapView
          region={location}
          rotateEnabled={false}
          style={{ flex: 1 }}
          style={styles.map}
          showsUserLocation
        >
          <UrlTile
            urlTemplate="https://a.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png"
            maximumZ={19}
          />
          <Marker
            title="Home"
            coordinate={{
              latitude: location.latitude,
              longitude: location.longitude,
            }}
          />
        </MapView>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#ffd",
    alignItems: "center",
    justifyContent: "center",
  },
  btn1: {
    margin: 20,
  },
  btn2: {
    margin: 20,
  },
  btns: {
    flex: 1,
    flexDirection: "row",
    backgroundColor: "grey",
  },
  myMap: {
    flex: 2,
    backgroundColor: "white",
    width: "100%",
    marginTop: 30,
    marginBottom: 30,
  },
  map: {
    width: "100%",
    height: "100%",
  },
});

Also, when I switch openstreetmap tile with my own MapTiler server tiles it doesn't show anything, just google map

'http://localhost:3650/api/maps/satellite-hybrid/{z}/{x}/{y}.png'

One last thing, I need to know if this going to cost me, I am required to use Google API key to run react-native-maps library, I need some explanation.

Thank you in advance.


问:
VSCode: Integrated terminal selected lines not highlighted

In the integrated terminal of VSCode even though I have selected the line print -c "print('Hello World')" as shown in the above screenshot, it doesn't gets highlighted like blue color in my iTerm2 terminal as illustrated in the screenshot below

Any ideas what settings should I change to achieve the same?

答:
Use this colorCustomization in your settings.json:

```<code>{
  "workbench.colorCustomizations": {

    "terminal.selectionBackground": "#f00"
  }
}
</code>```

See Customizing a color theme

Body:
Use this colorCustomization in your settings.json:

{
  "workbench.colorCustomizations": {

    "terminal.selectionBackground": "#f00"
  }
}

See Customizing a color theme


问:
How show one element of the JSON on interpolation with Angular
How show one element of the JSON on interpolation with Angular

```<code>  public responseData:any;

  renderTokenCard(){
    this.mundipaggS.checkToken().subscribe((response:any)=> {
    console.log("success: ", JSON.stringify(response));
    this.cartS.tokenCard = response;
    this.responseData = response;
  }, );
</code>```

         {{responseData}}
        </div

```
<p>The JSON</p>
<pre class="lang-json prettyprint-override"><code>[{"id":1,"pessoa_id":75505,"created_at":"2022-02-01T17:42:46.000000Z","holder":"test ","validade":"2026-06-01","bandeira":"Mastercard"}]
</code>```

How can I show the JSON holder property for example?

答:
Using your example, you can use interpolation to display it in HTML.

//ngIf to check if responseData is not undefined, otherwise it will throw error

      {{responseData[0].holder }}

```
<p>I see you are returning an array of objects, If you want to show multiple holders, you can use *ngFor to display them</p>
<pre class="lang-html prettyprint-override"><code><div class="card-body">
<i class="fab fa-cc-visa "></i>
   <div class="card-text" *ngFor="let data of responseData">
     <b> {{data.holder }} </b>
   </div>
</div>
</code>```

Body:
How show one element of the JSON on interpolation with Angular

  public responseData:any;

  renderTokenCard(){
    this.mundipaggS.checkToken().subscribe((response:any)=> {
    console.log("success: ", JSON.stringify(response));
    this.cartS.tokenCard = response;
    this.responseData = response;
  }, );

         {{responseData}}
        </div

The JSON

[{"id":1,"pessoa_id":75505,"created_at":"2022-02-01T17:42:46.000000Z","holder":"test ","validade":"2026-06-01","bandeira":"Mastercard"}]

How can I show the JSON holder property for example?

Body:
Using your example, you can use interpolation to display it in HTML.

<div class="card-body">
<i class="fab fa-cc-visa "></i>
//ngIf to check if responseData is not undefined, otherwise it will throw error
   <div class="card-text" *ngIf="responseData && responseData[0]">
     <b> {{responseData[0].holder }} </b>
    </div>
</div>

I see you are returning an array of objects, If you want to show multiple holders, you can use *ngFor to display them

<div class="card-body">
<i class="fab fa-cc-visa "></i>
   <div class="card-text" *ngFor="let data of responseData">
     <b> {{data.holder }} </b>
   </div>
</div>


问:
C# linq query, select parent list based on the condition of nest list
I have a list of projects with a list of project members for each project as follows

```<code>public List<Project> Projects { get; set; }
    public class Project
    {
        public Guid Id { get; set; }
        public string  Title { get; set; }
        public string Description { get; set; }
        public List<Member> Members { get; set; }
    }

    public class Member{
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
</code>```

I want to select projects for a list of member Ids using LINQ, thank you!

答:
try something like this:

```<code>        var projects = new List<Project>();
        List<Guid>searched_value = new List<Guid>();
        var newList = projects.Where(p => p.Members.Any(m => searched_value.Any(s => s == m.Id))).ToList();
</code>```

Edited to reflect the OP wants to check against a List

Body:
I have a list of projects with a list of project members for each project as follows

public List<Project> Projects { get; set; }
    public class Project
    {
        public Guid Id { get; set; }
        public string  Title { get; set; }
        public string Description { get; set; }
        public List<Member> Members { get; set; }
    }

    public class Member{
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

I want to select projects for a list of member Ids using LINQ, thank you!

Body:
try something like this:

        var projects = new List<Project>();
        List<Guid>searched_value = new List<Guid>();
        var newList = projects.Where(p => p.Members.Any(m => searched_value.Any(s => s == m.Id))).ToList();

Edited to reflect the OP wants to check against a List


问:
How to get json tree value to DataGridView
I need to get the EUR price from json source API page https://api.coingecko.com/api/v3/coins/axie-infinity which is in some kind of 'tree' results.

The Rank market_cap_rank I'm able to get but current_price I'm not able.

My Code:

```<code>Public Class JsonResponse

        <JsonProperty("market_cap_rank")>
        Public Property _rank As String

        <JsonProperty("current_price")>
        Public Property _cPrice As String

    End Class

    Public Sub getRankAXS()
    Try
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
        ServicePointManager.Expect100Continue = True

        Dim _urlAXS As String = "https://api.coingecko.com/api/v3/coins/axie-infinity" '&format=json"

        Dim _req As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(_urlAXS)
        _req.Proxy = Nothing
        _req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36"

        Dim _resp As System.Net.HttpWebResponse = _req.GetResponse
        Dim streamReader As System.IO.StreamReader = New System.IO.StreamReader(_resp.GetResponseStream())
        Dim rank_source As String = streamReader.ReadToEnd
        Dim _rankResults = JsonConvert.DeserializeObject(Of JsonResponse)(rank_source)

        Dim vRank = _rankResults._rank
        Dim vPrice = _rankResults._cPrice

        Dim row As DataGridViewRow = Nothing
        For Each item As DataGridViewRow In dgvMain.Rows
            row = item
            dgvMain.Rows(17).Cells(0).Value = vRank
            dgvMain.Rows(17).Cells(4).Value = vPrice

        Next
        dgvMain.Refresh()
        _runningThreads.Remove(Thread.CurrentThread)
    Catch ex As Exception
    End Try

End Sub
</code>```

The Source in short:

```<code>"country_origin": "",
"genesis_date": null,
"contract_address": "0xbb0e17ef65f82ab018d8edd776e8dd940327b28b",
"sentiment_votes_up_percentage": 86.04,
"sentiment_votes_down_percentage": 13.96,
"market_cap_rank": 35,
"coingecko_rank": 282,
"coingecko_score": 34.249,
"developer_score": 0.0,
"community_score": 12.533,
"liquidity_score": 74.834,
"public_interest_score": 4.85,
    "market_data": {
        "current_price": {
        "aed": 253.89,
        "dot": 3.081598,
        "eos": 26.36419,
        "eth": 0.022493,
        "eur": 60.44,
        "gbp": 51.16,
        }

    }
"total_value_locked": null,
"mcap_to_tvl_ratio": null,
"fdv_to_tvl_ratio": null,
"roi": null,
</code>```

SO under _cPrice I need to get the =>market_data => current_price => eur

Thank you for help.

答:
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. I cannot paste the example because the incoming payload is too large.

However, once you get the classes defined, you can then deserialize the object using the following:

Dim payload = JsonConvert.DeserializeObject(Of Rootobject)(rank_source)
Dim eurMarketDataCurrentPrice = payload.market_data.current_price.eur
```

Fiddle: https://dotnetfiddle.net/moVuMl

Body:
I need to get the EUR price from json source API page https://api.coingecko.com/api/v3/coins/axie-infinity which is in some kind of 'tree' results.

The Rank market_cap_rank I'm able to get but current_price I'm not able.

My Code:

Public Class JsonResponse

        <JsonProperty("market_cap_rank")>
        Public Property _rank As String

        <JsonProperty("current_price")>
        Public Property _cPrice As String

    End Class

    Public Sub getRankAXS()
    Try
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
        ServicePointManager.Expect100Continue = True

        Dim _urlAXS As String = "https://api.coingecko.com/api/v3/coins/axie-infinity" '&format=json"

        Dim _req As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(_urlAXS)
        _req.Proxy = Nothing
        _req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36"

        Dim _resp As System.Net.HttpWebResponse = _req.GetResponse
        Dim streamReader As System.IO.StreamReader = New System.IO.StreamReader(_resp.GetResponseStream())
        Dim rank_source As String = streamReader.ReadToEnd
        Dim _rankResults = JsonConvert.DeserializeObject(Of JsonResponse)(rank_source)

        Dim vRank = _rankResults._rank
        Dim vPrice = _rankResults._cPrice

        Dim row As DataGridViewRow = Nothing
        For Each item As DataGridViewRow In dgvMain.Rows
            row = item
            dgvMain.Rows(17).Cells(0).Value = vRank
            dgvMain.Rows(17).Cells(4).Value = vPrice

        Next
        dgvMain.Refresh()
        _runningThreads.Remove(Thread.CurrentThread)
    Catch ex As Exception
    End Try

End Sub

The Source in short:

"country_origin": "",
"genesis_date": null,
"contract_address": "0xbb0e17ef65f82ab018d8edd776e8dd940327b28b",
"sentiment_votes_up_percentage": 86.04,
"sentiment_votes_down_percentage": 13.96,
"market_cap_rank": 35,
"coingecko_rank": 282,
"coingecko_score": 34.249,
"developer_score": 0.0,
"community_score": 12.533,
"liquidity_score": 74.834,
"public_interest_score": 4.85,
    "market_data": {
        "current_price": {
        "aed": 253.89,
        "dot": 3.081598,
        "eos": 26.36419,
        "eth": 0.022493,
        "eur": 60.44,
        "gbp": 51.16,
        }

    }
"total_value_locked": null,
"mcap_to_tvl_ratio": null,
"fdv_to_tvl_ratio": null,
"roi": null,

SO under _cPrice I need to get the =>market_data => current_price => eur

Thank you for help.

Body:
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. I cannot paste the example because the incoming payload is too large.

However, once you get the classes defined, you can then deserialize the object using the following:

Dim payload = JsonConvert.DeserializeObject(Of Rootobject)(rank_source)
Dim eurMarketDataCurrentPrice = payload.market_data.current_price.eur

Fiddle: https://dotnetfiddle.net/moVuMl


问:
Why does pthread_join not take a thread pointer?
Pretty self explanatory question. For example, the header for pthread_create shows it takes a pointer to a thread:

```<code>int WINPTHREAD_API pthread_create(pthread_t *th, const pthread_attr_t *attr, void *(* func)(void *), void *arg);
</code>```

OK, makes sense, you allocate a pthread in memory then pass a pointer to pthread_create so it gets initialized... but now looking at the header for pthread_join:

```<code>int WINPTHREAD_API pthread_join(pthread_t t, void **res);
</code>```

It takes a copy of the pthread_t. I just don't get why it doesn't take a pointer to that already existing thread, rather than copying it and passing it over; it seems like if anything, doing so would cause more problems and more memory use. Am I missing something? I read the manpage, it doesn't seem to offer a reason to this.

答:
It takes a copy of the pthread_t.

Yes.

I just don't get why it doesn't take
a pointer to that already existing thread,

pthread_t is a thread identifier.  The specs consistently refer to it that way.  Copying it does not duplicate the thread itself, nor consume more memory than one pthread_t occupies.

rather than copying it and
passing it over; it seems like if anything, doing so would cause more
problems and more memory use.

It does not necessarily cause more memory use, as a pthread_t is not necessarily larger than a pointer.  It might be a pointer, or an integer.  Even if it is a structure, however, there is no reason to think that it so large that passing it by value presents a significant problem, because the specifics are under control of the pthreads implementation.  Why would implementers shoot themselves in the foot that way?  Note well that passing a structure by value is not inherently less efficient than passing a pointer.

As for problems other than excessive memory use, you would have to be more specific, but I don't see any issues inherent in accessing a copy of a thread identifier directly vs. accessing a common identifier object indirectly, for the purposes of those functions that accept a pthread_t by value.

Am I missing something?

I suspect that your concerns are tied up in a misunderstanding of type pthread_t as somehow carrying data supporting thread operation as opposed to simply identifying a thread.

You may also be supposing that pthreads is a library, with a particular implementation, whereas in fact, it is first and foremost a specification, designed to afford multiple implementations.  This is part of the reason for defining abstract data type pthread_t instead of specifying int or struct something * -- implementations can choose what actual type to use.

Perhaps you are also focusing too closely on the API functions.  Even if in some particular implementation, passing a pthread_t by value to, say, pthread_join() were less efficient than passing a pointer to one, how much of an impact do you suppose that would actually have?  pthread_join() is called infrequently, and only in cases where the caller is prepared to block.  What does it matter if argument passing consumes a few more nanoseconds than it might otherwise do?

I read the
manpage, it doesn't seem to offer a reason to this.

Few manual pages provide rationale for function design, but I think the most likely explanation is essentially that form follows function.  Those functions that receive a pthread_t by value do so because they do not need or want to modify the caller's value. The functions' designs reflect that.

Body:
Pretty self explanatory question. For example, the header for pthread_create shows it takes a pointer to a thread:

int WINPTHREAD_API pthread_create(pthread_t *th, const pthread_attr_t *attr, void *(* func)(void *), void *arg);

OK, makes sense, you allocate a pthread in memory then pass a pointer to pthread_create so it gets initialized... but now looking at the header for pthread_join:

int WINPTHREAD_API pthread_join(pthread_t t, void **res);

It takes a copy of the pthread_t. I just don't get why it doesn't take a pointer to that already existing thread, rather than copying it and passing it over; it seems like if anything, doing so would cause more problems and more memory use. Am I missing something? I read the manpage, it doesn't seem to offer a reason to this.


问:
What is the difference between passing local variable VS broadcast variable to spark pipeline?
consider the code below:

```<code>val rdd: RDD[String] = domainsRDD()
val backlistDomains: Set[String] = readDomainsBlacklist()
rdd.filter(domain => !backlistDomains.contains(domain)
</code>```

VS code where blacklisted domains are broacasted:

```<code>val rdd: RDD[String] = domainsRDD()
val bBacklistDomains: Set[String] = sc.broadcast(readDomainsBlacklist())
rdd.filter(domain => !bBacklistDomains.value.contains(domain))
</code>```

Despite the fact that broadcasted variable can be erased from executors (via bBacklistDomains.destroy()) are there any other reasons to use it (performance?)?
(please note, that in the first code example domains is a local variable and serialization issue will not appear)

答:
There is none, local variables used in stages are automatically broadcasted.

Spark automatically broadcasts the common data needed by tasks within each stage.
The data broadcasted this way is cached in serialized form and deserialized before running each task.
This means that explicitly creating broadcast variables is only useful when tasks across multiple stages need the same data or when caching the data in deserialized form is important.
```

From the docs: https://spark.apache.org/docs/latest/rdd-programming-guide.html#broadcast-variables

Body:
consider the code below:

val rdd: RDD[String] = domainsRDD()
val backlistDomains: Set[String] = readDomainsBlacklist()
rdd.filter(domain => !backlistDomains.contains(domain)

VS code where blacklisted domains are broacasted:

val rdd: RDD[String] = domainsRDD()
val bBacklistDomains: Set[String] = sc.broadcast(readDomainsBlacklist())
rdd.filter(domain => !bBacklistDomains.value.contains(domain))

Despite the fact that broadcasted variable can be erased from executors (via bBacklistDomains.destroy()) are there any other reasons to use it (performance?)?
(please note, that in the first code example domains is a local variable and serialization issue will not appear)

Body:
There is none, local variables used in stages are automatically broadcasted.

Spark automatically broadcasts the common data needed by tasks within each stage.
The data broadcasted this way is cached in serialized form and deserialized before running each task.
This means that explicitly creating broadcast variables is only useful when tasks across multiple stages need the same data or when caching the data in deserialized form is important.

From the docs: https://spark.apache.org/docs/latest/rdd-programming-guide.html#broadcast-variables


问:
How can I do work __set__ or __setattr__ with including class?
So, I have a class that describe some page object, something like this:

```<code>class Dashboard:
    project_edit_modal = Modal({
        "edit_input": Input(
            by=By.XPATH,
            value='//div[@class="header"][text()="Project edit"]',
            name='Title \'Project edit\''),
         "some_input: Input ()....
    )}
</code>```

Here "Input" - this is the class with selectors how to find elements. And "Modal" - is the class where collect this Inputs and other modal windows elements.

I have descriptor __set__inside the "Modal".
Now, when I want to type in "edit_input" I can white something like this:

```<code>Dashboard().Modal().edit_input = 'some value'.
</code>```

I suppose that __set__ or __setattr__ will called, and type into "edit_input", but doesnt(
__set__ calling only if you white something like this

```<code>Dashboard().Modal() = 'some value'.
</code>```

But I need:

```<code>Dashboard().Modal().edit_input = 'some value'.
</code>```

But how can I do work this construction with "Modal" class?

Code is here:

```<code>class Modal:

    def __init__(self, *args):
        if isinstance(args[0], dict):
            self.values = args[0]
            self.elements = self.values.keys()

    def __set__(self, instance, value):
          el: WebElement = Browser().get_element(selector_type=self._selector_type, selector=self._selector)
            el.send_keys(value)
</code>```

答:
you have a major misconception there, and I won't have the time or proper explaining it.

Buit in short, doing Dashboard().Modal() does not make any sense - if you had Modal - the class itself, not an instance of it - as an attribute of a Dashboard instance, then this would create you a fresh new instance of Modal, with no bindings to the Dashboard at all.

The binding behavior of the descriptor protocol, which makes Python call __get__ and __set__ methods takes place when you have an instance of your descriptor class set as a class attribute of the hosting class.
This is what your code snippet is doing correctly with the project_edit_modal attribute.

So, if the remaining of your code is well formed, your __set__ method will be called if you do:

```<code>Dashboard().project_edit_modal = 'some value'
</code>```

Body:
So, I have a class that describe some page object, something like this:

class Dashboard:
    project_edit_modal = Modal({
        "edit_input": Input(
            by=By.XPATH,
            value='//div[@class="header"][text()="Project edit"]',
            name='Title \'Project edit\''),
         "some_input: Input ()....
    )}

Here "Input" - this is the class with selectors how to find elements. And "Modal" - is the class where collect this Inputs and other modal windows elements.

I have descriptor __set__inside the "Modal".
Now, when I want to type in "edit_input" I can white something like this:

Dashboard().Modal().edit_input = 'some value'.

I suppose that __set__ or __setattr__ will called, and type into "edit_input", but doesnt(
__set__ calling only if you white something like this

Dashboard().Modal() = 'some value'.

But I need:

Dashboard().Modal().edit_input = 'some value'.

But how can I do work this construction with "Modal" class?

Code is here:

class Modal:

    def __init__(self, *args):
        if isinstance(args[0], dict):
            self.values = args[0]
            self.elements = self.values.keys()

    def __set__(self, instance, value):
          el: WebElement = Browser().get_element(selector_type=self._selector_type, selector=self._selector)
            el.send_keys(value)

Body:
you have a major misconception there, and I won't have the time or proper explaining it.

Buit in short, doing Dashboard().Modal() does not make any sense - if you had Modal - the class itself, not an instance of it - as an attribute of a Dashboard instance, then this would create you a fresh new instance of Modal, with no bindings to the Dashboard at all.

The binding behavior of the descriptor protocol, which makes Python call __get__ and __set__ methods takes place when you have an instance of your descriptor class set as a class attribute of the hosting class.
This is what your code snippet is doing correctly with the project_edit_modal attribute.

So, if the remaining of your code is well formed, your __set__ method will be called if you do:

Dashboard().project_edit_modal = 'some value'


问:
With VS-Code, I can't utilise the emmet option for Styled-component in React
Using VS-code, I'm attempting to use emmet for styled-components in react. I've tried every tip on the internet, but I still can't get it.

I have tried to install extensions like vscode-styled-components

i have added  "emmet.includeLanguages": { "jsx": "javascriptreact, css", "javascript": "javascriptreact, css" }, in my settings.json

for reference if we typedf it will be added as display:flex
but still im not getting it help me with solving this issue

答:
You can use vscode-styled-components extension in VSCode.
Link here.

It's an awesome Extension of VSCode.


问:
Write mysql custom query in query builder of grafana
I made a time-series graph screenshot attached and the generated query is

```<code>SELECT
  UNIX_TIMESTAMP(date_of_sign_up) DIV 600 * 600 AS "time",
  status AS "borrower_status",
  count(id) AS "Number Of Borrowers"
FROM borrowers
WHERE
  date_of_sign_up BETWEEN FROM_UNIXTIME(1631158800) AND FROM_UNIXTIME(1643881661) AND
  status IN ('APPROVED','INACTIVE','BASIC') AND
  client_id = 130454654
GROUP BY 1, status
ORDER BY UNIX_TIMESTAMP(date_of_sign_up) DIV 600 * 600
</code>```

Now i want to pass from and to from url in mysql query builder, below is the query i tried to write but it did not work

```<code>SELECT
  $__timeGroupAlias(date_of_sign_up,10m),
  status AS "borrower_status",
  count(id) AS "Number Of Borrowers"
FROM borrowers
WHERE
 date_of_signup between $from AND $to  AND
  status IN (${BorrowerStatus}) AND
  client_id = [[tenant]]
GROUP BY 1, status
ORDER BY $__timeGroup(date_of_sign_up,10m)
</code>```

What is the correct way of passing &from and &to from URL params in MySQL query builder date_of_signup between

答:
```<code>date_of_signup between $__timeFrom() AND $__timeTo()
</code>```

Body:
I made a time-series graph screenshot attached and the generated query is

SELECT
  UNIX_TIMESTAMP(date_of_sign_up) DIV 600 * 600 AS "time",
  status AS "borrower_status",
  count(id) AS "Number Of Borrowers"
FROM borrowers
WHERE
  date_of_sign_up BETWEEN FROM_UNIXTIME(1631158800) AND FROM_UNIXTIME(1643881661) AND
  status IN ('APPROVED','INACTIVE','BASIC') AND
  client_id = 130454654
GROUP BY 1, status
ORDER BY UNIX_TIMESTAMP(date_of_sign_up) DIV 600 * 600

Now i want to pass from and to from url in mysql query builder, below is the query i tried to write but it did not work

SELECT
  $__timeGroupAlias(date_of_sign_up,10m),
  status AS "borrower_status",
  count(id) AS "Number Of Borrowers"
FROM borrowers
WHERE
 date_of_signup between $from AND $to  AND
  status IN (${BorrowerStatus}) AND
  client_id = [[tenant]]
GROUP BY 1, status
ORDER BY $__timeGroup(date_of_sign_up,10m)

What is the correct way of passing &from and &to from URL params in MySQL query builder date_of_signup between


问:
C# Chromium browser whatsapp web send message using textbox
I already follow the Chromium user guide, still doesn't work. Using my C# program, I want to send message or image via whatsapp web by cascading the textbox in my program with the message box of whatsapp. This is my code

```<code>using CefSharp;
using CefSharp.WinForms;
using System;
using System.Windows.Forms;

namespace ChromiumwithEditorWsWeb
{
public partial class Form1 : Form
{
    ChromiumWebBrowser browser;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CefSettings settings = new CefSettings();
        Cef.Initialize(settings);

        browser = new ChromiumWebBrowser("http://web.whatsapp.com");
        browser.Dock = DockStyle.Fill;

        panel1.Controls.Add(browser);
    }

    private void buttonBack_Click(object sender, EventArgs e)
    {
        browser.Back();
    }

    private void buttonForward_Click(object sender, EventArgs e)
    {
        browser.Forward();
    }

    private void buttonReload_Click(object sender, EventArgs e)
    {
        browser.ShowDevTools();
    }

    private void buttonGo_Click(object sender, EventArgs e)
    {
        browser.Load(textBoxUrl.Text);
    }

    private void buttonPhoneNo_Click(object sender, EventArgs e)
    {

        browser.EvaluateScriptAsync("document.GetElementsByClass('jN-F5 copyable-text selectable-text').value = textBoxPhone.Text");
        browser.EvaluateScriptAsync("document.GetElementsByClass('_2S1VP copyable-text selectable-text').value = textBoxMessage.Text");

    }
}
</code>```

}

Help it! Give suggestions for the best step.

答:
```<code>        Clipboard.SetText(msg);
        Thread.Sleep(TimeSpan.FromSeconds(2));
        SendKeys.Send(msg); //SendKeys.SendWait("^{V}");
        Thread.Sleep(TimeSpan.FromSeconds(1));
        SendKeys.SendWait("{ENTER}");
</code>```

Not a good solution though, as it requires the windows to be on focus and this uses the clipboard. But it works !

Body:
I already follow the Chromium user guide, still doesn't work. Using my C# program, I want to send message or image via whatsapp web by cascading the textbox in my program with the message box of whatsapp. This is my code

using CefSharp;
using CefSharp.WinForms;
using System;
using System.Windows.Forms;

namespace ChromiumwithEditorWsWeb
{
public partial class Form1 : Form
{
    ChromiumWebBrowser browser;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CefSettings settings = new CefSettings();
        Cef.Initialize(settings);

        browser = new ChromiumWebBrowser("http://web.whatsapp.com");
        browser.Dock = DockStyle.Fill;

        panel1.Controls.Add(browser);
    }

    private void buttonBack_Click(object sender, EventArgs e)
    {
        browser.Back();
    }

    private void buttonForward_Click(object sender, EventArgs e)
    {
        browser.Forward();
    }

    private void buttonReload_Click(object sender, EventArgs e)
    {
        browser.ShowDevTools();
    }

    private void buttonGo_Click(object sender, EventArgs e)
    {
        browser.Load(textBoxUrl.Text);
    }

    private void buttonPhoneNo_Click(object sender, EventArgs e)
    {

        browser.EvaluateScriptAsync("document.GetElementsByClass('jN-F5 copyable-text selectable-text').value = textBoxPhone.Text");
        browser.EvaluateScriptAsync("document.GetElementsByClass('_2S1VP copyable-text selectable-text').value = textBoxMessage.Text");

    }
}

}

Help it! Give suggestions for the best step.

Body:
        Clipboard.SetText(msg);
        Thread.Sleep(TimeSpan.FromSeconds(2));
        SendKeys.Send(msg); //SendKeys.SendWait("^{V}");
        Thread.Sleep(TimeSpan.FromSeconds(1));
        SendKeys.SendWait("{ENTER}");

Not a good solution though, as it requires the windows to be on focus and this uses the clipboard. But it works !


问:
Error: Member not found: 'packageRoot', how to solve ignore: deprecated_member_use in Flutter?
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

```<code>    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1
</code>```

So, I need a suggestion that how can I solve this issue?

答:
I fixed it with one command:</p>
```<code>$ flutter pub cache repair
</code>```

Body:
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1

So, I need a suggestion that how can I solve this issue?

Body:
I fixed it with one command:

$ flutter pub cache repair


问:
Why do we usually use || over |? What is the difference?
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

```<code>if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
</code>```

```<code>if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass
</code>```

Can we use | instead of ||? Same thing with & and &&.

答:
One main difference is that || and && exhibit "short-circuiting", so the RHS will only be evaluated if needed.

For e.g.

```<code>if (a || b) {
    path1...
} else {
    path2..
}
</code>```

Above if a is true then b will not be tested and path1 is executed. If | was used then both sides would be evaluated even if 'a' is true.

See Here and here, for a little more information.

Hope this helps.

Body:
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.

Body:
One main difference is that || and && exhibit "short-circuiting", so the RHS will only be evaluated if needed.

For e.g.

if (a || b) {
    path1...
} else {
    path2..
}

Above if a is true then b will not be tested and path1 is executed. If | was used then both sides would be evaluated even if 'a' is true.

See Here and here, for a little more information.

Hope this helps.