问:
maven-scm-plugin and git. when downloading files from repository - NullPointerException
I want to download files from git repository (aka clone) to project directory using maven-scm-plugin

I am getting an error

```<code>Failed to execute goal org.apache.maven.plugins:maven-scm-plugin:1.12.2:export (myjsp) on project myproject-tomcat-web: Execution myjsp of goal org.apache.maven.plugins:maven-scm-plugin:1.12.2:export failed.: NullPointerException
</code>```

In pom.xml I use the following construct

```<code>            <plugin>
                <artifactId>maven-scm-plugin</artifactId>
                <version>1.12.2</version>
                <executions>
                    <execution>
                        <id>myjsp</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>export</goal>
                        </goals>
                        <configuration>
                            <connectionUrl>scm:git:https://git.myserver.com/myurl.git</connectionUrl>
                            <exportDirectory>target/web-resources/WEB-INF/resource</exportDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

At the same time, everything loads normally from the SVN repository (when setting the url to connectionUrl).

What could be the problem?

答: Resolved, checkoutDirectory should be set instead of exportDirectory</p>

Body:
I want to download files from git repository (aka clone) to project directory using maven-scm-plugin

I am getting an error

Failed to execute goal org.apache.maven.plugins:maven-scm-plugin:1.12.2:export (myjsp) on project myproject-tomcat-web: Execution myjsp of goal org.apache.maven.plugins:maven-scm-plugin:1.12.2:export failed.: NullPointerException

In pom.xml I use the following construct

            <plugin>
                <artifactId>maven-scm-plugin</artifactId>
                <version>1.12.2</version>
                <executions>
                    <execution>
                        <id>myjsp</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>export</goal>
                        </goals>
                        <configuration>
                            <connectionUrl>scm:git:https://git.myserver.com/myurl.git</connectionUrl>
                            <exportDirectory>target/web-resources/WEB-INF/resource</exportDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

At the same time, everything loads normally from the SVN repository (when setting the url to connectionUrl).

What could be the problem?


来源: stackexchange

问:
While creating item from parent to child component, going to infinite loop in React
This is my home page and getting list data then creating List component as much as need.
Then going to List component and creating list item. so creating new component using map function. I tried different ways for it but I can't figure out. It goes infinite loop whatever I did.

Home.jsx

```<code>const [lists, setLists] = useState([]);

  useEffect(() => {
    const getRandomList = async () => {
      try {
        const res = await axios.get(`/lists${type ? "?type=" + type : ""}`, {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            token: token,
          },
        });
        setLists(res.data);
      } catch (error) {
        console.log(error);
      }
    };
    getRandomList();
  }, [type]);
  return (
    <div className="home">
      <Navbar />
      <Featured type={type} />
      {lists.map((list, index) => {
        return <List key={index} list={list}/>;
      })}
    </div>
  );
}
</code>```

in List component, creating List item component as much as need.

List.jsx

```<code>export default function List({ list }) {
  const [isMoved, setIsMoved] = useState(false);
  const [slideNumber, setSlideNumber] = useState(0);
  const [clickLimit, setClickLimit] = useState(window.innerWidth / 230);
  const [lists, setLists] = useState([])
  const listRef = useRef();

  useEffect( () =>{
    const getList = ()=>{
      setLists(list.content)
    }
    getList()
  },[list])

  const handleClick = (direction) => {
    setIsMoved(true);
    let distance = listRef.current.getBoundingClientRect().x - 50;
    if (direction === "left" && slideNumber > 0) {
      setSlideNumber(slideNumber - 1);
      listRef.current.style.transform = `translateX(${230 + distance}px)`;
    }
    if (direction === "right" && slideNumber < 10 - clickLimit) {
      setSlideNumber(slideNumber + 1);
      listRef.current.style.transform = `translateX(${-230 + distance}px)`;
    }
  };
  return (
    <div className="list">
      <span className="listTitle">Continue to watch</span>
      <div className="listWrapper">
        <ArrowBackIosOutlined
          className="sliderArrow left"
          onClick={() => handleClick("left")}
          style={{ display: !isMoved && "none" }}
        />
        <div className="listContainer" ref={listRef}>
          {lists.map((item, index) => {
            return <ListItem key={index} index={index} item={item} />;
          })}
        </div>
        <ArrowForwardIosOutlined
          className="sliderArrow right"
          onClick={() => handleClick("right")}
        />
      </div>
    </div>
  );
}

</code>```

last component here.

ListItem.jsx

```<code>export default function ListItem({ index, item }) {
  const [isHovered, setIsHovered] = useState(false);
  const [movie, setMovie] = useState({});

  useEffect(() => {
    const getMovie = async (item) => {
      try {
        const res = await axios.get("/movies/find/" + item, {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            token: token,
          },
        });
        setMovie(res.data);
      } catch (error) {
        console.log(error);
      }
    };
    getMovie()

  }, [item]);

  return (
    <div
      className="listItem"
       style={{
        left:
          isHovered &&
          Object.values(index) * 225 - 50 + Object.values(index) * 2.5,
      }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <img src={movie.img} alt="" />
      {isHovered && (
        <>
          <video src={movie.trailer} autoPlay loop></video>
          <div className="itemInfo">
            <div className="itemIcons">
              <PlayArrow className="itemIcon" />
              <Add className="itemIcon" />
              <ThumbUpAltOutlined className="itemIcon" />
              <ThumbDownAltOutlined className="itemIcon" />
            </div>
            <div className="itemInfoTop">
              <span>1 hour 14 mins</span>
              <span className="limit">{movie.limit}</span>
              <span>{movie.year}</span>
            </div>
            <div className="itemDescription">{movie.description}</div>
            <div className="itemGenre">{movie.genre}</div>
          </div>
        </>
      )}
    </div>
  );
}
</code>```

答:
Try to remove the useEffect from the List component and map on the list.content directly:

```<code>export default function List({ list }) {
  const [isMoved, setIsMoved] = useState(false);
  const [slideNumber, setSlideNumber] = useState(0);
  const [clickLimit, setClickLimit] = useState(window.innerWidth / 230);

  const listRef = useRef();

  const handleClick = (direction) => {
    setIsMoved(true);
    let distance = listRef.current.getBoundingClientRect().x - 50;
    if (direction === "left" && slideNumber > 0) {
      setSlideNumber(slideNumber - 1);
      listRef.current.style.transform = `translateX(${230 + distance}px)`;
    }
    if (direction === "right" && slideNumber < 10 - clickLimit) {
      setSlideNumber(slideNumber + 1);
      listRef.current.style.transform = `translateX(${-230 + distance}px)`;
    }
  };

  return (
    <div className="list">
      <span className="listTitle">Continue to watch</span>
      <div className="listWrapper">
        <ArrowBackIosOutlined
          className="sliderArrow left"
          onClick={() => handleClick("left")}
          style={{ display: !isMoved && "none" }}
        />
        <div className="listContainer" ref={listRef}>
          {list.content.map((item, index) => {
            return <ListItem key={index} index={index} item={item} />;
          })}
        </div>
        <ArrowForwardIosOutlined
          className="sliderArrow right"
          onClick={() => handleClick("right")}
        />
      </div>
    </div>
  );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is my home page and getting list data then creating List component as much as need.
Then going to List component and creating list item. so creating new component using map function. I tried different ways for it but I can't figure out. It goes infinite loop whatever I did.

Home.jsx

const [lists, setLists] = useState([]);

  useEffect(() => {
    const getRandomList = async () => {
      try {
        const res = await axios.get(`/lists${type ? "?type=" + type : ""}`, {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            token: token,
          },
        });
        setLists(res.data);
      } catch (error) {
        console.log(error);
      }
    };
    getRandomList();
  }, [type]);
  return (

      <Navbar />
      <Featured type={type} />
      {lists.map((list, index) => {
        return <List key={index} list={list}/>;
      })}

  );
}

in List component, creating List item component as much as need.

List.jsx

export default function List({ list }) {
  const [isMoved, setIsMoved] = useState(false);
  const [slideNumber, setSlideNumber] = useState(0);
  const [clickLimit, setClickLimit] = useState(window.innerWidth / 230);
  const [lists, setLists] = useState([])
  const listRef = useRef();

  useEffect( () =>{
    const getList = ()=>{
      setLists(list.content)
    }
    getList()
  },[list])

  const handleClick = (direction) => {
    setIsMoved(true);
    let distance = listRef.current.getBoundingClientRect().x - 50;
    if (direction === "left" && slideNumber > 0) {
      setSlideNumber(slideNumber - 1);
      listRef.current.style.transform = `translateX(${230 + distance}px)`;
    }
    if (direction === "right" && slideNumber < 10 - clickLimit) {
      setSlideNumber(slideNumber + 1);
      listRef.current.style.transform = `translateX(${-230 + distance}px)`;
    }
  };
  return (

      Continue to watch

        <ArrowBackIosOutlined
          className="sliderArrow left"
          onClick={() => handleClick("left")}
          style={{ display: !isMoved && "none" }}
        />

          {lists.map((item, index) => {
            return <ListItem key={index} index={index} item={item} />;
          })}

        <ArrowForwardIosOutlined
          className="sliderArrow right"
          onClick={() => handleClick("right")}
        />

  );
}

last component here.

ListItem.jsx

export default function ListItem({ index, item }) {
  const [isHovered, setIsHovered] = useState(false);
  const [movie, setMovie] = useState({});

  useEffect(() => {
    const getMovie = async (item) => {
      try {
        const res = await axios.get("/movies/find/" + item, {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            token: token,
          },
        });
        setMovie(res.data);
      } catch (error) {
        console.log(error);
      }
    };
    getMovie()

  }, [item]);

  return (

 setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >

      {isHovered && (
        <>
          <video src={movie.trailer} autoPlay loop></video>

              <PlayArrow className="itemIcon" />
              <Add className="itemIcon" />
              <ThumbUpAltOutlined className="itemIcon" />
              <ThumbDownAltOutlined className="itemIcon" />

              1 hour 14 mins
              {movie.limit}
              {movie.year}

{movie.description}

{movie.genre}

        </>
      )}

  );
}

Body:
Try to remove the useEffect from the List component and map on the list.content directly:

export default function List({ list }) {
  const [isMoved, setIsMoved] = useState(false);
  const [slideNumber, setSlideNumber] = useState(0);
  const [clickLimit, setClickLimit] = useState(window.innerWidth / 230);

  const listRef = useRef();

  const handleClick = (direction) => {
    setIsMoved(true);
    let distance = listRef.current.getBoundingClientRect().x - 50;
    if (direction === "left" && slideNumber > 0) {
      setSlideNumber(slideNumber - 1);
      listRef.current.style.transform = `translateX(${230 + distance}px)`;
    }
    if (direction === "right" && slideNumber < 10 - clickLimit) {
      setSlideNumber(slideNumber + 1);
      listRef.current.style.transform = `translateX(${-230 + distance}px)`;
    }
  };

  return (
    <div className="list">
      <span className="listTitle">Continue to watch</span>
      <div className="listWrapper">
        <ArrowBackIosOutlined
          className="sliderArrow left"
          onClick={() => handleClick("left")}
          style={{ display: !isMoved && "none" }}
        />
        <div className="listContainer" ref={listRef}>
          {list.content.map((item, index) => {
            return <ListItem key={index} index={index} item={item} />;
          })}
        </div>
        <ArrowForwardIosOutlined
          className="sliderArrow right"
          onClick={() => handleClick("right")}
        />
      </div>
    </div>
  );
}


问:
r create a unique numeric value for every id in column
I have a dataset with a long list of random IDs like this.

```<code> ID
 H001
 H00A
 H00M
 B00A
 BB0B
 AB0A
 AA0B
 AA0B
 BB0B
 H001
 H00A
 H001
 H00M
 H00Z
 CC01
 CD01
 CC02
 XT01
 XT0A
 XT0A
</code>```

I like to create a new column with numeric values for each ID.  The final dataset would appear like this.

```<code> ID      NumId
 H001    1
 H00A    2
 H00M    3
 B00A    4
 BB0B    5
 AB0A    6
 AA0B    7
 AA0B    7
 BB0B    5
 H001    1
 H00A    2
 H001    1
 H00M    3
 H00Z    8
 CC01    9
 CD01    10
 CC02    11
 XT01    12
 XT0A    13
 XT0A    13
</code>```

Any suggestions on how to create a numerically equivalent column is much appreciated thanks.

答:
By using the fact that factors are internally numeric this is quite easy:

a<-c('a','b','c','a','b','e')
as.numeric(as.factor(a))
#> [1] 1 2 3 1 2 4
```

Created on 2022-02-10 by the reprex package (v2.0.1)

Body:
I have a dataset with a long list of random IDs like this.

 ID
 H001
 H00A
 H00M
 B00A
 BB0B
 AB0A
 AA0B
 AA0B
 BB0B
 H001
 H00A
 H001
 H00M
 H00Z
 CC01
 CD01
 CC02
 XT01
 XT0A
 XT0A

I like to create a new column with numeric values for each ID.  The final dataset would appear like this.

 ID      NumId
 H001    1
 H00A    2
 H00M    3
 B00A    4
 BB0B    5
 AB0A    6
 AA0B    7
 AA0B    7
 BB0B    5
 H001    1
 H00A    2
 H001    1
 H00M    3
 H00Z    8
 CC01    9
 CD01    10
 CC02    11
 XT01    12
 XT0A    13
 XT0A    13

Any suggestions on how to create a numerically equivalent column is much appreciated thanks.

Body:
By using the fact that factors are internally numeric this is quite easy:

a<-c('a','b','c','a','b','e')
as.numeric(as.factor(a))
#> [1] 1 2 3 1 2 4

Created on 2022-02-10 by the reprex package (v2.0.1)


问:
substring-before the last occurrence of any non-word character xslt 2.0 3.0
Similar to this question, but in XSLT 2.0 or 3.0, and I want to break on the last non-word character (like the regex \W)

Finding the last occurrence of a string xslt 1.0

The input is REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX

The desired output is:

```<code>REMOVE-THIS-IS-A-TEST-LINE,XXX,

</code>```

This works for one delimiter at a time, but I need to break on at least commas, spaces and dashes.

```<code>substring('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX',1,index-of(string-to-codepoints('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX'),string-to-codepoints(' '))[last()])
</code>```

I am using oxygen with saxon 9.9EE and antenna house.

答:
I would do

```<code>replace('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX', '(\W)\w*$', '$1')
</code>```

However, this involves back-tracking, so it might be expensive if done on a long line. To avoid the backtracking, try

```<code>string-join(
   analyze-string(
      'REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX', '\W')
      /*[not(position()=last())])
</code>```

Body:
Similar to this question, but in XSLT 2.0 or 3.0, and I want to break on the last non-word character (like the regex \W)

Finding the last occurrence of a string xslt 1.0

The input is REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX

The desired output is:

REMOVE-THIS-IS-A-TEST-LINE,XXX,

This works for one delimiter at a time, but I need to break on at least commas, spaces and dashes.

substring('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX',1,index-of(string-to-codepoints('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX'),string-to-codepoints(' '))[last()])

I am using oxygen with saxon 9.9EE and antenna house.

Body:
I would do

replace('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX', '(\W)\w*$', '$1')

However, this involves back-tracking, so it might be expensive if done on a long line. To avoid the backtracking, try

string-join(
   analyze-string(
      'REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX', '\W')
      /*[not(position()=last())])


问:
AgoraRtcEngineDelegate does not get invoked
when I invoke AgoraRtcEngineKit.shareEngine(withAppId: "", delegate: delegate), I found none of the methods in the delegate get invoked, is there anything need to pay attention?</p>

答:
None of the delegate methods should fire until you attempt to join a channel.

This example is super minimal, but the delegate method still works fine. Try comparing your project's setup with that one.


问:
How to fix this error please - TypeError: Object of type bytes is not JSON serializable
In my case the JSON file which I need to insert into database is already stored in variable named "data" i.e data = res.read().

I need to insert that "data" into the database directly where my database name called Rest and table called bms. It is getting connected to database. But I am getting the below error. I need help please

Traceback (most recent call last):
File "C:\Users\trees\RESTAPI_Python_Code\Test2.py", line 70, in
cursor.execute(('INSERT INTO dbo.bms([Value],[Unit],[WatchName])'),(json.dumps(data)))
File "C:\Python310\lib\json_init.py", line 231, in dumps
return default_encoder.encode(obj)
File "C:\Python310\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, one_shot=True)
File "C:\Python310\lib\json\encoder.py", line 257, in iterencode
return iterencode(o, 0)
File "C:\Python310\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type bytes is not JSON serializable

My code is below

```<code>conn = http.client.HTTPSConnection("120.157.117.168:8443")
payload = ''
headers = {
  'Authorization': f'Bearer {bearer_token}'
}
conn.request("GET", "/api/watches/AHU1%20Control", payload, headers)
#conn.request("GET", "/watches/AHU1%20Control", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

cnxn = pyodbc.connect("Driver={SQL Server};"
                      "Server=DESKTOP-9KT0GQV;"
                      "Database=Rest;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()

cursor.execute(('INSERT INTO dbo.bms([Value],[Unit],[WatchName])'),(json.dumps(data)))

for row in cursor:
    print(row)

cursor.close()
cnxn.close()
</code>```

答: Your object is a bytes object. You need to decode() it first (as you did in the print) before trying to serialize (json.dumps()) it.

Body:
In my case the JSON file which I need to insert into database is already stored in variable named "data" i.e data = res.read().

I need to insert that "data" into the database directly where my database name called Rest and table called bms. It is getting connected to database. But I am getting the below error. I need help please

Traceback (most recent call last):
File "C:\Users\trees\RESTAPI_Python_Code\Test2.py", line 70, in
cursor.execute(('INSERT INTO dbo.bms([Value],[Unit],[WatchName])'),(json.dumps(data)))
File "C:\Python310\lib\json_init.py", line 231, in dumps
return default_encoder.encode(obj)
File "C:\Python310\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, one_shot=True)
File "C:\Python310\lib\json\encoder.py", line 257, in iterencode
return iterencode(o, 0)
File "C:\Python310\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type bytes is not JSON serializable

My code is below

conn = http.client.HTTPSConnection("120.157.117.168:8443")
payload = ''
headers = {
  'Authorization': f'Bearer {bearer_token}'
}
conn.request("GET", "/api/watches/AHU1%20Control", payload, headers)
#conn.request("GET", "/watches/AHU1%20Control", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

cnxn = pyodbc.connect("Driver={SQL Server};"
                      "Server=DESKTOP-9KT0GQV;"
                      "Database=Rest;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()

cursor.execute(('INSERT INTO dbo.bms([Value],[Unit],[WatchName])'),(json.dumps(data)))

for row in cursor:
    print(row)

cursor.close()
cnxn.close()


问:
Quarkus does not @Inject beans in @QuarkusTest suite
I am pretty new in Quarkus but I'm pretty proficient in other IoC frameworks (Spring). I have a bean declared as follow

```<code>@ApplicationScoped
public class TestingRepo {
    public String greet() {
        return "Hi";
    }
}
</code>```

and I do also have a Quarkus test that looks like this

```<code>@QuarkusTest
public class InjectionTest {

    @Inject
    public TestingRepo tr;

    @Test
    public void testInjection() {
        Assertions.assertNotNull(tr);
    }
}
</code>```

When I do mvn test I got:

```<code>[ERROR] testInjection  Time elapsed: 0.006 s  <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: not <null>
     at org.mytest.InjectionTest.testInjection(InjectionTest.java:25)
</code>```

There is something I'm missing? I'm expecting to have the bean injected and not being null!
Thanks for your help.

答:
Had the same problem - and import org.junit.jupiter.api.Test; was already there.

But I noticed that VSCode - for whatever reason  - imported

```<code>import com.google.inject.Inject;
</code>```

Changing this to

```<code>import javax.inject.Inject;
</code>```

fixed the problem. The injected Bean was no longer null.

Body:
I am pretty new in Quarkus but I'm pretty proficient in other IoC frameworks (Spring). I have a bean declared as follow

@ApplicationScoped
public class TestingRepo {
    public String greet() {
        return "Hi";
    }
}

and I do also have a Quarkus test that looks like this

@QuarkusTest
public class InjectionTest {

    @Inject
    public TestingRepo tr;

    @Test
    public void testInjection() {
        Assertions.assertNotNull(tr);
    }
}

When I do mvn test I got:

[ERROR] testInjection  Time elapsed: 0.006 s  <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: not <null>
     at org.mytest.InjectionTest.testInjection(InjectionTest.java:25)

There is something I'm missing? I'm expecting to have the bean injected and not being null!
Thanks for your help.

Body:
Had the same problem - and import org.junit.jupiter.api.Test; was already there.

But I noticed that VSCode - for whatever reason  - imported

import com.google.inject.Inject;

Changing this to

import javax.inject.Inject;

fixed the problem. The injected Bean was no longer null.


问:
How to loop over nested JSON array and filter out search Query in Angular?
I have a complex nested JSON Array and I want to filter it(name property) through based on what user enters in input tag and show it as an autocomplete. A basic of it I have created here on stackblitz click here for the code. I have two entries of name "Tom" in two different objects so when user types Tom it should appear twice in the autocomplete as of now it shows only once. So if I press letter "T" it should show me all the names starting with "T". Here in this case "Tom" twice if I press "To" and if I press just "T" then Tiffany and Tom 2 times. Could you please help me here in the code ?
Any help is appreciated.  Thanks much!

答:
You can check the below code also, I have updated code you check in stackbliz https://stackblitz.com/edit/angular-ivy-k14se7</p>
```<code>matches = [];
  ngOnInit() {}
  searchKeyup(ev) {

    var term: any = ev.target as HTMLElement;
    console.log("Value", term.value);
    this.matches = [];
    let content = [
      {
        name: 'Robert',
        children: [],
      },
      {
        name: 'Doug',
        children: [
          {
            name: 'James',
            children: [
              {
                name: 'John',
                children: [
                  {
                    name: 'Tom',
                    children: [],
                  },
                ],
              },
            ],
          },
        ],
      },
      {
        name: 'Susan',
        children: [
          {
            name: 'Tiffany',
            children: [
              {
                name: 'Merry',
                children: [
                  {
                    name: 'Sasha',
                    children: [],
                  },
                  {
                    name: 'Tommy',
                    children: [],
                  },
                ],
              },
            ],
          },
        ],
      },
    ];
    if(term.value.length > 0){
      this.filter(content, term.value);
    } else {
      document.getElementById('list').innerHTML = '';
    }

    if (this.matches.length > 0) {
      document.getElementById('list').innerHTML = this.matches.map(match => match.name).join(",");
    } else{
      document.getElementById('list').innerHTML = "";
    }

  }
  filter(arr, term) {

    arr.forEach((i) => {
      if (i.name.includes(term)) {
        this.matches.push(i);
      }
      if (i.children.length > 0) {
        this.filter(i.children, term);
      }
    });
    console.log(this.matches);
  }
</code>```

Body:
You can check the below code also, I have updated code you check in stackbliz https://stackblitz.com/edit/angular-ivy-k14se7

matches = [];
  ngOnInit() {}
  searchKeyup(ev) {

    var term: any = ev.target as HTMLElement;
    console.log("Value", term.value);
    this.matches = [];
    let content = [
      {
        name: 'Robert',
        children: [],
      },
      {
        name: 'Doug',
        children: [
          {
            name: 'James',
            children: [
              {
                name: 'John',
                children: [
                  {
                    name: 'Tom',
                    children: [],
                  },
                ],
              },
            ],
          },
        ],
      },
      {
        name: 'Susan',
        children: [
          {
            name: 'Tiffany',
            children: [
              {
                name: 'Merry',
                children: [
                  {
                    name: 'Sasha',
                    children: [],
                  },
                  {
                    name: 'Tommy',
                    children: [],
                  },
                ],
              },
            ],
          },
        ],
      },
    ];
    if(term.value.length > 0){
      this.filter(content, term.value);
    } else {
      document.getElementById('list').innerHTML = '';
    }

    if (this.matches.length > 0) {
      document.getElementById('list').innerHTML = this.matches.map(match => match.name).join(",");
    } else{
      document.getElementById('list').innerHTML = "";
    }

  }
  filter(arr, term) {

    arr.forEach((i) => {
      if (i.name.includes(term)) {
        this.matches.push(i);
      }
      if (i.children.length > 0) {
        this.filter(i.children, term);
      }
    });
    console.log(this.matches);
  }


问:
How can I display CouchDB Complex output like this in one request?
I just the beginner of couchdb so I may be misunderstand point of view so you can teach and discuss with me

Doc Type
- User
- Topic
- Comment

Requirement
- I want to webboard
- 1 Request to get this complex doc

Output I need KEY "topic-id" ,  VALUE  {
  _id : "topic-id", created_at:"2011-05-30 19:50:22", title:"Hello
  World", user: {_id :
  "user-1",type:"user",username:"dominixz",signature:"http://dominixz.com"}
  comments: [ {_id:"comment-1", text:"Comment 1",created_at:"2011-05-30
  19:50:22",user: {_id :
  "user-1",type:"user",username:"dominixz",signature:"http://dominixz.com"}},
  {_id:"comment-2", text:"Comment 2",created_at:"2011-05-30
  19:50:23",user: {_id :
  "user-2",type:"user",username:"dominixz2",signature:"http://dominixz1.com"}},
  {_id:"comment-3", text:"Comment 3",created_at:"2011-05-30
  19:50:24",user: {_id :
  "user-3",type:"user",username:"dominixz3",signature:"http://dominixz2.com"}},
  ] }

I have "user" data like this
  {_id:"user-1",type:"user",username:"dominixz",signature:"http://dominixz.com"}
  {_id:"user-2",type:"user",username:"dominixz2",signature:"http://dominixz1.com"}
  {_id:"user-3",type:"user",username:"dominixz3",signature:"http://dominixz2.com"}

"Topic" data like this {_id : "topic-id",created_at:"2011-05-30
  19:50:22",title:"Hello World",user:"user-1"}

"Comment" data like this {_id:"comment-1",type:"comment" ,
  text:"Comment 1", created_at:"2011-05-30 19:50:22" , user: "user-1" ,
  topic:"topic-id"} {_id:"comment-2",type:"comment" , text:"Comment 2",
  created_at:"2011-05-30 19:50:23" , user: "user-2" , topic:"topic-id"}
  {_id:"comment-3",type:"comment" , text:"Comment 3",
  created_at:"2011-05-30 19:50:24" , user: "user-3" , topic:"topic-id"}

How can I write map,reduce,list for achieve this complex data ? and how about when I wanna use LIMIT , OFFSET like in db

Thank in advance

答:
CouchDB is a document database, not a relational database. As such it is best suited to deal with documents that encompass all the related data. While you can normalize your schema relational-style like you did, I'd argue that this isn't be best use case for Couch.

If I were to design your CMS in Couch I'd keep the topic, content and comments all in a single document. That would directly solve your problem.

You're free of course to use document stores to emulate relational databases, but that's not their natural use case, which leads to questions like this one.

ContentLicense: CC BY-SA 3.0


问:
event.dataTransfer.dropEffect in chrome
I have a script which determines the result of drag and drop operation from the value of event.dataTransfer.dropEffect. I set the property event.dataTransfer.effectAllowed to value "copymove". In Firefox the value of dropEffect is "move" by default and "copy" when I press ctrl key during drag. In Chrome, the value of dropEffect is always "none". Does Chrome not suppot this API?</p>

答:
I got a solution for this as it is still not working these years.

Only Firefox seems to update the value of event.dataTransfer.dropEffect automatically.

In all other browsers you will have to do some extra steps (provided in script below) by using keyboard events (event.ctrlKey and event.shiftKey) to capture the status of CTRL and SHIFT keys and update the event.dataTransfer.dropEffect.

Solution

The basic script I attach here, updates the event.dataTransfer.dropEffect and makes things work in Chrome and in Edge as well.

document.addEventListener("dragover", (event) => {
  event.preventDefault();
  var c = event.ctrlKey;
  var s = event.shiftKey;
  var dropEffect = updateDropEffect(c, s);
  event.dataTransfer.dropEffect = dropEffect;

  document.getElementById("div1").innerHTML = "drag type: " + dropEffect;;

    }, false);

function updateDropEffect(c, s) {
    // control, shift, none behaviors
    if (c && s) { return "link"; }
    if (c) { return "copy" }
    return "move";
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="drag1"draggable="true">DRAG THIS TEXT BUT KEEP MOUSE BUTTON PRESSED WHILE PRESSING CTRL + SHIFT KEY
  <br> You will notice that mouse pointer icon changes, not only in Firefox but also in in Chrome and Edge
  <br><br>
</div>
<div id="div1">*** Look here for status of mouse pointer icon *** </div>    </code>```

Title: event.dataTransfer.dropEffect in chrome

Body:
I got a solution for this as it is still not working these years.

Only Firefox seems to update the value of event.dataTransfer.dropEffect automatically.

In all other browsers you will have to do some extra steps (provided in script below) by using keyboard events (event.ctrlKey and event.shiftKey) to capture the status of CTRL and SHIFT keys and update the event.dataTransfer.dropEffect.

Solution

The basic script I attach here, updates the event.dataTransfer.dropEffect and makes things work in Chrome and in Edge as well.

document.addEventListener("dragover", (event) => {
  event.preventDefault();
  var c = event.ctrlKey;
  var s = event.shiftKey;
  var dropEffect = updateDropEffect(c, s);
  event.dataTransfer.dropEffect = dropEffect;

  document.getElementById("div1").innerHTML = "drag type: " + dropEffect;;

    }, false);

function updateDropEffect(c, s) {
    // control, shift, none behaviors
    if (c && s) { return "link"; }
    if (c) { return "copy" }
    return "move";
  }

<div id="drag1"draggable="true">DRAG THIS TEXT BUT KEEP MOUSE BUTTON PRESSED WHILE PRESSING CTRL + SHIFT KEY
  <br> You will notice that mouse pointer icon changes, not only in Firefox but also in in Chrome and Edge
  <br><br>
</div>
<div id="div1">*** Look here for status of mouse pointer icon *** </div>


问:
Python statement merge
I have a standard format letter(in txt format) and within it I want to replace some words(keywords) with the words I have created in a separate wordlist.

to visualise my letter is:

```<code>Dear [name],

I have b-day party on [date] at [venue]
please be there @ [time]

Sincerely,
</code>```

the following is the file that I would like to replace:

```<code>Mary
12.02.2022
Soho House
08.00pm
</code>```

so Mary would be seen on the [name] and 12.02.2022 is seen on the [date] such as:

Dear Mary,
I have a b-day party on 12.02.2022 xxxx

Following code didnot work. Could you please support how to solve this issue?

```<code>import keyword

placeholder1="[name]"
placeholder2="[date]"
placeholder3="[venue]"
placeholder4="[time]"

with open("occurence.txt") as letter:
    keyref=letter.readlines()

with open("sample_letter.txt") as target:
    target_contents=target.read()

for name in keyref:
    word1=target_contents.replace(placeholder1,name)

for date in keyref:
    word2 = target_contents.replace(placeholder2, date)

print(word1)
print(word2)
</code>```

答:
You don't need to import keywords use variables instead. Write things and that. I don't think it will work that way. Please sort it out nicely. You can also make it so that it is an input but this is what I wrote:</p>
```<code>name = 'name'
date = 'date'
venue = 'venue'
time = 'time'

print("Dear ",name + "\nI have b-day party on ",date + "at ",venue +
"please be there @",time + "\nSincerely,"
</code>```

Title: Python statement merge

Body:
I have a standard format letter(in txt format) and within it I want to replace some words(keywords) with the words I have created in a separate wordlist.

to visualise my letter is:

Dear [name],

I have b-day party on [date] at [venue]
please be there @ [time]

Sincerely,

the following is the file that I would like to replace:

Mary
12.02.2022
Soho House
08.00pm

so Mary would be seen on the [name] and 12.02.2022 is seen on the [date] such as:

Dear Mary,
I have a b-day party on 12.02.2022 xxxx

Following code didnot work. Could you please support how to solve this issue?

import keyword

placeholder1="[name]"
placeholder2="[date]"
placeholder3="[venue]"
placeholder4="[time]"

with open("occurence.txt") as letter:
    keyref=letter.readlines()

with open("sample_letter.txt") as target:
    target_contents=target.read()

for name in keyref:
    word1=target_contents.replace(placeholder1,name)

for date in keyref:
    word2 = target_contents.replace(placeholder2, date)

print(word1)
print(word2)

Body:
You don't need to import keywords use variables instead. Write things and that. I don't think it will work that way. Please sort it out nicely. You can also make it so that it is an input but this is what I wrote:

name = 'name'
date = 'date'
venue = 'venue'
time = 'time'

print("Dear ",name + "\nI have b-day party on ",date + "at ",venue +
"please be there @",time + "\nSincerely,"


问:
Add a "Ship To" column in Woocommerce "My Account" orders table
I am trying to add a column that displays the 'Ship to' company name to the WooCommerce > my account > orders page.

So far the code below adds a column but how do I get the 'Ship to' data to show, where am I'm I getting it wrong?

 // Add new column(s) to the "My Orders" table in the account.
function filter_woocommerce_account_orders_columns( $columns ) {
    $columns['custom-column'] = __( 'New Column 1', 'woocommerce' );
    return $columns;
}
add_filter( 'woocommerce_account_orders_columns', 'filter_woocommerce_account_orders_columns', 10, 1 );

 // Adds data to the custom column in "My Account > Orders"
function filter_woocommerce_my_account_my_orders_shipping_company_column( $order ) {
    echo 'New Column 1';
}
add_action( 'woocommerce_my_account_my_orders_column_custom-column', 'filter_woocommerce_my_account_my_orders_column_custom_column', 10, 1 );

 $order_shipping_company = $order_data['shipping']['company'];```

答:
You can use woocommerce_my_account_my_orders_query filter hook. You have to pass a number of orders you want to display to numberposts param. try below code.

```<code>function modify_numberposts_woocommerce_my_account_my_orders_query( $customer_orders_args ){
    $customer_orders_args['numberposts'] = 20;
    return $customer_orders_args;
}

add_filter( 'woocommerce_my_account_my_orders_query', 'modify_numberposts_woocommerce_my_account_my_orders_query' );
</code>```

Body:
You can use woocommerce_my_account_my_orders_query filter hook. You have to pass a number of orders you want to display to numberposts param. try below code.

function modify_numberposts_woocommerce_my_account_my_orders_query( $customer_orders_args ){
    $customer_orders_args['numberposts'] = 20;
    return $customer_orders_args;
}

add_filter( 'woocommerce_my_account_my_orders_query', 'modify_numberposts_woocommerce_my_account_my_orders_query' );


问:
Google AdMob Unity: Only test ads work (in Unity Editor) but no real ads
My admob account is linked to the app in play store, status "ready", AdMob app ID also added into ad settings in Unity, added in the real ad unit ID, test ad showing in Unity, waited a week...

Result: no real ads

My event is calling RequestAndLoadInterstitialAd() and ShowInterstitialAd(), which works in Unity with the test ad. I expected it to work once the test ad implemented successfully.

```<code>    using UnityEngine.Events;
    using UnityEngine;
    using GoogleMobileAds.Api;
    using GoogleMobileAds.Common;
    using UnityEngine.UI;
    using System;
    using System.Collections.Generic;

    public class GoogleAdMobController : MonoBehaviour
    {
        private AppOpenAd appOpenAd;
        private BannerView bannerView;
        private InterstitialAd interstitialAd;
        private RewardedAd rewardedAd;
        private RewardedInterstitialAd rewardedInterstitialAd;
        private float deltaTime;
        private bool isShowingAppOpenAd;
        public UnityEvent OnAdLoadedEvent;
        public UnityEvent OnAdFailedToLoadEvent;
        public UnityEvent OnAdOpeningEvent;
        public UnityEvent OnAdFailedToShowEvent;
        public UnityEvent OnUserEarnedRewardEvent;
        public UnityEvent OnAdClosedEvent;
        public bool showFpsMeter = true;
        public Text fpsMeter;
        public Text statusText;

        #region UNITY MONOBEHAVIOR METHODS

        public void Start()
        {
            MobileAds.SetiOSAppPauseOnBackground(true);

            List<String> deviceIds = new List<String>() { AdRequest.TestDeviceSimulator };

            // Add some test device IDs (replace with your own device IDs).
    #if UNITY_IPHONE
            deviceIds.Add("b77a5c561934e089)--a185c62eba2497c95197140e5282b27a");
    #elif UNITY_ANDROID
            deviceIds.Add("b77a5c561934e089)--a185c62eba2497c95197140e5282b27a");
    #endif

            // Configure TagForChildDirectedTreatment and test device IDs.
            RequestConfiguration requestConfiguration =
                new RequestConfiguration.Builder()
                .SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.Unspecified)
                .SetTestDeviceIds(deviceIds).build();
            MobileAds.SetRequestConfiguration(requestConfiguration);

            // Initialize the Google Mobile Ads SDK.
            MobileAds.Initialize(HandleInitCompleteAction);
        }

        private void HandleInitCompleteAction(InitializationStatus initstatus)
        {
            // Callbacks from GoogleMobileAds are not guaranteed to be called on
            // main thread.
            // In this example we use MobileAdsEventExecutor to schedule these calls on
            // the next Update() loop.
            MobileAdsEventExecutor.ExecuteInUpdate(() =>
            {
                statusText.text = "Initialization complete";
            //  RequestBannerAd();
            });
        }

        private void Update()
        {
            if (showFpsMeter)
            {
                fpsMeter.gameObject.SetActive(true);
                deltaTime += (Time.deltaTime - deltaTime) * 0.1f;
                float fps = 1.0f / deltaTime;
                fpsMeter.text = string.Format("{0:0.} fps", fps);
            }
            else
            {
                fpsMeter.gameObject.SetActive(false);
            }
        }

        #endregion

        #region HELPER METHODS

        private AdRequest CreateAdRequest()
        {
            return new AdRequest.Builder()
                .AddKeyword("unity-admob-sample")
                .Build();
        }

        public void OnApplicationPause(bool paused)
        {
            // Display the app open ad when the app is foregrounded.
            if (!paused)
            {
                ShowAppOpenAd();
            }
        }

        #endregion

        #region BANNER ADS

        public void RequestBannerAd()
        {
            statusText.text = "Requesting Banner Ad.";

            // These ad units are configured to always serve test ads.
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/6300978111";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/2934735716";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Clean up banner before reusing
            if (bannerView != null)
            {
                bannerView.Destroy();
            }

            // Create a 320x50 banner at top of the screen
            bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Top);

            // Add Event Handlers
            bannerView.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            bannerView.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            bannerView.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            bannerView.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

            // Load a banner ad
            bannerView.LoadAd(CreateAdRequest());
        }

        public void DestroyBannerAd()
        {
            if (bannerView != null)
            {
                bannerView.Destroy();
            }
        }

        #endregion

        #region INTERSTITIAL ADS

        public void RequestAndLoadInterstitialAd()
        {
            // statusText.text = "Requesting Interstitial Ad.";

    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-2334240444886107/9358512518";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/4411468910";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Clean up interstitial before using it
            if (interstitialAd != null)
            {
                interstitialAd.Destroy();
            }
            interstitialAd = new InterstitialAd(adUnitId);

            // Add Event Handlers
            interstitialAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            interstitialAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            interstitialAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            interstitialAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

            // Load an interstitial ad
            interstitialAd.LoadAd(CreateAdRequest());
        }

        public void ShowInterstitialAd()
        {
            if (interstitialAd.IsLoaded())
            {
                interstitialAd.Show();
            }
            else
            {
                statusText.text = "Interstitial ad is not ready yet";
            }
        }

        public void DestroyInterstitialAd()
        {
            if (interstitialAd != null)
            {
                interstitialAd.Destroy();
            }
        }

        #endregion

        #region REWARDED ADS

        public void RequestAndLoadRewardedAd()
        {
            statusText.text = "Requesting Rewarded Ad.";
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/5224354917";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/1712485313";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // create new rewarded ad instance
            rewardedAd = new RewardedAd(adUnitId);

            // Add Event Handlers
            rewardedAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            rewardedAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            rewardedAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            rewardedAd.OnAdFailedToShow += (sender, args) => OnAdFailedToShowEvent.Invoke();
            rewardedAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();
            rewardedAd.OnUserEarnedReward += (sender, args) => OnUserEarnedRewardEvent.Invoke();

            // Create empty ad request
            rewardedAd.LoadAd(CreateAdRequest());
        }

        public void ShowRewardedAd()
        {
            if (rewardedAd != null)
            {
                rewardedAd.Show();
            }
            else
            {
                statusText.text = "Rewarded ad is not ready yet.";
            }
        }

        public void RequestAndLoadRewardedInterstitialAd()
        {
            statusText.text = "Requesting Rewarded Interstitial Ad.";

            // These ad units are configured to always serve test ads.
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
                string adUnitId = "ca-app-pub-3940256099942544/5354046379";
    #elif UNITY_IPHONE
                string adUnitId = "ca-app-pub-3940256099942544/6978759866";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Create an interstitial.
            RewardedInterstitialAd.LoadAd(adUnitId, CreateAdRequest(), (rewardedInterstitialAd, error) =>
            {
                if (error != null)
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "RewardedInterstitialAd load failed, error: " + error;
                    });
                    return;
                }
                this.rewardedInterstitialAd = rewardedInterstitialAd;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "RewardedInterstitialAd loaded";
                });
                // Register for ad events.
                this.rewardedInterstitialAd.OnAdDidPresentFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial presented.";
                    });
                };
                this.rewardedInterstitialAd.OnAdDidDismissFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial dismissed.";
                    });
                    this.rewardedInterstitialAd = null;
                };
                this.rewardedInterstitialAd.OnAdFailedToPresentFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial failed to present.";
                    });
                    this.rewardedInterstitialAd = null;
                };
            });
        }

        public void ShowRewardedInterstitialAd()
        {
            if (rewardedInterstitialAd != null)
            {
                rewardedInterstitialAd.Show((reward) => {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "User Rewarded: " + reward.Amount;
                    });
                });
            }
            else
            {
                statusText.text = "Rewarded ad is not ready yet.";
            }
        }

        #endregion

        #region APPOPEN ADS

        public void RequestAndLoadAppOpenAd()
        {
            statusText.text = "Requesting App Open Ad.";
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/3419835294";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/5662855259";
    #else
            string adUnitId = "unexpected_platform";
    #endif
            // create new app open ad instance
            AppOpenAd.LoadAd(adUnitId, ScreenOrientation.Portrait, CreateAdRequest(), (appOpenAd, error) =>
            {
                if (error != null)
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "AppOpenAd load failed, error: " + error;
                    });
                    return;
                }
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "AppOpenAd loaded. Please background the app and return.";
                });
                this.appOpenAd = appOpenAd;
            });
        }

        public void ShowAppOpenAd()
        {
            if (isShowingAppOpenAd)
            {
                return;
            }
            if (appOpenAd == null)
            {
                return;
            }
            // Register for ad events.
            this.appOpenAd.OnAdDidDismissFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = false;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd dismissed.");
                    if (this.appOpenAd != null)
                    {
                        this.appOpenAd.Destroy();
                        this.appOpenAd = null;
                    }
                });
            };
            this.appOpenAd.OnAdFailedToPresentFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = false;
                var msg = args.AdError.GetMessage();
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "AppOpenAd present failed, error: " + msg;
                    if (this.appOpenAd != null)
                    {
                        this.appOpenAd.Destroy();
                        this.appOpenAd = null;
                    }
                });
            };
            this.appOpenAd.OnAdDidPresentFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = true;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd presented.");
                });
            };
            this.appOpenAd.OnAdDidRecordImpression += (sender, args) =>
            {
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd recorded an impression.");
                });
            };
            this.appOpenAd.OnPaidEvent += (sender, args) =>
            {
                string currencyCode = args.AdValue.CurrencyCode;
                long adValue = args.AdValue.Value;
                string suffix = "AppOpenAd received a paid event.";
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    string msg = string.Format("{0} (currency: {1}, value: {2}", suffix, currencyCode, adValue);
                    statusText.text = msg;
                });
            };
            appOpenAd.Show();
        }

        #endregion

        #region AD INSPECTOR

        public void OpenAdInspector()
        {
            statusText.text = "Open Ad Inspector.";

            MobileAds.OpenAdInspector((error) =>
            {
                if (error != null)
                {
                    string errorMessage = error.GetMessage();
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Ad Inspector failed to open, error: " + errorMessage;
                    });
                }
                else
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Ad Inspector closed.";
                    });
                }
            });
        }

        #endregion
    }
</code>```

答:
There were two things wrong. One, I was using my live adUnit ID not the test one. The second issue was I was calling the load and show methods at the same time which worked in Unity, but on Android it seems there needs to be more time for the ad to load.

What I did to get the test ads on mobile device:

Set up the test device like HTugsadK said https://support.google.com/admob/answer/9691433

Change the adUnitId in RequestAndLoadInterstitialAd() to the interstitial test ID from here https://developers.google.com/admob/unity/test-ads#add_your_test_device_programmatically
For production this should be changed back to the real adUnitId.

Change the end of the RequestAndLoadInterstitialAd() method and Invoke the show method with a 5 second delay. Now in your event you only have to call this method.

```<code> public void RequestAndLoadInterstitialAd()
     {
         // statusText.text = "Requesting Interstitial Ad.";

 #if UNITY_EDITOR
         string adUnitId = "unused";
 #elif UNITY_ANDROID
         string adUnitId = "ca-app-pub-3940256099942544/1033173712";
 #elif UNITY_IPHONE
         string adUnitId = "ca-app-pub-3940256099942544/4411468910";
 #else
         string adUnitId = "unexpected_platform";
 #endif

         // Clean up interstitial before using it
         if (interstitialAd != null)
         {
             interstitialAd.Destroy();
         }
         interstitialAd = new InterstitialAd(adUnitId);

         // Add Event Handlers
         interstitialAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
         interstitialAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
         interstitialAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
         interstitialAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

         // Load an interstitial ad
         interstitialAd.LoadAd(CreateAdRequest());
         Invoke("ShowInterstitialAd", 5);
     }
</code>```

Body:
My admob account is linked to the app in play store, status "ready", AdMob app ID also added into ad settings in Unity, added in the real ad unit ID, test ad showing in Unity, waited a week...

Result: no real ads

My event is calling RequestAndLoadInterstitialAd() and ShowInterstitialAd(), which works in Unity with the test ad. I expected it to work once the test ad implemented successfully.

    using UnityEngine.Events;
    using UnityEngine;
    using GoogleMobileAds.Api;
    using GoogleMobileAds.Common;
    using UnityEngine.UI;
    using System;
    using System.Collections.Generic;

    public class GoogleAdMobController : MonoBehaviour
    {
        private AppOpenAd appOpenAd;
        private BannerView bannerView;
        private InterstitialAd interstitialAd;
        private RewardedAd rewardedAd;
        private RewardedInterstitialAd rewardedInterstitialAd;
        private float deltaTime;
        private bool isShowingAppOpenAd;
        public UnityEvent OnAdLoadedEvent;
        public UnityEvent OnAdFailedToLoadEvent;
        public UnityEvent OnAdOpeningEvent;
        public UnityEvent OnAdFailedToShowEvent;
        public UnityEvent OnUserEarnedRewardEvent;
        public UnityEvent OnAdClosedEvent;
        public bool showFpsMeter = true;
        public Text fpsMeter;
        public Text statusText;

        #region UNITY MONOBEHAVIOR METHODS

        public void Start()
        {
            MobileAds.SetiOSAppPauseOnBackground(true);

            List<String> deviceIds = new List<String>() { AdRequest.TestDeviceSimulator };

            // Add some test device IDs (replace with your own device IDs).
    #if UNITY_IPHONE
            deviceIds.Add("b77a5c561934e089)--a185c62eba2497c95197140e5282b27a");
    #elif UNITY_ANDROID
            deviceIds.Add("b77a5c561934e089)--a185c62eba2497c95197140e5282b27a");
    #endif

            // Configure TagForChildDirectedTreatment and test device IDs.
            RequestConfiguration requestConfiguration =
                new RequestConfiguration.Builder()
                .SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.Unspecified)
                .SetTestDeviceIds(deviceIds).build();
            MobileAds.SetRequestConfiguration(requestConfiguration);

            // Initialize the Google Mobile Ads SDK.
            MobileAds.Initialize(HandleInitCompleteAction);
        }

        private void HandleInitCompleteAction(InitializationStatus initstatus)
        {
            // Callbacks from GoogleMobileAds are not guaranteed to be called on
            // main thread.
            // In this example we use MobileAdsEventExecutor to schedule these calls on
            // the next Update() loop.
            MobileAdsEventExecutor.ExecuteInUpdate(() =>
            {
                statusText.text = "Initialization complete";
            //  RequestBannerAd();
            });
        }

        private void Update()
        {
            if (showFpsMeter)
            {
                fpsMeter.gameObject.SetActive(true);
                deltaTime += (Time.deltaTime - deltaTime) * 0.1f;
                float fps = 1.0f / deltaTime;
                fpsMeter.text = string.Format("{0:0.} fps", fps);
            }
            else
            {
                fpsMeter.gameObject.SetActive(false);
            }
        }

        #endregion

        #region HELPER METHODS

        private AdRequest CreateAdRequest()
        {
            return new AdRequest.Builder()
                .AddKeyword("unity-admob-sample")
                .Build();
        }

        public void OnApplicationPause(bool paused)
        {
            // Display the app open ad when the app is foregrounded.
            if (!paused)
            {
                ShowAppOpenAd();
            }
        }

        #endregion

        #region BANNER ADS

        public void RequestBannerAd()
        {
            statusText.text = "Requesting Banner Ad.";

            // These ad units are configured to always serve test ads.
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/6300978111";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/2934735716";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Clean up banner before reusing
            if (bannerView != null)
            {
                bannerView.Destroy();
            }

            // Create a 320x50 banner at top of the screen
            bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Top);

            // Add Event Handlers
            bannerView.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            bannerView.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            bannerView.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            bannerView.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

            // Load a banner ad
            bannerView.LoadAd(CreateAdRequest());
        }

        public void DestroyBannerAd()
        {
            if (bannerView != null)
            {
                bannerView.Destroy();
            }
        }

        #endregion

        #region INTERSTITIAL ADS

        public void RequestAndLoadInterstitialAd()
        {
            // statusText.text = "Requesting Interstitial Ad.";

    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-2334240444886107/9358512518";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/4411468910";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Clean up interstitial before using it
            if (interstitialAd != null)
            {
                interstitialAd.Destroy();
            }
            interstitialAd = new InterstitialAd(adUnitId);

            // Add Event Handlers
            interstitialAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            interstitialAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            interstitialAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            interstitialAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

            // Load an interstitial ad
            interstitialAd.LoadAd(CreateAdRequest());
        }

        public void ShowInterstitialAd()
        {
            if (interstitialAd.IsLoaded())
            {
                interstitialAd.Show();
            }
            else
            {
                statusText.text = "Interstitial ad is not ready yet";
            }
        }

        public void DestroyInterstitialAd()
        {
            if (interstitialAd != null)
            {
                interstitialAd.Destroy();
            }
        }

        #endregion

        #region REWARDED ADS

        public void RequestAndLoadRewardedAd()
        {
            statusText.text = "Requesting Rewarded Ad.";
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/5224354917";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/1712485313";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // create new rewarded ad instance
            rewardedAd = new RewardedAd(adUnitId);

            // Add Event Handlers
            rewardedAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            rewardedAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            rewardedAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            rewardedAd.OnAdFailedToShow += (sender, args) => OnAdFailedToShowEvent.Invoke();
            rewardedAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();
            rewardedAd.OnUserEarnedReward += (sender, args) => OnUserEarnedRewardEvent.Invoke();

            // Create empty ad request
            rewardedAd.LoadAd(CreateAdRequest());
        }

        public void ShowRewardedAd()
        {
            if (rewardedAd != null)
            {
                rewardedAd.Show();
            }
            else
            {
                statusText.text = "Rewarded ad is not ready yet.";
            }
        }

        public void RequestAndLoadRewardedInterstitialAd()
        {
            statusText.text = "Requesting Rewarded Interstitial Ad.";

            // These ad units are configured to always serve test ads.
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
                string adUnitId = "ca-app-pub-3940256099942544/5354046379";
    #elif UNITY_IPHONE
                string adUnitId = "ca-app-pub-3940256099942544/6978759866";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Create an interstitial.
            RewardedInterstitialAd.LoadAd(adUnitId, CreateAdRequest(), (rewardedInterstitialAd, error) =>
            {
                if (error != null)
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "RewardedInterstitialAd load failed, error: " + error;
                    });
                    return;
                }
                this.rewardedInterstitialAd = rewardedInterstitialAd;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "RewardedInterstitialAd loaded";
                });
                // Register for ad events.
                this.rewardedInterstitialAd.OnAdDidPresentFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial presented.";
                    });
                };
                this.rewardedInterstitialAd.OnAdDidDismissFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial dismissed.";
                    });
                    this.rewardedInterstitialAd = null;
                };
                this.rewardedInterstitialAd.OnAdFailedToPresentFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial failed to present.";
                    });
                    this.rewardedInterstitialAd = null;
                };
            });
        }

        public void ShowRewardedInterstitialAd()
        {
            if (rewardedInterstitialAd != null)
            {
                rewardedInterstitialAd.Show((reward) => {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "User Rewarded: " + reward.Amount;
                    });
                });
            }
            else
            {
                statusText.text = "Rewarded ad is not ready yet.";
            }
        }

        #endregion

        #region APPOPEN ADS

        public void RequestAndLoadAppOpenAd()
        {
            statusText.text = "Requesting App Open Ad.";
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/3419835294";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/5662855259";
    #else
            string adUnitId = "unexpected_platform";
    #endif
            // create new app open ad instance
            AppOpenAd.LoadAd(adUnitId, ScreenOrientation.Portrait, CreateAdRequest(), (appOpenAd, error) =>
            {
                if (error != null)
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "AppOpenAd load failed, error: " + error;
                    });
                    return;
                }
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "AppOpenAd loaded. Please background the app and return.";
                });
                this.appOpenAd = appOpenAd;
            });
        }

        public void ShowAppOpenAd()
        {
            if (isShowingAppOpenAd)
            {
                return;
            }
            if (appOpenAd == null)
            {
                return;
            }
            // Register for ad events.
            this.appOpenAd.OnAdDidDismissFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = false;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd dismissed.");
                    if (this.appOpenAd != null)
                    {
                        this.appOpenAd.Destroy();
                        this.appOpenAd = null;
                    }
                });
            };
            this.appOpenAd.OnAdFailedToPresentFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = false;
                var msg = args.AdError.GetMessage();
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "AppOpenAd present failed, error: " + msg;
                    if (this.appOpenAd != null)
                    {
                        this.appOpenAd.Destroy();
                        this.appOpenAd = null;
                    }
                });
            };
            this.appOpenAd.OnAdDidPresentFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = true;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd presented.");
                });
            };
            this.appOpenAd.OnAdDidRecordImpression += (sender, args) =>
            {
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd recorded an impression.");
                });
            };
            this.appOpenAd.OnPaidEvent += (sender, args) =>
            {
                string currencyCode = args.AdValue.CurrencyCode;
                long adValue = args.AdValue.Value;
                string suffix = "AppOpenAd received a paid event.";
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    string msg = string.Format("{0} (currency: {1}, value: {2}", suffix, currencyCode, adValue);
                    statusText.text = msg;
                });
            };
            appOpenAd.Show();
        }

        #endregion

        #region AD INSPECTOR

        public void OpenAdInspector()
        {
            statusText.text = "Open Ad Inspector.";

            MobileAds.OpenAdInspector((error) =>
            {
                if (error != null)
                {
                    string errorMessage = error.GetMessage();
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Ad Inspector failed to open, error: " + errorMessage;
                    });
                }
                else
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Ad Inspector closed.";
                    });
                }
            });
        }

        #endregion
    }

Body:
There were two things wrong. One, I was using my live adUnit ID not the test one. The second issue was I was calling the load and show methods at the same time which worked in Unity, but on Android it seems there needs to be more time for the ad to load.

What I did to get the test ads on mobile device:

Set up the test device like HTugsadK said https://support.google.com/admob/answer/9691433

Change the adUnitId in RequestAndLoadInterstitialAd() to the interstitial test ID from here https://developers.google.com/admob/unity/test-ads#add_your_test_device_programmatically
For production this should be changed back to the real adUnitId.

Change the end of the RequestAndLoadInterstitialAd() method and Invoke the show method with a 5 second delay. Now in your event you only have to call this method.

 public void RequestAndLoadInterstitialAd()
     {
         // statusText.text = "Requesting Interstitial Ad.";

 #if UNITY_EDITOR
         string adUnitId = "unused";
 #elif UNITY_ANDROID
         string adUnitId = "ca-app-pub-3940256099942544/1033173712";
 #elif UNITY_IPHONE
         string adUnitId = "ca-app-pub-3940256099942544/4411468910";
 #else
         string adUnitId = "unexpected_platform";
 #endif

         // Clean up interstitial before using it
         if (interstitialAd != null)
         {
             interstitialAd.Destroy();
         }
         interstitialAd = new InterstitialAd(adUnitId);

         // Add Event Handlers
         interstitialAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
         interstitialAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
         interstitialAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
         interstitialAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

         // Load an interstitial ad
         interstitialAd.LoadAd(CreateAdRequest());
         Invoke("ShowInterstitialAd", 5);
     }


问:
TLS/SSL client authentication using a client certificate which comes available at runtime Android/Java
Suppose I have an application which in some way retrieves a client certificate (private/public key pair) at runtime via a secure channel (so I don't have this client certificate at build time).

How can I use this client certificate for client authentication without using keytool and not using some on persistent/ondisk keystore. So I do not want (actually I can't) to import it using a command line keytool?

Actually I want to replicate the functionality done in libcurl. You just set the client certificate (with private key) and your done. It doesn't involve a keystore.

All this has to be done in Java/Android.

答: You can do it in Java by defining your own KeyManager as described in the JSSE Reference Guide. I can't speak for Android.


问:
Encrypt the password in selenium robot framework
I would like to encrypt my password, how is it possible in robot framework+selenium+python?

I am taking password from excel. any pointers will be helpful.

答:
You can use b64encode   to encode the password
but you have to provide the real password once to encode it, once it is encrypted you can use it right away

Encrypt the password :

```<code>password= abc123
${encryptedPassword}    b64encode    ${password}
log to console  ${encryptedPassword}
</code>```

Use the Encrypted password

```<code>${password} = <Paste The encrypted password here>
${password1}    b64decode  ${password}
input text ${xpath}  ${password1}
</code>```

Body:
You can use b64encode   to encode the password
but you have to provide the real password once to encode it, once it is encrypted you can use it right away

Encrypt the password :

password= abc123
${encryptedPassword}    b64encode    ${password}
log to console  ${encryptedPassword}

Use the Encrypted password

${password} = <Paste The encrypted password here>
${password1}    b64decode  ${password}
input text ${xpath}  ${password1}


问:
Optaplanner - ConstructionHeuristics find a feasible solution before all planning entity get initialized
I have this setting:

%test.quarkus.optaplanner.solver.termination.best-score-limit=0hard/*soft

In ConstructionHeuristics phase, if optaplanner get a 0 HARD score (feasible solution) before assigning all planning entities an initial value, then it becomes infeasible again (-1 HARD) after assigning more planning entities initial value, I noticed when the construction heuristics phase ends, optaplanner will not do LOCAL SEARCH and just report the infeasible solution as final best solution.

Shouldn't the final best solution be the one after all planning entities got assigned a value and starts from there to check whether to terminate the search?

I even have hard constraints to not allow any Planning entities to have null planning variable. but before the planning entity got initialized in Construction Heuristics phase, the hard constraint does not seem to kick in.

Is there a way to add a constraint for uninitialized planning entity?
How to let optaplanner to take the final best solution only after all planning entities are initialized?

Here are the logs I see in my case:

```<code>2022-02-09 14:20:05,126 INFO  [org.opt.cor.imp.sol.DefaultSolver] (pool-9-thread-1) Solving started: time spent (90), best score (-30init/0hard/0soft), environment mode (REPRODUCIBLE), move thread count (NONE), random (JDK with seed 0).
2022-02-09 14:20:05,198 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (0), time spent (170), score (-28init/-2hard/-5soft), selected move count (32), picked move ([a.0 {null -> MANUAL_ASSEMBLY}, a.0 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,247 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (1), time spent (219), score (-26init/-1hard/-5soft), selected move count (33), picked move ([f.4 {null -> MANUAL_ASSEMBLY}, f.4 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,286 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (2), time spent (258), score (-24init/-1hard/-5soft), selected move count (34), picked move ([2.f {null -> MANUAL_ASSEMBLY}, 2.f {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,315 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (3), time spent (287), score (-22init/-1hard/-4soft), selected move count (35), picked move ([9.8 {null -> MANUAL_ASSEMBLY}, 9.8 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,338 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (4), time spent (310), score (-20init/-1hard/-4soft), selected move count (36), picked move ([6.c {null -> MANUAL_ASSEMBLY}, 6.c {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,362 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (5), time spent (334), score (-18init/-1hard/-4soft), selected move count (37), picked move ([8.3 {null -> MANUAL_ASSEMBLY}, 8.3 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,384 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (6), time spent (356), score (-16init/-1hard/-4soft), selected move count (38), picked move ([f.2 {null -> MANUAL_ASSEMBLY}, f.2 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,400 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (7), time spent (372), score (-14init/-1hard/-3soft), selected move count (39), picked move ([4.6 {null -> MANUAL_ASSEMBLY}, 4.6 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,415 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (8), time spent (387), score (-12init/-1hard/-3soft), selected move count (40), picked move ([8.2 {null -> MANUAL_ASSEMBLY}, 8.2 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,428 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (9), time spent (400), score (-10init/0hard/-3soft), selected move count (41), picked move ([a.4 {null -> MANUAL_ASSEMBLY}, a.4 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,440 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (10), time spent (412), score (-8init/0hard/-2soft), selected move count (42), picked move ([4.5 {null -> MANUAL_ASSEMBLY}, 4.5 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,453 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (11), time spent (425), score (-6init/0hard/-2soft), selected move count (43), picked move ([5.d {null -> MANUAL_ASSEMBLY}, 5.d {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,474 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (12), time spent (446), score (-4init/0hard/-2soft), selected move count (44), picked move ([8.a {null -> MANUAL_ASSEMBLY}, 8.a {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,501 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (13), time spent (473), score (-2init/0hard/-2soft), selected move count (45), picked move ([6.3 {null -> MANUAL_ASSEMBLY}, 6.3 {null -> a.0}]).
2022-02-09 14:20:05,530 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (14), time spent (502), score (-1hard/-2soft), selected move count (46), picked move ([3.b {null -> MANUAL_ASSEMBLY}, 3.b {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,532 INFO  [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1) Construction Heuristic phase (0) ended: time spent (504), best score (-1hard/-2soft), score calculation speed (1446/sec), step total (15).
2022-02-09 14:20:05,641 DEBUG [org.opt.cor.imp.loc.DefaultLocalSearchPhase] (pool-9-thread-1)     LS step (0), time spent (613), score (0hard/-2soft), new best score (0hard/-2soft), accepted/selected move count (100/100), picked move ([a.0..6.3] {f.4} <-reversing-> [8.2..f.2] {a.4}).
2022-02-09 14:20:05,642 INFO  [org.opt.cor.imp.loc.DefaultLocalSearchPhase] (pool-9-thread-1) Local Search phase (1) ended: time spent (614), best score (0hard/-2soft), score calculation speed (1010/sec), step total (1).
2022-02-09 14:20:05,644 INFO  [org.opt.cor.imp.sol.DefaultSolver] (pool-9-thread-1) Solving ended: time spent (614), best score (0hard/-2soft), score calculation speed (1120/sec), phase total (2), environment mode (REPRODUCIBLE), move thread count (NONE).
Explanation of score (-1hard/-2soft):
</code>```

From the log, it says "Construction Heuristic phase (0) ended: time spent (504), best score (-1hard/-2soft)" but why LOCAL SEARCH remembers the best score as "new best score (0hard/-2soft)" and then stopped, but reporting finalbestsolution with "Explanation of score (-1hard/-2soft)"?

答:
The score is feasible only if the hard score is >= 0 and the solution has been fully initialized. For example, a solution represented by the score (-2init/0hard/-2soft) is NOT feasible, as there are two planning entities that have not been initialized yet.

According to the log you provided, the construction heuristic initialized the solution with a score (-1hard/-2soft). Then, the local search improved the solution further to the score (0hard/-2soft) and the solver terminated as the termination condition was met.

As for the "Explanation of score" in the log; I don't think it comes from the solver run itself. Are you by any chance using ScoreManager to explain the solution?

Can you verify what the score is for the best solution you receive after the solver terminates?

Body:
I have this setting:

%test.quarkus.optaplanner.solver.termination.best-score-limit=0hard/*soft

In ConstructionHeuristics phase, if optaplanner get a 0 HARD score (feasible solution) before assigning all planning entities an initial value, then it becomes infeasible again (-1 HARD) after assigning more planning entities initial value, I noticed when the construction heuristics phase ends, optaplanner will not do LOCAL SEARCH and just report the infeasible solution as final best solution.

Shouldn't the final best solution be the one after all planning entities got assigned a value and starts from there to check whether to terminate the search?

I even have hard constraints to not allow any Planning entities to have null planning variable. but before the planning entity got initialized in Construction Heuristics phase, the hard constraint does not seem to kick in.

Is there a way to add a constraint for uninitialized planning entity?
How to let optaplanner to take the final best solution only after all planning entities are initialized?

Here are the logs I see in my case:

2022-02-09 14:20:05,126 INFO  [org.opt.cor.imp.sol.DefaultSolver] (pool-9-thread-1) Solving started: time spent (90), best score (-30init/0hard/0soft), environment mode (REPRODUCIBLE), move thread count (NONE), random (JDK with seed 0).
2022-02-09 14:20:05,198 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (0), time spent (170), score (-28init/-2hard/-5soft), selected move count (32), picked move ([a.0 {null -> MANUAL_ASSEMBLY}, a.0 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,247 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (1), time spent (219), score (-26init/-1hard/-5soft), selected move count (33), picked move ([f.4 {null -> MANUAL_ASSEMBLY}, f.4 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,286 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (2), time spent (258), score (-24init/-1hard/-5soft), selected move count (34), picked move ([2.f {null -> MANUAL_ASSEMBLY}, 2.f {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,315 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (3), time spent (287), score (-22init/-1hard/-4soft), selected move count (35), picked move ([9.8 {null -> MANUAL_ASSEMBLY}, 9.8 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,338 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (4), time spent (310), score (-20init/-1hard/-4soft), selected move count (36), picked move ([6.c {null -> MANUAL_ASSEMBLY}, 6.c {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,362 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (5), time spent (334), score (-18init/-1hard/-4soft), selected move count (37), picked move ([8.3 {null -> MANUAL_ASSEMBLY}, 8.3 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,384 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (6), time spent (356), score (-16init/-1hard/-4soft), selected move count (38), picked move ([f.2 {null -> MANUAL_ASSEMBLY}, f.2 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,400 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (7), time spent (372), score (-14init/-1hard/-3soft), selected move count (39), picked move ([4.6 {null -> MANUAL_ASSEMBLY}, 4.6 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,415 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (8), time spent (387), score (-12init/-1hard/-3soft), selected move count (40), picked move ([8.2 {null -> MANUAL_ASSEMBLY}, 8.2 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,428 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (9), time spent (400), score (-10init/0hard/-3soft), selected move count (41), picked move ([a.4 {null -> MANUAL_ASSEMBLY}, a.4 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,440 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (10), time spent (412), score (-8init/0hard/-2soft), selected move count (42), picked move ([4.5 {null -> MANUAL_ASSEMBLY}, 4.5 {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,453 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (11), time spent (425), score (-6init/0hard/-2soft), selected move count (43), picked move ([5.d {null -> MANUAL_ASSEMBLY}, 5.d {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,474 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (12), time spent (446), score (-4init/0hard/-2soft), selected move count (44), picked move ([8.a {null -> MANUAL_ASSEMBLY}, 8.a {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,501 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (13), time spent (473), score (-2init/0hard/-2soft), selected move count (45), picked move ([6.3 {null -> MANUAL_ASSEMBLY}, 6.3 {null -> a.0}]).
2022-02-09 14:20:05,530 DEBUG [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1)     CH step (14), time spent (502), score (-1hard/-2soft), selected move count (46), picked move ([3.b {null -> MANUAL_ASSEMBLY}, 3.b {null -> Inve.0/0-0}]).
2022-02-09 14:20:05,532 INFO  [org.opt.cor.imp.con.DefaultConstructionHeuristicPhase] (pool-9-thread-1) Construction Heuristic phase (0) ended: time spent (504), best score (-1hard/-2soft), score calculation speed (1446/sec), step total (15).
2022-02-09 14:20:05,641 DEBUG [org.opt.cor.imp.loc.DefaultLocalSearchPhase] (pool-9-thread-1)     LS step (0), time spent (613), score (0hard/-2soft), new best score (0hard/-2soft), accepted/selected move count (100/100), picked move ([a.0..6.3] {f.4} <-reversing-> [8.2..f.2] {a.4}).
2022-02-09 14:20:05,642 INFO  [org.opt.cor.imp.loc.DefaultLocalSearchPhase] (pool-9-thread-1) Local Search phase (1) ended: time spent (614), best score (0hard/-2soft), score calculation speed (1010/sec), step total (1).
2022-02-09 14:20:05,644 INFO  [org.opt.cor.imp.sol.DefaultSolver] (pool-9-thread-1) Solving ended: time spent (614), best score (0hard/-2soft), score calculation speed (1120/sec), phase total (2), environment mode (REPRODUCIBLE), move thread count (NONE).
Explanation of score (-1hard/-2soft):

From the log, it says "Construction Heuristic phase (0) ended: time spent (504), best score (-1hard/-2soft)" but why LOCAL SEARCH remembers the best score as "new best score (0hard/-2soft)" and then stopped, but reporting finalbestsolution with "Explanation of score (-1hard/-2soft)"?


问:
How to check the percentage of downloaded files
I use selenium to get reports. I wrote the following code to check if the report was received.

```<code>    # switch to new tab
    driver.switch_to.window(driver.window_handles[-1])
    # navigate to chrome downloads
    driver.get('chrome://downloads')
    # define the endTime
    endTime = time.time()+20
    downloadPercentage = driver.execute_script(
                "return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value")
    print(downloadPercentage)
</code>```

But on the last line I get the following error

```<code>selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'value' of null
</code>```

答:
I use another solution.
As soon as download started I switch to edge://download (chrome://download) page and start parsing it regularly (i.e. once in 3 seconds) waiting till "Cancel" or "Pause" title disappears.
When these words disappear (in fact converts to "Show in folder") it means the file has been downloaded.</p>

Body:
I use selenium to get reports. I wrote the following code to check if the report was received.

    # switch to new tab
    driver.switch_to.window(driver.window_handles[-1])
    # navigate to chrome downloads
    driver.get('chrome://downloads')
    # define the endTime
    endTime = time.time()+20
    downloadPercentage = driver.execute_script(
                "return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value")
    print(downloadPercentage)

But on the last line I get the following error

selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'value' of null


答:
If you want to keep your original ordering</p>
```<code>tmp=df$ID[!duplicated(df$ID)]
match(df$ID,tmp)

 [1]  1  2  3  4  5  6  7  7  5  1  2  1  3  8  9 10 11 12 13 13
</code>```

Title: r create a unique numeric value for every id in column

Body:
I have a dataset with a long list of random IDs like this.

 ID
 H001
 H00A
 H00M
 B00A
 BB0B
 AB0A
 AA0B
 AA0B
 BB0B
 H001
 H00A
 H001
 H00M
 H00Z
 CC01
 CD01
 CC02
 XT01
 XT0A
 XT0A

I like to create a new column with numeric values for each ID.  The final dataset would appear like this.

 ID      NumId
 H001    1
 H00A    2
 H00M    3
 B00A    4
 BB0B    5
 AB0A    6
 AA0B    7
 AA0B    7
 BB0B    5
 H001    1
 H00A    2
 H001    1
 H00M    3
 H00Z    8
 CC01    9
 CD01    10
 CC02    11
 XT01    12
 XT0A    13
 XT0A    13

Any suggestions on how to create a numerically equivalent column is much appreciated thanks.

Body:
If you want to keep your original ordering

tmp=df$ID[!duplicated(df$ID)]
match(df$ID,tmp)

 [1]  1  2  3  4  5  6  7  7  5  1  2  1  3  8  9 10 11 12 13 13


问:
XMLHttpRequest return from a function before response is back
I have a function as the code below, I am trying to send a file through XMLHttpRequest to the server and then store it in DB and retrieve the id of the file in DB and make an object of ids.
The problem is that the function exits a lot before I got the response back from the server to store it in the object therefore the object doesn't store those values.
I know that I need make the XHR asynchronous but it doesn't change the result, I have also tried timeout or using a different platform like Ajax but still, it didn't work.

```<code>async function getFileObj() {
    var FileObject = {}
    for (let key1 in PObj) {
        FileObject[key1] = {}
        for (let key2 in PObj[key1]) {
            FileObject[key1][key2] = {}
            for (let key3 in PObj[key1][key2]) {
                const formData = new FormData();
                formData.append('myFile.png', filesObjDB[key1][key2][key3]);

                var xhr = new XMLHttpRequest();
                xhr.open("POST", 'url', true);
                xhr.onreadystatechange = async function() {
                    if (this.readyState === XMLHttpRequest.DONE && this.status === 200)
                        var id = await xhr.response.text();
                        FileObject[key1][key2][key3] = parseInt(id)
                }
                xhr.responseType = 'blob';
                xhr.send(formData);
            }
        }
    }
    return FileObject;
}
</code>```

Help would be very appreciated!

答:
You are not awaiting the request. To make the existing code wait for the result, you'd need to wrap the outdated callback-based code in a promise and await that (and also I don't think getting the response text of an XHR works as you showed, I changed it now):

// This is just to demonstrate what was immediately wrong
// with the existing code - it's not the best solution! See below.

FileObject[key1][key2][key3] = await new Promise((resolve, reject) => {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
      var id = xhr.responseText;
      resolve(parseInt(id));
    }
  };
  xhr.send(formData);
});
```
<p>Note there is no error handling yet, if the request fails everything will just hang.</p>
<p>But at that point, it doesn't actually make sense to use XHR in the first place! <strong>It's a lot more straightforward to use <code>fetch</code>, which has a promise API out of the box</strong>:</p>
<pre class="lang-js prettyprint-override"><code>const response = await fetch(url, { method: 'POST', body: formData })
FileObject[key1][key2][key3] = parseInt(await response.text())
</code>```

Body:
I have a function as the code below, I am trying to send a file through XMLHttpRequest to the server and then store it in DB and retrieve the id of the file in DB and make an object of ids.
The problem is that the function exits a lot before I got the response back from the server to store it in the object therefore the object doesn't store those values.
I know that I need make the XHR asynchronous but it doesn't change the result, I have also tried timeout or using a different platform like Ajax but still, it didn't work.

async function getFileObj() {
    var FileObject = {}
    for (let key1 in PObj) {
        FileObject[key1] = {}
        for (let key2 in PObj[key1]) {
            FileObject[key1][key2] = {}
            for (let key3 in PObj[key1][key2]) {
                const formData = new FormData();
                formData.append('myFile.png', filesObjDB[key1][key2][key3]);

                var xhr = new XMLHttpRequest();
                xhr.open("POST", 'url', true);
                xhr.onreadystatechange = async function() {
                    if (this.readyState === XMLHttpRequest.DONE && this.status === 200)
                        var id = await xhr.response.text();
                        FileObject[key1][key2][key3] = parseInt(id)
                }
                xhr.responseType = 'blob';
                xhr.send(formData);
            }
        }
    }
    return FileObject;
}

Help would be very appreciated!

Body:
You are not awaiting the request. To make the existing code wait for the result, you'd need to wrap the outdated callback-based code in a promise and await that (and also I don't think getting the response text of an XHR works as you showed, I changed it now):

// This is just to demonstrate what was immediately wrong
// with the existing code - it's not the best solution! See below.

FileObject[key1][key2][key3] = await new Promise((resolve, reject) => {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
      var id = xhr.responseText;
      resolve(parseInt(id));
    }
  };
  xhr.send(formData);
});

Note there is no error handling yet, if the request fails everything will just hang.

But at that point, it doesn't actually make sense to use XHR in the first place! It's a lot more straightforward to use fetch, which has a promise API out of the box:

const response = await fetch(url, { method: 'POST', body: formData })
FileObject[key1][key2][key3] = parseInt(await response.text())